xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision e5c37958f901cc9bec50624dbee85d40143e4bca)
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/TargetFrameLowering.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/CodeGen/WinEHFuncInfo.h"
65 #include "llvm/IR/Argument.h"
66 #include "llvm/IR/Attributes.h"
67 #include "llvm/IR/BasicBlock.h"
68 #include "llvm/IR/CFG.h"
69 #include "llvm/IR/CallSite.h"
70 #include "llvm/IR/CallingConv.h"
71 #include "llvm/IR/Constant.h"
72 #include "llvm/IR/ConstantRange.h"
73 #include "llvm/IR/Constants.h"
74 #include "llvm/IR/DataLayout.h"
75 #include "llvm/IR/DebugInfoMetadata.h"
76 #include "llvm/IR/DebugLoc.h"
77 #include "llvm/IR/DerivedTypes.h"
78 #include "llvm/IR/Function.h"
79 #include "llvm/IR/GetElementPtrTypeIterator.h"
80 #include "llvm/IR/InlineAsm.h"
81 #include "llvm/IR/InstrTypes.h"
82 #include "llvm/IR/Instruction.h"
83 #include "llvm/IR/Instructions.h"
84 #include "llvm/IR/IntrinsicInst.h"
85 #include "llvm/IR/Intrinsics.h"
86 #include "llvm/IR/LLVMContext.h"
87 #include "llvm/IR/Metadata.h"
88 #include "llvm/IR/Module.h"
89 #include "llvm/IR/Operator.h"
90 #include "llvm/IR/PatternMatch.h"
91 #include "llvm/IR/Statepoint.h"
92 #include "llvm/IR/Type.h"
93 #include "llvm/IR/User.h"
94 #include "llvm/IR/Value.h"
95 #include "llvm/MC/MCContext.h"
96 #include "llvm/MC/MCSymbol.h"
97 #include "llvm/Support/AtomicOrdering.h"
98 #include "llvm/Support/BranchProbability.h"
99 #include "llvm/Support/Casting.h"
100 #include "llvm/Support/CodeGen.h"
101 #include "llvm/Support/CommandLine.h"
102 #include "llvm/Support/Compiler.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Support/ErrorHandling.h"
105 #include "llvm/Support/MachineValueType.h"
106 #include "llvm/Support/MathExtras.h"
107 #include "llvm/Support/raw_ostream.h"
108 #include "llvm/Target/TargetIntrinsicInfo.h"
109 #include "llvm/Target/TargetMachine.h"
110 #include "llvm/Target/TargetOptions.h"
111 #include <algorithm>
112 #include <cassert>
113 #include <cstddef>
114 #include <cstdint>
115 #include <cstring>
116 #include <iterator>
117 #include <limits>
118 #include <numeric>
119 #include <tuple>
120 #include <utility>
121 #include <vector>
122 
123 using namespace llvm;
124 using namespace PatternMatch;
125 
126 #define DEBUG_TYPE "isel"
127 
128 /// LimitFloatPrecision - Generate low-precision inline sequences for
129 /// some float libcalls (6, 8 or 12 bits).
130 static unsigned LimitFloatPrecision;
131 
132 static cl::opt<unsigned, true>
133     LimitFPPrecision("limit-float-precision",
134                      cl::desc("Generate low-precision inline sequences "
135                               "for some float libcalls"),
136                      cl::location(LimitFloatPrecision), cl::Hidden,
137                      cl::init(0));
138 
139 static cl::opt<unsigned> SwitchPeelThreshold(
140     "switch-peel-threshold", cl::Hidden, cl::init(66),
141     cl::desc("Set the case probability threshold for peeling the case from a "
142              "switch statement. A value greater than 100 will void this "
143              "optimization"));
144 
145 // Limit the width of DAG chains. This is important in general to prevent
146 // DAG-based analysis from blowing up. For example, alias analysis and
147 // load clustering may not complete in reasonable time. It is difficult to
148 // recognize and avoid this situation within each individual analysis, and
149 // future analyses are likely to have the same behavior. Limiting DAG width is
150 // the safe approach and will be especially important with global DAGs.
151 //
152 // MaxParallelChains default is arbitrarily high to avoid affecting
153 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
154 // sequence over this should have been converted to llvm.memcpy by the
155 // frontend. It is easy to induce this behavior with .ll code such as:
156 // %buffer = alloca [4096 x i8]
157 // %data = load [4096 x i8]* %argPtr
158 // store [4096 x i8] %data, [4096 x i8]* %buffer
159 static const unsigned MaxParallelChains = 64;
160 
161 // Return the calling convention if the Value passed requires ABI mangling as it
162 // is a parameter to a function or a return value from a function which is not
163 // an intrinsic.
164 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
165   if (auto *R = dyn_cast<ReturnInst>(V))
166     return R->getParent()->getParent()->getCallingConv();
167 
168   if (auto *CI = dyn_cast<CallInst>(V)) {
169     const bool IsInlineAsm = CI->isInlineAsm();
170     const bool IsIndirectFunctionCall =
171         !IsInlineAsm && !CI->getCalledFunction();
172 
173     // It is possible that the call instruction is an inline asm statement or an
174     // indirect function call in which case the return value of
175     // getCalledFunction() would be nullptr.
176     const bool IsInstrinsicCall =
177         !IsInlineAsm && !IsIndirectFunctionCall &&
178         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
179 
180     if (!IsInlineAsm && !IsInstrinsicCall)
181       return CI->getCallingConv();
182   }
183 
184   return None;
185 }
186 
187 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
188                                       const SDValue *Parts, unsigned NumParts,
189                                       MVT PartVT, EVT ValueVT, const Value *V,
190                                       Optional<CallingConv::ID> CC);
191 
192 /// getCopyFromParts - Create a value that contains the specified legal parts
193 /// combined into the value they represent.  If the parts combine to a type
194 /// larger than ValueVT then AssertOp can be used to specify whether the extra
195 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
196 /// (ISD::AssertSext).
197 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
198                                 const SDValue *Parts, unsigned NumParts,
199                                 MVT PartVT, EVT ValueVT, const Value *V,
200                                 Optional<CallingConv::ID> CC = None,
201                                 Optional<ISD::NodeType> AssertOp = None) {
202   if (ValueVT.isVector())
203     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
204                                   CC);
205 
206   assert(NumParts > 0 && "No parts to assemble!");
207   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
208   SDValue Val = Parts[0];
209 
210   if (NumParts > 1) {
211     // Assemble the value from multiple parts.
212     if (ValueVT.isInteger()) {
213       unsigned PartBits = PartVT.getSizeInBits();
214       unsigned ValueBits = ValueVT.getSizeInBits();
215 
216       // Assemble the power of 2 part.
217       unsigned RoundParts = NumParts & (NumParts - 1) ?
218         1 << Log2_32(NumParts) : NumParts;
219       unsigned RoundBits = PartBits * RoundParts;
220       EVT RoundVT = RoundBits == ValueBits ?
221         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
222       SDValue Lo, Hi;
223 
224       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
225 
226       if (RoundParts > 2) {
227         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
228                               PartVT, HalfVT, V);
229         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
230                               RoundParts / 2, PartVT, HalfVT, V);
231       } else {
232         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
233         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
234       }
235 
236       if (DAG.getDataLayout().isBigEndian())
237         std::swap(Lo, Hi);
238 
239       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
240 
241       if (RoundParts < NumParts) {
242         // Assemble the trailing non-power-of-2 part.
243         unsigned OddParts = NumParts - RoundParts;
244         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
245         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
246                               OddVT, V, CC);
247 
248         // Combine the round and odd parts.
249         Lo = Val;
250         if (DAG.getDataLayout().isBigEndian())
251           std::swap(Lo, Hi);
252         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
253         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
254         Hi =
255             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
256                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
257                                         TLI.getPointerTy(DAG.getDataLayout())));
258         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
259         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
260       }
261     } else if (PartVT.isFloatingPoint()) {
262       // FP split into multiple FP parts (for ppcf128)
263       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
264              "Unexpected split");
265       SDValue Lo, Hi;
266       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
267       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
268       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
269         std::swap(Lo, Hi);
270       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
271     } else {
272       // FP split into integer parts (soft fp)
273       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
274              !PartVT.isVector() && "Unexpected split");
275       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
276       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
277     }
278   }
279 
280   // There is now one part, held in Val.  Correct it to match ValueVT.
281   // PartEVT is the type of the register class that holds the value.
282   // ValueVT is the type of the inline asm operation.
283   EVT PartEVT = Val.getValueType();
284 
285   if (PartEVT == ValueVT)
286     return Val;
287 
288   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
289       ValueVT.bitsLT(PartEVT)) {
290     // For an FP value in an integer part, we need to truncate to the right
291     // width first.
292     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
293     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
294   }
295 
296   // Handle types that have the same size.
297   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
298     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
299 
300   // Handle types with different sizes.
301   if (PartEVT.isInteger() && ValueVT.isInteger()) {
302     if (ValueVT.bitsLT(PartEVT)) {
303       // For a truncate, see if we have any information to
304       // indicate whether the truncated bits will always be
305       // zero or sign-extension.
306       if (AssertOp.hasValue())
307         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
308                           DAG.getValueType(ValueVT));
309       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
310     }
311     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
312   }
313 
314   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
315     // FP_ROUND's are always exact here.
316     if (ValueVT.bitsLT(Val.getValueType()))
317       return DAG.getNode(
318           ISD::FP_ROUND, DL, ValueVT, Val,
319           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
320 
321     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
322   }
323 
324   llvm_unreachable("Unknown mismatch!");
325 }
326 
327 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
328                                               const Twine &ErrMsg) {
329   const Instruction *I = dyn_cast_or_null<Instruction>(V);
330   if (!V)
331     return Ctx.emitError(ErrMsg);
332 
333   const char *AsmError = ", possible invalid constraint for vector type";
334   if (const CallInst *CI = dyn_cast<CallInst>(I))
335     if (isa<InlineAsm>(CI->getCalledValue()))
336       return Ctx.emitError(I, ErrMsg + AsmError);
337 
338   return Ctx.emitError(I, ErrMsg);
339 }
340 
341 /// getCopyFromPartsVector - Create a value that contains the specified legal
342 /// parts combined into the value they represent.  If the parts combine to a
343 /// type larger than ValueVT then AssertOp can be used to specify whether the
344 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
345 /// ValueVT (ISD::AssertSext).
346 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
347                                       const SDValue *Parts, unsigned NumParts,
348                                       MVT PartVT, EVT ValueVT, const Value *V,
349                                       Optional<CallingConv::ID> CallConv) {
350   assert(ValueVT.isVector() && "Not a vector value");
351   assert(NumParts > 0 && "No parts to assemble!");
352   const bool IsABIRegCopy = CallConv.hasValue();
353 
354   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
355   SDValue Val = Parts[0];
356 
357   // Handle a multi-element vector.
358   if (NumParts > 1) {
359     EVT IntermediateVT;
360     MVT RegisterVT;
361     unsigned NumIntermediates;
362     unsigned NumRegs;
363 
364     if (IsABIRegCopy) {
365       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
366           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
367           NumIntermediates, RegisterVT);
368     } else {
369       NumRegs =
370           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
371                                      NumIntermediates, RegisterVT);
372     }
373 
374     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
375     NumParts = NumRegs; // Silence a compiler warning.
376     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
377     assert(RegisterVT.getSizeInBits() ==
378            Parts[0].getSimpleValueType().getSizeInBits() &&
379            "Part type sizes don't match!");
380 
381     // Assemble the parts into intermediate operands.
382     SmallVector<SDValue, 8> Ops(NumIntermediates);
383     if (NumIntermediates == NumParts) {
384       // If the register was not expanded, truncate or copy the value,
385       // as appropriate.
386       for (unsigned i = 0; i != NumParts; ++i)
387         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
388                                   PartVT, IntermediateVT, V);
389     } else if (NumParts > 0) {
390       // If the intermediate type was expanded, build the intermediate
391       // operands from the parts.
392       assert(NumParts % NumIntermediates == 0 &&
393              "Must expand into a divisible number of parts!");
394       unsigned Factor = NumParts / NumIntermediates;
395       for (unsigned i = 0; i != NumIntermediates; ++i)
396         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
397                                   PartVT, IntermediateVT, V);
398     }
399 
400     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
401     // intermediate operands.
402     EVT BuiltVectorTy =
403         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
404                          (IntermediateVT.isVector()
405                               ? IntermediateVT.getVectorNumElements() * NumParts
406                               : NumIntermediates));
407     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
408                                                 : ISD::BUILD_VECTOR,
409                       DL, BuiltVectorTy, Ops);
410   }
411 
412   // There is now one part, held in Val.  Correct it to match ValueVT.
413   EVT PartEVT = Val.getValueType();
414 
415   if (PartEVT == ValueVT)
416     return Val;
417 
418   if (PartEVT.isVector()) {
419     // If the element type of the source/dest vectors are the same, but the
420     // parts vector has more elements than the value vector, then we have a
421     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
422     // elements we want.
423     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
424       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
425              "Cannot narrow, it would be a lossy transformation");
426       return DAG.getNode(
427           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
428           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
429     }
430 
431     // Vector/Vector bitcast.
432     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
433       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
434 
435     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
436       "Cannot handle this kind of promotion");
437     // Promoted vector extract
438     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
439 
440   }
441 
442   // Trivial bitcast if the types are the same size and the destination
443   // vector type is legal.
444   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
445       TLI.isTypeLegal(ValueVT))
446     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
447 
448   if (ValueVT.getVectorNumElements() != 1) {
449      // Certain ABIs require that vectors are passed as integers. For vectors
450      // are the same size, this is an obvious bitcast.
451      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
452        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
453      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
454        // Bitcast Val back the original type and extract the corresponding
455        // vector we want.
456        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
457        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
458                                            ValueVT.getVectorElementType(), Elts);
459        Val = DAG.getBitcast(WiderVecType, Val);
460        return DAG.getNode(
461            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
462            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
463      }
464 
465      diagnosePossiblyInvalidConstraint(
466          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
467      return DAG.getUNDEF(ValueVT);
468   }
469 
470   // Handle cases such as i8 -> <1 x i1>
471   EVT ValueSVT = ValueVT.getVectorElementType();
472   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
473     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
474                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
475 
476   return DAG.getBuildVector(ValueVT, DL, Val);
477 }
478 
479 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
480                                  SDValue Val, SDValue *Parts, unsigned NumParts,
481                                  MVT PartVT, const Value *V,
482                                  Optional<CallingConv::ID> CallConv);
483 
484 /// getCopyToParts - Create a series of nodes that contain the specified value
485 /// split into legal parts.  If the parts contain more bits than Val, then, for
486 /// integers, ExtendKind can be used to specify how to generate the extra bits.
487 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
488                            SDValue *Parts, unsigned NumParts, MVT PartVT,
489                            const Value *V,
490                            Optional<CallingConv::ID> CallConv = None,
491                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
492   EVT ValueVT = Val.getValueType();
493 
494   // Handle the vector case separately.
495   if (ValueVT.isVector())
496     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
497                                 CallConv);
498 
499   unsigned PartBits = PartVT.getSizeInBits();
500   unsigned OrigNumParts = NumParts;
501   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
502          "Copying to an illegal type!");
503 
504   if (NumParts == 0)
505     return;
506 
507   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
508   EVT PartEVT = PartVT;
509   if (PartEVT == ValueVT) {
510     assert(NumParts == 1 && "No-op copy with multiple parts!");
511     Parts[0] = Val;
512     return;
513   }
514 
515   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
516     // If the parts cover more bits than the value has, promote the value.
517     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
518       assert(NumParts == 1 && "Do not know what to promote to!");
519       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
520     } else {
521       if (ValueVT.isFloatingPoint()) {
522         // FP values need to be bitcast, then extended if they are being put
523         // into a larger container.
524         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
525         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
526       }
527       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
528              ValueVT.isInteger() &&
529              "Unknown mismatch!");
530       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
531       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
532       if (PartVT == MVT::x86mmx)
533         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
534     }
535   } else if (PartBits == ValueVT.getSizeInBits()) {
536     // Different types of the same size.
537     assert(NumParts == 1 && PartEVT != ValueVT);
538     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
540     // If the parts cover less bits than value has, truncate the value.
541     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
542            ValueVT.isInteger() &&
543            "Unknown mismatch!");
544     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
545     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
546     if (PartVT == MVT::x86mmx)
547       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
548   }
549 
550   // The value may have changed - recompute ValueVT.
551   ValueVT = Val.getValueType();
552   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
553          "Failed to tile the value with PartVT!");
554 
555   if (NumParts == 1) {
556     if (PartEVT != ValueVT) {
557       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
558                                         "scalar-to-vector conversion failed");
559       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
560     }
561 
562     Parts[0] = Val;
563     return;
564   }
565 
566   // Expand the value into multiple parts.
567   if (NumParts & (NumParts - 1)) {
568     // The number of parts is not a power of 2.  Split off and copy the tail.
569     assert(PartVT.isInteger() && ValueVT.isInteger() &&
570            "Do not know what to expand to!");
571     unsigned RoundParts = 1 << Log2_32(NumParts);
572     unsigned RoundBits = RoundParts * PartBits;
573     unsigned OddParts = NumParts - RoundParts;
574     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
575                                  DAG.getIntPtrConstant(RoundBits, DL));
576     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
577                    CallConv);
578 
579     if (DAG.getDataLayout().isBigEndian())
580       // The odd parts were reversed by getCopyToParts - unreverse them.
581       std::reverse(Parts + RoundParts, Parts + NumParts);
582 
583     NumParts = RoundParts;
584     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
585     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
586   }
587 
588   // The number of parts is a power of 2.  Repeatedly bisect the value using
589   // EXTRACT_ELEMENT.
590   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
591                          EVT::getIntegerVT(*DAG.getContext(),
592                                            ValueVT.getSizeInBits()),
593                          Val);
594 
595   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
596     for (unsigned i = 0; i < NumParts; i += StepSize) {
597       unsigned ThisBits = StepSize * PartBits / 2;
598       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
599       SDValue &Part0 = Parts[i];
600       SDValue &Part1 = Parts[i+StepSize/2];
601 
602       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
603                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
604       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
605                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
606 
607       if (ThisBits == PartBits && ThisVT != PartVT) {
608         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
609         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
610       }
611     }
612   }
613 
614   if (DAG.getDataLayout().isBigEndian())
615     std::reverse(Parts, Parts + OrigNumParts);
616 }
617 
618 static SDValue widenVectorToPartType(SelectionDAG &DAG,
619                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
620   if (!PartVT.isVector())
621     return SDValue();
622 
623   EVT ValueVT = Val.getValueType();
624   unsigned PartNumElts = PartVT.getVectorNumElements();
625   unsigned ValueNumElts = ValueVT.getVectorNumElements();
626   if (PartNumElts > ValueNumElts &&
627       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
628     EVT ElementVT = PartVT.getVectorElementType();
629     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
630     // undef elements.
631     SmallVector<SDValue, 16> Ops;
632     DAG.ExtractVectorElements(Val, Ops);
633     SDValue EltUndef = DAG.getUNDEF(ElementVT);
634     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
635       Ops.push_back(EltUndef);
636 
637     // FIXME: Use CONCAT for 2x -> 4x.
638     return DAG.getBuildVector(PartVT, DL, Ops);
639   }
640 
641   return SDValue();
642 }
643 
644 /// getCopyToPartsVector - Create a series of nodes that contain the specified
645 /// value split into legal parts.
646 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
647                                  SDValue Val, SDValue *Parts, unsigned NumParts,
648                                  MVT PartVT, const Value *V,
649                                  Optional<CallingConv::ID> CallConv) {
650   EVT ValueVT = Val.getValueType();
651   assert(ValueVT.isVector() && "Not a vector");
652   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
653   const bool IsABIRegCopy = CallConv.hasValue();
654 
655   if (NumParts == 1) {
656     EVT PartEVT = PartVT;
657     if (PartEVT == ValueVT) {
658       // Nothing to do.
659     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
660       // Bitconvert vector->vector case.
661       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
662     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
663       Val = Widened;
664     } else if (PartVT.isVector() &&
665                PartEVT.getVectorElementType().bitsGE(
666                  ValueVT.getVectorElementType()) &&
667                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
668 
669       // Promoted vector extract
670       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
671     } else {
672       if (ValueVT.getVectorNumElements() == 1) {
673         Val = DAG.getNode(
674             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
675             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
676       } else {
677         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
678                "lossy conversion of vector to scalar type");
679         EVT IntermediateType =
680             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
681         Val = DAG.getBitcast(IntermediateType, Val);
682         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
683       }
684     }
685 
686     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
687     Parts[0] = Val;
688     return;
689   }
690 
691   // Handle a multi-element vector.
692   EVT IntermediateVT;
693   MVT RegisterVT;
694   unsigned NumIntermediates;
695   unsigned NumRegs;
696   if (IsABIRegCopy) {
697     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
698         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
699         NumIntermediates, RegisterVT);
700   } else {
701     NumRegs =
702         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
703                                    NumIntermediates, RegisterVT);
704   }
705 
706   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
707   NumParts = NumRegs; // Silence a compiler warning.
708   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
709 
710   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
711     IntermediateVT.getVectorNumElements() : 1;
712 
713   // Convert the vector to the appropiate type if necessary.
714   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
715 
716   EVT BuiltVectorTy = EVT::getVectorVT(
717       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
718   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
719   if (ValueVT != BuiltVectorTy) {
720     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
721       Val = Widened;
722 
723     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
724   }
725 
726   // Split the vector into intermediate operands.
727   SmallVector<SDValue, 8> Ops(NumIntermediates);
728   for (unsigned i = 0; i != NumIntermediates; ++i) {
729     if (IntermediateVT.isVector()) {
730       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
731                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
732     } else {
733       Ops[i] = DAG.getNode(
734           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
735           DAG.getConstant(i, DL, IdxVT));
736     }
737   }
738 
739   // Split the intermediate operands into legal parts.
740   if (NumParts == NumIntermediates) {
741     // If the register was not expanded, promote or copy the value,
742     // as appropriate.
743     for (unsigned i = 0; i != NumParts; ++i)
744       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
745   } else if (NumParts > 0) {
746     // If the intermediate type was expanded, split each the value into
747     // legal parts.
748     assert(NumIntermediates != 0 && "division by zero");
749     assert(NumParts % NumIntermediates == 0 &&
750            "Must expand into a divisible number of parts!");
751     unsigned Factor = NumParts / NumIntermediates;
752     for (unsigned i = 0; i != NumIntermediates; ++i)
753       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
754                      CallConv);
755   }
756 }
757 
758 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
759                            EVT valuevt, Optional<CallingConv::ID> CC)
760     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
761       RegCount(1, regs.size()), CallConv(CC) {}
762 
763 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
764                            const DataLayout &DL, unsigned Reg, Type *Ty,
765                            Optional<CallingConv::ID> CC) {
766   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
767 
768   CallConv = CC;
769 
770   for (EVT ValueVT : ValueVTs) {
771     unsigned NumRegs =
772         isABIMangled()
773             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
774             : TLI.getNumRegisters(Context, ValueVT);
775     MVT RegisterVT =
776         isABIMangled()
777             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
778             : TLI.getRegisterType(Context, ValueVT);
779     for (unsigned i = 0; i != NumRegs; ++i)
780       Regs.push_back(Reg + i);
781     RegVTs.push_back(RegisterVT);
782     RegCount.push_back(NumRegs);
783     Reg += NumRegs;
784   }
785 }
786 
787 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
788                                       FunctionLoweringInfo &FuncInfo,
789                                       const SDLoc &dl, SDValue &Chain,
790                                       SDValue *Flag, const Value *V) const {
791   // A Value with type {} or [0 x %t] needs no registers.
792   if (ValueVTs.empty())
793     return SDValue();
794 
795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
796 
797   // Assemble the legal parts into the final values.
798   SmallVector<SDValue, 4> Values(ValueVTs.size());
799   SmallVector<SDValue, 8> Parts;
800   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
801     // Copy the legal parts from the registers.
802     EVT ValueVT = ValueVTs[Value];
803     unsigned NumRegs = RegCount[Value];
804     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
805                                           *DAG.getContext(),
806                                           CallConv.getValue(), RegVTs[Value])
807                                     : RegVTs[Value];
808 
809     Parts.resize(NumRegs);
810     for (unsigned i = 0; i != NumRegs; ++i) {
811       SDValue P;
812       if (!Flag) {
813         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
814       } else {
815         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
816         *Flag = P.getValue(2);
817       }
818 
819       Chain = P.getValue(1);
820       Parts[i] = P;
821 
822       // If the source register was virtual and if we know something about it,
823       // add an assert node.
824       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
825           !RegisterVT.isInteger())
826         continue;
827 
828       const FunctionLoweringInfo::LiveOutInfo *LOI =
829         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
830       if (!LOI)
831         continue;
832 
833       unsigned RegSize = RegisterVT.getScalarSizeInBits();
834       unsigned NumSignBits = LOI->NumSignBits;
835       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
836 
837       if (NumZeroBits == RegSize) {
838         // The current value is a zero.
839         // Explicitly express that as it would be easier for
840         // optimizations to kick in.
841         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
842         continue;
843       }
844 
845       // FIXME: We capture more information than the dag can represent.  For
846       // now, just use the tightest assertzext/assertsext possible.
847       bool isSExt;
848       EVT FromVT(MVT::Other);
849       if (NumZeroBits) {
850         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
851         isSExt = false;
852       } else if (NumSignBits > 1) {
853         FromVT =
854             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
855         isSExt = true;
856       } else {
857         continue;
858       }
859       // Add an assertion node.
860       assert(FromVT != MVT::Other);
861       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
862                              RegisterVT, P, DAG.getValueType(FromVT));
863     }
864 
865     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
866                                      RegisterVT, ValueVT, V, CallConv);
867     Part += NumRegs;
868     Parts.clear();
869   }
870 
871   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
872 }
873 
874 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
875                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
876                                  const Value *V,
877                                  ISD::NodeType PreferredExtendType) const {
878   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
879   ISD::NodeType ExtendKind = PreferredExtendType;
880 
881   // Get the list of the values's legal parts.
882   unsigned NumRegs = Regs.size();
883   SmallVector<SDValue, 8> Parts(NumRegs);
884   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
885     unsigned NumParts = RegCount[Value];
886 
887     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
888                                           *DAG.getContext(),
889                                           CallConv.getValue(), RegVTs[Value])
890                                     : RegVTs[Value];
891 
892     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
893       ExtendKind = ISD::ZERO_EXTEND;
894 
895     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
896                    NumParts, RegisterVT, V, CallConv, ExtendKind);
897     Part += NumParts;
898   }
899 
900   // Copy the parts into the registers.
901   SmallVector<SDValue, 8> Chains(NumRegs);
902   for (unsigned i = 0; i != NumRegs; ++i) {
903     SDValue Part;
904     if (!Flag) {
905       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
906     } else {
907       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
908       *Flag = Part.getValue(1);
909     }
910 
911     Chains[i] = Part.getValue(0);
912   }
913 
914   if (NumRegs == 1 || Flag)
915     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
916     // flagged to it. That is the CopyToReg nodes and the user are considered
917     // a single scheduling unit. If we create a TokenFactor and return it as
918     // chain, then the TokenFactor is both a predecessor (operand) of the
919     // user as well as a successor (the TF operands are flagged to the user).
920     // c1, f1 = CopyToReg
921     // c2, f2 = CopyToReg
922     // c3     = TokenFactor c1, c2
923     // ...
924     //        = op c3, ..., f2
925     Chain = Chains[NumRegs-1];
926   else
927     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
928 }
929 
930 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
931                                         unsigned MatchingIdx, const SDLoc &dl,
932                                         SelectionDAG &DAG,
933                                         std::vector<SDValue> &Ops) const {
934   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
935 
936   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
937   if (HasMatching)
938     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
939   else if (!Regs.empty() &&
940            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
941     // Put the register class of the virtual registers in the flag word.  That
942     // way, later passes can recompute register class constraints for inline
943     // assembly as well as normal instructions.
944     // Don't do this for tied operands that can use the regclass information
945     // from the def.
946     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
947     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
948     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
949   }
950 
951   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
952   Ops.push_back(Res);
953 
954   if (Code == InlineAsm::Kind_Clobber) {
955     // Clobbers should always have a 1:1 mapping with registers, and may
956     // reference registers that have illegal (e.g. vector) types. Hence, we
957     // shouldn't try to apply any sort of splitting logic to them.
958     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
959            "No 1:1 mapping from clobbers to regs?");
960     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
961     (void)SP;
962     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
963       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
964       assert(
965           (Regs[I] != SP ||
966            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
967           "If we clobbered the stack pointer, MFI should know about it.");
968     }
969     return;
970   }
971 
972   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
973     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
974     MVT RegisterVT = RegVTs[Value];
975     for (unsigned i = 0; i != NumRegs; ++i) {
976       assert(Reg < Regs.size() && "Mismatch in # registers expected");
977       unsigned TheReg = Regs[Reg++];
978       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
979     }
980   }
981 }
982 
983 SmallVector<std::pair<unsigned, unsigned>, 4>
984 RegsForValue::getRegsAndSizes() const {
985   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
986   unsigned I = 0;
987   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
988     unsigned RegCount = std::get<0>(CountAndVT);
989     MVT RegisterVT = std::get<1>(CountAndVT);
990     unsigned RegisterSize = RegisterVT.getSizeInBits();
991     for (unsigned E = I + RegCount; I != E; ++I)
992       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
993   }
994   return OutVec;
995 }
996 
997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
998                                const TargetLibraryInfo *li) {
999   AA = aa;
1000   GFI = gfi;
1001   LibInfo = li;
1002   DL = &DAG.getDataLayout();
1003   Context = DAG.getContext();
1004   LPadToCallSiteMap.clear();
1005 }
1006 
1007 void SelectionDAGBuilder::clear() {
1008   NodeMap.clear();
1009   UnusedArgNodeMap.clear();
1010   PendingLoads.clear();
1011   PendingExports.clear();
1012   CurInst = nullptr;
1013   HasTailCall = false;
1014   SDNodeOrder = LowestSDNodeOrder;
1015   StatepointLowering.clear();
1016 }
1017 
1018 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1019   DanglingDebugInfoMap.clear();
1020 }
1021 
1022 SDValue SelectionDAGBuilder::getRoot() {
1023   if (PendingLoads.empty())
1024     return DAG.getRoot();
1025 
1026   if (PendingLoads.size() == 1) {
1027     SDValue Root = PendingLoads[0];
1028     DAG.setRoot(Root);
1029     PendingLoads.clear();
1030     return Root;
1031   }
1032 
1033   // Otherwise, we have to make a token factor node.
1034   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1035   PendingLoads.clear();
1036   DAG.setRoot(Root);
1037   return Root;
1038 }
1039 
1040 SDValue SelectionDAGBuilder::getControlRoot() {
1041   SDValue Root = DAG.getRoot();
1042 
1043   if (PendingExports.empty())
1044     return Root;
1045 
1046   // Turn all of the CopyToReg chains into one factored node.
1047   if (Root.getOpcode() != ISD::EntryToken) {
1048     unsigned i = 0, e = PendingExports.size();
1049     for (; i != e; ++i) {
1050       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1051       if (PendingExports[i].getNode()->getOperand(0) == Root)
1052         break;  // Don't add the root if we already indirectly depend on it.
1053     }
1054 
1055     if (i == e)
1056       PendingExports.push_back(Root);
1057   }
1058 
1059   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1060                      PendingExports);
1061   PendingExports.clear();
1062   DAG.setRoot(Root);
1063   return Root;
1064 }
1065 
1066 void SelectionDAGBuilder::visit(const Instruction &I) {
1067   // Set up outgoing PHI node register values before emitting the terminator.
1068   if (I.isTerminator()) {
1069     HandlePHINodesInSuccessorBlocks(I.getParent());
1070   }
1071 
1072   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1073   if (!isa<DbgInfoIntrinsic>(I))
1074     ++SDNodeOrder;
1075 
1076   CurInst = &I;
1077 
1078   visit(I.getOpcode(), I);
1079 
1080   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1081     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1082     // maps to this instruction.
1083     // TODO: We could handle all flags (nsw, etc) here.
1084     // TODO: If an IR instruction maps to >1 node, only the final node will have
1085     //       flags set.
1086     if (SDNode *Node = getNodeForIRValue(&I)) {
1087       SDNodeFlags IncomingFlags;
1088       IncomingFlags.copyFMF(*FPMO);
1089       if (!Node->getFlags().isDefined())
1090         Node->setFlags(IncomingFlags);
1091       else
1092         Node->intersectFlagsWith(IncomingFlags);
1093     }
1094   }
1095 
1096   if (!I.isTerminator() && !HasTailCall &&
1097       !isStatepoint(&I)) // statepoints handle their exports internally
1098     CopyToExportRegsIfNeeded(&I);
1099 
1100   CurInst = nullptr;
1101 }
1102 
1103 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1104   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1105 }
1106 
1107 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1108   // Note: this doesn't use InstVisitor, because it has to work with
1109   // ConstantExpr's in addition to instructions.
1110   switch (Opcode) {
1111   default: llvm_unreachable("Unknown instruction type encountered!");
1112     // Build the switch statement using the Instruction.def file.
1113 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1114     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1115 #include "llvm/IR/Instruction.def"
1116   }
1117 }
1118 
1119 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1120                                                 const DIExpression *Expr) {
1121   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1122     const DbgValueInst *DI = DDI.getDI();
1123     DIVariable *DanglingVariable = DI->getVariable();
1124     DIExpression *DanglingExpr = DI->getExpression();
1125     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1126       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1127       return true;
1128     }
1129     return false;
1130   };
1131 
1132   for (auto &DDIMI : DanglingDebugInfoMap) {
1133     DanglingDebugInfoVector &DDIV = DDIMI.second;
1134     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1135   }
1136 }
1137 
1138 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1139 // generate the debug data structures now that we've seen its definition.
1140 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1141                                                    SDValue Val) {
1142   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1143   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1144     return;
1145 
1146   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1147   for (auto &DDI : DDIV) {
1148     const DbgValueInst *DI = DDI.getDI();
1149     assert(DI && "Ill-formed DanglingDebugInfo");
1150     DebugLoc dl = DDI.getdl();
1151     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1152     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1153     DILocalVariable *Variable = DI->getVariable();
1154     DIExpression *Expr = DI->getExpression();
1155     assert(Variable->isValidLocationForIntrinsic(dl) &&
1156            "Expected inlined-at fields to agree");
1157     SDDbgValue *SDV;
1158     if (Val.getNode()) {
1159       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1160         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1161                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1162         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1163         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1164         // inserted after the definition of Val when emitting the instructions
1165         // after ISel. An alternative could be to teach
1166         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1167         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1168                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1169                    << ValSDNodeOrder << "\n");
1170         SDV = getDbgValue(Val, Variable, Expr, dl,
1171                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1172         DAG.AddDbgValue(SDV, Val.getNode(), false);
1173       } else
1174         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1175                           << "in EmitFuncArgumentDbgValue\n");
1176     } else
1177       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1178   }
1179   DDIV.clear();
1180 }
1181 
1182 /// getCopyFromRegs - If there was virtual register allocated for the value V
1183 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1184 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1185   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1186   SDValue Result;
1187 
1188   if (It != FuncInfo.ValueMap.end()) {
1189     unsigned InReg = It->second;
1190 
1191     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1192                      DAG.getDataLayout(), InReg, Ty,
1193                      None); // This is not an ABI copy.
1194     SDValue Chain = DAG.getEntryNode();
1195     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1196                                  V);
1197     resolveDanglingDebugInfo(V, Result);
1198   }
1199 
1200   return Result;
1201 }
1202 
1203 /// getValue - Return an SDValue for the given Value.
1204 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1205   // If we already have an SDValue for this value, use it. It's important
1206   // to do this first, so that we don't create a CopyFromReg if we already
1207   // have a regular SDValue.
1208   SDValue &N = NodeMap[V];
1209   if (N.getNode()) return N;
1210 
1211   // If there's a virtual register allocated and initialized for this
1212   // value, use it.
1213   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1214     return copyFromReg;
1215 
1216   // Otherwise create a new SDValue and remember it.
1217   SDValue Val = getValueImpl(V);
1218   NodeMap[V] = Val;
1219   resolveDanglingDebugInfo(V, Val);
1220   return Val;
1221 }
1222 
1223 // Return true if SDValue exists for the given Value
1224 bool SelectionDAGBuilder::findValue(const Value *V) const {
1225   return (NodeMap.find(V) != NodeMap.end()) ||
1226     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1227 }
1228 
1229 /// getNonRegisterValue - Return an SDValue for the given Value, but
1230 /// don't look in FuncInfo.ValueMap for a virtual register.
1231 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1232   // If we already have an SDValue for this value, use it.
1233   SDValue &N = NodeMap[V];
1234   if (N.getNode()) {
1235     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1236       // Remove the debug location from the node as the node is about to be used
1237       // in a location which may differ from the original debug location.  This
1238       // is relevant to Constant and ConstantFP nodes because they can appear
1239       // as constant expressions inside PHI nodes.
1240       N->setDebugLoc(DebugLoc());
1241     }
1242     return N;
1243   }
1244 
1245   // Otherwise create a new SDValue and remember it.
1246   SDValue Val = getValueImpl(V);
1247   NodeMap[V] = Val;
1248   resolveDanglingDebugInfo(V, Val);
1249   return Val;
1250 }
1251 
1252 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1253 /// Create an SDValue for the given value.
1254 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1255   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1256 
1257   if (const Constant *C = dyn_cast<Constant>(V)) {
1258     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1259 
1260     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1261       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1262 
1263     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1264       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1265 
1266     if (isa<ConstantPointerNull>(C)) {
1267       unsigned AS = V->getType()->getPointerAddressSpace();
1268       return DAG.getConstant(0, getCurSDLoc(),
1269                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1270     }
1271 
1272     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1273       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1274 
1275     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1276       return DAG.getUNDEF(VT);
1277 
1278     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1279       visit(CE->getOpcode(), *CE);
1280       SDValue N1 = NodeMap[V];
1281       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1282       return N1;
1283     }
1284 
1285     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1286       SmallVector<SDValue, 4> Constants;
1287       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1288            OI != OE; ++OI) {
1289         SDNode *Val = getValue(*OI).getNode();
1290         // If the operand is an empty aggregate, there are no values.
1291         if (!Val) continue;
1292         // Add each leaf value from the operand to the Constants list
1293         // to form a flattened list of all the values.
1294         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1295           Constants.push_back(SDValue(Val, i));
1296       }
1297 
1298       return DAG.getMergeValues(Constants, getCurSDLoc());
1299     }
1300 
1301     if (const ConstantDataSequential *CDS =
1302           dyn_cast<ConstantDataSequential>(C)) {
1303       SmallVector<SDValue, 4> Ops;
1304       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1305         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1306         // Add each leaf value from the operand to the Constants list
1307         // to form a flattened list of all the values.
1308         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1309           Ops.push_back(SDValue(Val, i));
1310       }
1311 
1312       if (isa<ArrayType>(CDS->getType()))
1313         return DAG.getMergeValues(Ops, getCurSDLoc());
1314       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1315     }
1316 
1317     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1318       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1319              "Unknown struct or array constant!");
1320 
1321       SmallVector<EVT, 4> ValueVTs;
1322       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1323       unsigned NumElts = ValueVTs.size();
1324       if (NumElts == 0)
1325         return SDValue(); // empty struct
1326       SmallVector<SDValue, 4> Constants(NumElts);
1327       for (unsigned i = 0; i != NumElts; ++i) {
1328         EVT EltVT = ValueVTs[i];
1329         if (isa<UndefValue>(C))
1330           Constants[i] = DAG.getUNDEF(EltVT);
1331         else if (EltVT.isFloatingPoint())
1332           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1333         else
1334           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1335       }
1336 
1337       return DAG.getMergeValues(Constants, getCurSDLoc());
1338     }
1339 
1340     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1341       return DAG.getBlockAddress(BA, VT);
1342 
1343     VectorType *VecTy = cast<VectorType>(V->getType());
1344     unsigned NumElements = VecTy->getNumElements();
1345 
1346     // Now that we know the number and type of the elements, get that number of
1347     // elements into the Ops array based on what kind of constant it is.
1348     SmallVector<SDValue, 16> Ops;
1349     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1350       for (unsigned i = 0; i != NumElements; ++i)
1351         Ops.push_back(getValue(CV->getOperand(i)));
1352     } else {
1353       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1354       EVT EltVT =
1355           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1356 
1357       SDValue Op;
1358       if (EltVT.isFloatingPoint())
1359         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1360       else
1361         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1362       Ops.assign(NumElements, Op);
1363     }
1364 
1365     // Create a BUILD_VECTOR node.
1366     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1367   }
1368 
1369   // If this is a static alloca, generate it as the frameindex instead of
1370   // computation.
1371   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1372     DenseMap<const AllocaInst*, int>::iterator SI =
1373       FuncInfo.StaticAllocaMap.find(AI);
1374     if (SI != FuncInfo.StaticAllocaMap.end())
1375       return DAG.getFrameIndex(SI->second,
1376                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1377   }
1378 
1379   // If this is an instruction which fast-isel has deferred, select it now.
1380   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1381     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1382 
1383     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1384                      Inst->getType(), getABIRegCopyCC(V));
1385     SDValue Chain = DAG.getEntryNode();
1386     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1387   }
1388 
1389   llvm_unreachable("Can't get register for value!");
1390 }
1391 
1392 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1393   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1394   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1395   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1396   bool IsSEH = isAsynchronousEHPersonality(Pers);
1397   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1398   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1399   if (!IsSEH)
1400     CatchPadMBB->setIsEHScopeEntry();
1401   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1402   if (IsMSVCCXX || IsCoreCLR)
1403     CatchPadMBB->setIsEHFuncletEntry();
1404   // Wasm does not need catchpads anymore
1405   if (!IsWasmCXX)
1406     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1407                             getControlRoot()));
1408 }
1409 
1410 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1411   // Update machine-CFG edge.
1412   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1413   FuncInfo.MBB->addSuccessor(TargetMBB);
1414 
1415   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1416   bool IsSEH = isAsynchronousEHPersonality(Pers);
1417   if (IsSEH) {
1418     // If this is not a fall-through branch or optimizations are switched off,
1419     // emit the branch.
1420     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1421         TM.getOptLevel() == CodeGenOpt::None)
1422       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1423                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1424     return;
1425   }
1426 
1427   // Figure out the funclet membership for the catchret's successor.
1428   // This will be used by the FuncletLayout pass to determine how to order the
1429   // BB's.
1430   // A 'catchret' returns to the outer scope's color.
1431   Value *ParentPad = I.getCatchSwitchParentPad();
1432   const BasicBlock *SuccessorColor;
1433   if (isa<ConstantTokenNone>(ParentPad))
1434     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1435   else
1436     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1437   assert(SuccessorColor && "No parent funclet for catchret!");
1438   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1439   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1440 
1441   // Create the terminator node.
1442   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1443                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1444                             DAG.getBasicBlock(SuccessorColorMBB));
1445   DAG.setRoot(Ret);
1446 }
1447 
1448 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1449   // Don't emit any special code for the cleanuppad instruction. It just marks
1450   // the start of an EH scope/funclet.
1451   FuncInfo.MBB->setIsEHScopeEntry();
1452   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1453   if (Pers != EHPersonality::Wasm_CXX) {
1454     FuncInfo.MBB->setIsEHFuncletEntry();
1455     FuncInfo.MBB->setIsCleanupFuncletEntry();
1456   }
1457 }
1458 
1459 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1460 // the control flow always stops at the single catch pad, as it does for a
1461 // cleanup pad. In case the exception caught is not of the types the catch pad
1462 // catches, it will be rethrown by a rethrow.
1463 static void findWasmUnwindDestinations(
1464     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1465     BranchProbability Prob,
1466     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1467         &UnwindDests) {
1468   while (EHPadBB) {
1469     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1470     if (isa<CleanupPadInst>(Pad)) {
1471       // Stop on cleanup pads.
1472       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1473       UnwindDests.back().first->setIsEHScopeEntry();
1474       break;
1475     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1476       // Add the catchpad handlers to the possible destinations. We don't
1477       // continue to the unwind destination of the catchswitch for wasm.
1478       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1479         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1480         UnwindDests.back().first->setIsEHScopeEntry();
1481       }
1482       break;
1483     } else {
1484       continue;
1485     }
1486   }
1487 }
1488 
1489 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1490 /// many places it could ultimately go. In the IR, we have a single unwind
1491 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1492 /// This function skips over imaginary basic blocks that hold catchswitch
1493 /// instructions, and finds all the "real" machine
1494 /// basic block destinations. As those destinations may not be successors of
1495 /// EHPadBB, here we also calculate the edge probability to those destinations.
1496 /// The passed-in Prob is the edge probability to EHPadBB.
1497 static void findUnwindDestinations(
1498     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1499     BranchProbability Prob,
1500     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1501         &UnwindDests) {
1502   EHPersonality Personality =
1503     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1504   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1505   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1506   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1507   bool IsSEH = isAsynchronousEHPersonality(Personality);
1508 
1509   if (IsWasmCXX) {
1510     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1511     return;
1512   }
1513 
1514   while (EHPadBB) {
1515     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1516     BasicBlock *NewEHPadBB = nullptr;
1517     if (isa<LandingPadInst>(Pad)) {
1518       // Stop on landingpads. They are not funclets.
1519       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1520       break;
1521     } else if (isa<CleanupPadInst>(Pad)) {
1522       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1523       // personalities.
1524       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1525       UnwindDests.back().first->setIsEHScopeEntry();
1526       UnwindDests.back().first->setIsEHFuncletEntry();
1527       break;
1528     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1529       // Add the catchpad handlers to the possible destinations.
1530       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1531         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1532         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1533         if (IsMSVCCXX || IsCoreCLR)
1534           UnwindDests.back().first->setIsEHFuncletEntry();
1535         if (!IsSEH)
1536           UnwindDests.back().first->setIsEHScopeEntry();
1537       }
1538       NewEHPadBB = CatchSwitch->getUnwindDest();
1539     } else {
1540       continue;
1541     }
1542 
1543     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1544     if (BPI && NewEHPadBB)
1545       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1546     EHPadBB = NewEHPadBB;
1547   }
1548 }
1549 
1550 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1551   // Update successor info.
1552   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1553   auto UnwindDest = I.getUnwindDest();
1554   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1555   BranchProbability UnwindDestProb =
1556       (BPI && UnwindDest)
1557           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1558           : BranchProbability::getZero();
1559   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1560   for (auto &UnwindDest : UnwindDests) {
1561     UnwindDest.first->setIsEHPad();
1562     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1563   }
1564   FuncInfo.MBB->normalizeSuccProbs();
1565 
1566   // Create the terminator node.
1567   SDValue Ret =
1568       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1569   DAG.setRoot(Ret);
1570 }
1571 
1572 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1573   report_fatal_error("visitCatchSwitch not yet implemented!");
1574 }
1575 
1576 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1578   auto &DL = DAG.getDataLayout();
1579   SDValue Chain = getControlRoot();
1580   SmallVector<ISD::OutputArg, 8> Outs;
1581   SmallVector<SDValue, 8> OutVals;
1582 
1583   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1584   // lower
1585   //
1586   //   %val = call <ty> @llvm.experimental.deoptimize()
1587   //   ret <ty> %val
1588   //
1589   // differently.
1590   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1591     LowerDeoptimizingReturn();
1592     return;
1593   }
1594 
1595   if (!FuncInfo.CanLowerReturn) {
1596     unsigned DemoteReg = FuncInfo.DemoteRegister;
1597     const Function *F = I.getParent()->getParent();
1598 
1599     // Emit a store of the return value through the virtual register.
1600     // Leave Outs empty so that LowerReturn won't try to load return
1601     // registers the usual way.
1602     SmallVector<EVT, 1> PtrValueVTs;
1603     ComputeValueVTs(TLI, DL,
1604                     F->getReturnType()->getPointerTo(
1605                         DAG.getDataLayout().getAllocaAddrSpace()),
1606                     PtrValueVTs);
1607 
1608     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1609                                         DemoteReg, PtrValueVTs[0]);
1610     SDValue RetOp = getValue(I.getOperand(0));
1611 
1612     SmallVector<EVT, 4> ValueVTs;
1613     SmallVector<uint64_t, 4> Offsets;
1614     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1615     unsigned NumValues = ValueVTs.size();
1616 
1617     SmallVector<SDValue, 4> Chains(NumValues);
1618     for (unsigned i = 0; i != NumValues; ++i) {
1619       // An aggregate return value cannot wrap around the address space, so
1620       // offsets to its parts don't wrap either.
1621       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1622       Chains[i] = DAG.getStore(
1623           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1624           // FIXME: better loc info would be nice.
1625           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1626     }
1627 
1628     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1629                         MVT::Other, Chains);
1630   } else if (I.getNumOperands() != 0) {
1631     SmallVector<EVT, 4> ValueVTs;
1632     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1633     unsigned NumValues = ValueVTs.size();
1634     if (NumValues) {
1635       SDValue RetOp = getValue(I.getOperand(0));
1636 
1637       const Function *F = I.getParent()->getParent();
1638 
1639       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1640       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1641                                           Attribute::SExt))
1642         ExtendKind = ISD::SIGN_EXTEND;
1643       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1644                                                Attribute::ZExt))
1645         ExtendKind = ISD::ZERO_EXTEND;
1646 
1647       LLVMContext &Context = F->getContext();
1648       bool RetInReg = F->getAttributes().hasAttribute(
1649           AttributeList::ReturnIndex, Attribute::InReg);
1650 
1651       for (unsigned j = 0; j != NumValues; ++j) {
1652         EVT VT = ValueVTs[j];
1653 
1654         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1655           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1656 
1657         CallingConv::ID CC = F->getCallingConv();
1658 
1659         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1660         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1661         SmallVector<SDValue, 4> Parts(NumParts);
1662         getCopyToParts(DAG, getCurSDLoc(),
1663                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1664                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1665 
1666         // 'inreg' on function refers to return value
1667         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1668         if (RetInReg)
1669           Flags.setInReg();
1670 
1671         // Propagate extension type if any
1672         if (ExtendKind == ISD::SIGN_EXTEND)
1673           Flags.setSExt();
1674         else if (ExtendKind == ISD::ZERO_EXTEND)
1675           Flags.setZExt();
1676 
1677         for (unsigned i = 0; i < NumParts; ++i) {
1678           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1679                                         VT, /*isfixed=*/true, 0, 0));
1680           OutVals.push_back(Parts[i]);
1681         }
1682       }
1683     }
1684   }
1685 
1686   // Push in swifterror virtual register as the last element of Outs. This makes
1687   // sure swifterror virtual register will be returned in the swifterror
1688   // physical register.
1689   const Function *F = I.getParent()->getParent();
1690   if (TLI.supportSwiftError() &&
1691       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1692     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1693     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1694     Flags.setSwiftError();
1695     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1696                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1697                                   true /*isfixed*/, 1 /*origidx*/,
1698                                   0 /*partOffs*/));
1699     // Create SDNode for the swifterror virtual register.
1700     OutVals.push_back(
1701         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1702                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1703                         EVT(TLI.getPointerTy(DL))));
1704   }
1705 
1706   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1707   CallingConv::ID CallConv =
1708     DAG.getMachineFunction().getFunction().getCallingConv();
1709   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1710       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1711 
1712   // Verify that the target's LowerReturn behaved as expected.
1713   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1714          "LowerReturn didn't return a valid chain!");
1715 
1716   // Update the DAG with the new chain value resulting from return lowering.
1717   DAG.setRoot(Chain);
1718 }
1719 
1720 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1721 /// created for it, emit nodes to copy the value into the virtual
1722 /// registers.
1723 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1724   // Skip empty types
1725   if (V->getType()->isEmptyTy())
1726     return;
1727 
1728   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1729   if (VMI != FuncInfo.ValueMap.end()) {
1730     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1731     CopyValueToVirtualRegister(V, VMI->second);
1732   }
1733 }
1734 
1735 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1736 /// the current basic block, add it to ValueMap now so that we'll get a
1737 /// CopyTo/FromReg.
1738 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1739   // No need to export constants.
1740   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1741 
1742   // Already exported?
1743   if (FuncInfo.isExportedInst(V)) return;
1744 
1745   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1746   CopyValueToVirtualRegister(V, Reg);
1747 }
1748 
1749 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1750                                                      const BasicBlock *FromBB) {
1751   // The operands of the setcc have to be in this block.  We don't know
1752   // how to export them from some other block.
1753   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1754     // Can export from current BB.
1755     if (VI->getParent() == FromBB)
1756       return true;
1757 
1758     // Is already exported, noop.
1759     return FuncInfo.isExportedInst(V);
1760   }
1761 
1762   // If this is an argument, we can export it if the BB is the entry block or
1763   // if it is already exported.
1764   if (isa<Argument>(V)) {
1765     if (FromBB == &FromBB->getParent()->getEntryBlock())
1766       return true;
1767 
1768     // Otherwise, can only export this if it is already exported.
1769     return FuncInfo.isExportedInst(V);
1770   }
1771 
1772   // Otherwise, constants can always be exported.
1773   return true;
1774 }
1775 
1776 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1777 BranchProbability
1778 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1779                                         const MachineBasicBlock *Dst) const {
1780   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1781   const BasicBlock *SrcBB = Src->getBasicBlock();
1782   const BasicBlock *DstBB = Dst->getBasicBlock();
1783   if (!BPI) {
1784     // If BPI is not available, set the default probability as 1 / N, where N is
1785     // the number of successors.
1786     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1787     return BranchProbability(1, SuccSize);
1788   }
1789   return BPI->getEdgeProbability(SrcBB, DstBB);
1790 }
1791 
1792 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1793                                                MachineBasicBlock *Dst,
1794                                                BranchProbability Prob) {
1795   if (!FuncInfo.BPI)
1796     Src->addSuccessorWithoutProb(Dst);
1797   else {
1798     if (Prob.isUnknown())
1799       Prob = getEdgeProbability(Src, Dst);
1800     Src->addSuccessor(Dst, Prob);
1801   }
1802 }
1803 
1804 static bool InBlock(const Value *V, const BasicBlock *BB) {
1805   if (const Instruction *I = dyn_cast<Instruction>(V))
1806     return I->getParent() == BB;
1807   return true;
1808 }
1809 
1810 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1811 /// This function emits a branch and is used at the leaves of an OR or an
1812 /// AND operator tree.
1813 void
1814 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1815                                                   MachineBasicBlock *TBB,
1816                                                   MachineBasicBlock *FBB,
1817                                                   MachineBasicBlock *CurBB,
1818                                                   MachineBasicBlock *SwitchBB,
1819                                                   BranchProbability TProb,
1820                                                   BranchProbability FProb,
1821                                                   bool InvertCond) {
1822   const BasicBlock *BB = CurBB->getBasicBlock();
1823 
1824   // If the leaf of the tree is a comparison, merge the condition into
1825   // the caseblock.
1826   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1827     // The operands of the cmp have to be in this block.  We don't know
1828     // how to export them from some other block.  If this is the first block
1829     // of the sequence, no exporting is needed.
1830     if (CurBB == SwitchBB ||
1831         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1832          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1833       ISD::CondCode Condition;
1834       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1835         ICmpInst::Predicate Pred =
1836             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1837         Condition = getICmpCondCode(Pred);
1838       } else {
1839         const FCmpInst *FC = cast<FCmpInst>(Cond);
1840         FCmpInst::Predicate Pred =
1841             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1842         Condition = getFCmpCondCode(Pred);
1843         if (TM.Options.NoNaNsFPMath)
1844           Condition = getFCmpCodeWithoutNaN(Condition);
1845       }
1846 
1847       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1848                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1849       SwitchCases.push_back(CB);
1850       return;
1851     }
1852   }
1853 
1854   // Create a CaseBlock record representing this branch.
1855   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1856   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1857                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1858   SwitchCases.push_back(CB);
1859 }
1860 
1861 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1862                                                MachineBasicBlock *TBB,
1863                                                MachineBasicBlock *FBB,
1864                                                MachineBasicBlock *CurBB,
1865                                                MachineBasicBlock *SwitchBB,
1866                                                Instruction::BinaryOps Opc,
1867                                                BranchProbability TProb,
1868                                                BranchProbability FProb,
1869                                                bool InvertCond) {
1870   // Skip over not part of the tree and remember to invert op and operands at
1871   // next level.
1872   Value *NotCond;
1873   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
1874       InBlock(NotCond, CurBB->getBasicBlock())) {
1875     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1876                          !InvertCond);
1877     return;
1878   }
1879 
1880   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1881   // Compute the effective opcode for Cond, taking into account whether it needs
1882   // to be inverted, e.g.
1883   //   and (not (or A, B)), C
1884   // gets lowered as
1885   //   and (and (not A, not B), C)
1886   unsigned BOpc = 0;
1887   if (BOp) {
1888     BOpc = BOp->getOpcode();
1889     if (InvertCond) {
1890       if (BOpc == Instruction::And)
1891         BOpc = Instruction::Or;
1892       else if (BOpc == Instruction::Or)
1893         BOpc = Instruction::And;
1894     }
1895   }
1896 
1897   // If this node is not part of the or/and tree, emit it as a branch.
1898   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1899       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
1900       BOp->getParent() != CurBB->getBasicBlock() ||
1901       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1902       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1903     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1904                                  TProb, FProb, InvertCond);
1905     return;
1906   }
1907 
1908   //  Create TmpBB after CurBB.
1909   MachineFunction::iterator BBI(CurBB);
1910   MachineFunction &MF = DAG.getMachineFunction();
1911   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1912   CurBB->getParent()->insert(++BBI, TmpBB);
1913 
1914   if (Opc == Instruction::Or) {
1915     // Codegen X | Y as:
1916     // BB1:
1917     //   jmp_if_X TBB
1918     //   jmp TmpBB
1919     // TmpBB:
1920     //   jmp_if_Y TBB
1921     //   jmp FBB
1922     //
1923 
1924     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1925     // The requirement is that
1926     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1927     //     = TrueProb for original BB.
1928     // Assuming the original probabilities are A and B, one choice is to set
1929     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1930     // A/(1+B) and 2B/(1+B). This choice assumes that
1931     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1932     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1933     // TmpBB, but the math is more complicated.
1934 
1935     auto NewTrueProb = TProb / 2;
1936     auto NewFalseProb = TProb / 2 + FProb;
1937     // Emit the LHS condition.
1938     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1939                          NewTrueProb, NewFalseProb, InvertCond);
1940 
1941     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1942     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1943     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1944     // Emit the RHS condition into TmpBB.
1945     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1946                          Probs[0], Probs[1], InvertCond);
1947   } else {
1948     assert(Opc == Instruction::And && "Unknown merge op!");
1949     // Codegen X & Y as:
1950     // BB1:
1951     //   jmp_if_X TmpBB
1952     //   jmp FBB
1953     // TmpBB:
1954     //   jmp_if_Y TBB
1955     //   jmp FBB
1956     //
1957     //  This requires creation of TmpBB after CurBB.
1958 
1959     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1960     // The requirement is that
1961     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1962     //     = FalseProb for original BB.
1963     // Assuming the original probabilities are A and B, one choice is to set
1964     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1965     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1966     // TrueProb for BB1 * FalseProb for TmpBB.
1967 
1968     auto NewTrueProb = TProb + FProb / 2;
1969     auto NewFalseProb = FProb / 2;
1970     // Emit the LHS condition.
1971     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1972                          NewTrueProb, NewFalseProb, InvertCond);
1973 
1974     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1975     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1976     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1977     // Emit the RHS condition into TmpBB.
1978     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1979                          Probs[0], Probs[1], InvertCond);
1980   }
1981 }
1982 
1983 /// If the set of cases should be emitted as a series of branches, return true.
1984 /// If we should emit this as a bunch of and/or'd together conditions, return
1985 /// false.
1986 bool
1987 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1988   if (Cases.size() != 2) return true;
1989 
1990   // If this is two comparisons of the same values or'd or and'd together, they
1991   // will get folded into a single comparison, so don't emit two blocks.
1992   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1993        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1994       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1995        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1996     return false;
1997   }
1998 
1999   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2000   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2001   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2002       Cases[0].CC == Cases[1].CC &&
2003       isa<Constant>(Cases[0].CmpRHS) &&
2004       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2005     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2006       return false;
2007     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2008       return false;
2009   }
2010 
2011   return true;
2012 }
2013 
2014 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2015   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2016 
2017   // Update machine-CFG edges.
2018   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2019 
2020   if (I.isUnconditional()) {
2021     // Update machine-CFG edges.
2022     BrMBB->addSuccessor(Succ0MBB);
2023 
2024     // If this is not a fall-through branch or optimizations are switched off,
2025     // emit the branch.
2026     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2027       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2028                               MVT::Other, getControlRoot(),
2029                               DAG.getBasicBlock(Succ0MBB)));
2030 
2031     return;
2032   }
2033 
2034   // If this condition is one of the special cases we handle, do special stuff
2035   // now.
2036   const Value *CondVal = I.getCondition();
2037   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2038 
2039   // If this is a series of conditions that are or'd or and'd together, emit
2040   // this as a sequence of branches instead of setcc's with and/or operations.
2041   // As long as jumps are not expensive, this should improve performance.
2042   // For example, instead of something like:
2043   //     cmp A, B
2044   //     C = seteq
2045   //     cmp D, E
2046   //     F = setle
2047   //     or C, F
2048   //     jnz foo
2049   // Emit:
2050   //     cmp A, B
2051   //     je foo
2052   //     cmp D, E
2053   //     jle foo
2054   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2055     Instruction::BinaryOps Opcode = BOp->getOpcode();
2056     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2057         !I.getMetadata(LLVMContext::MD_unpredictable) &&
2058         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2059       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2060                            Opcode,
2061                            getEdgeProbability(BrMBB, Succ0MBB),
2062                            getEdgeProbability(BrMBB, Succ1MBB),
2063                            /*InvertCond=*/false);
2064       // If the compares in later blocks need to use values not currently
2065       // exported from this block, export them now.  This block should always
2066       // be the first entry.
2067       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2068 
2069       // Allow some cases to be rejected.
2070       if (ShouldEmitAsBranches(SwitchCases)) {
2071         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
2072           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
2073           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
2074         }
2075 
2076         // Emit the branch for this block.
2077         visitSwitchCase(SwitchCases[0], BrMBB);
2078         SwitchCases.erase(SwitchCases.begin());
2079         return;
2080       }
2081 
2082       // Okay, we decided not to do this, remove any inserted MBB's and clear
2083       // SwitchCases.
2084       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2085         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2086 
2087       SwitchCases.clear();
2088     }
2089   }
2090 
2091   // Create a CaseBlock record representing this branch.
2092   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2093                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2094 
2095   // Use visitSwitchCase to actually insert the fast branch sequence for this
2096   // cond branch.
2097   visitSwitchCase(CB, BrMBB);
2098 }
2099 
2100 /// visitSwitchCase - Emits the necessary code to represent a single node in
2101 /// the binary search tree resulting from lowering a switch instruction.
2102 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2103                                           MachineBasicBlock *SwitchBB) {
2104   SDValue Cond;
2105   SDValue CondLHS = getValue(CB.CmpLHS);
2106   SDLoc dl = CB.DL;
2107 
2108   // Build the setcc now.
2109   if (!CB.CmpMHS) {
2110     // Fold "(X == true)" to X and "(X == false)" to !X to
2111     // handle common cases produced by branch lowering.
2112     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2113         CB.CC == ISD::SETEQ)
2114       Cond = CondLHS;
2115     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2116              CB.CC == ISD::SETEQ) {
2117       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2118       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2119     } else
2120       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2121   } else {
2122     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2123 
2124     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2125     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2126 
2127     SDValue CmpOp = getValue(CB.CmpMHS);
2128     EVT VT = CmpOp.getValueType();
2129 
2130     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2131       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2132                           ISD::SETLE);
2133     } else {
2134       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2135                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2136       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2137                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2138     }
2139   }
2140 
2141   // Update successor info
2142   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2143   // TrueBB and FalseBB are always different unless the incoming IR is
2144   // degenerate. This only happens when running llc on weird IR.
2145   if (CB.TrueBB != CB.FalseBB)
2146     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2147   SwitchBB->normalizeSuccProbs();
2148 
2149   // If the lhs block is the next block, invert the condition so that we can
2150   // fall through to the lhs instead of the rhs block.
2151   if (CB.TrueBB == NextBlock(SwitchBB)) {
2152     std::swap(CB.TrueBB, CB.FalseBB);
2153     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2154     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2155   }
2156 
2157   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2158                                MVT::Other, getControlRoot(), Cond,
2159                                DAG.getBasicBlock(CB.TrueBB));
2160 
2161   // Insert the false branch. Do this even if it's a fall through branch,
2162   // this makes it easier to do DAG optimizations which require inverting
2163   // the branch condition.
2164   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2165                        DAG.getBasicBlock(CB.FalseBB));
2166 
2167   DAG.setRoot(BrCond);
2168 }
2169 
2170 /// visitJumpTable - Emit JumpTable node in the current MBB
2171 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2172   // Emit the code for the jump table
2173   assert(JT.Reg != -1U && "Should lower JT Header first!");
2174   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2175   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2176                                      JT.Reg, PTy);
2177   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2178   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2179                                     MVT::Other, Index.getValue(1),
2180                                     Table, Index);
2181   DAG.setRoot(BrJumpTable);
2182 }
2183 
2184 /// visitJumpTableHeader - This function emits necessary code to produce index
2185 /// in the JumpTable from switch case.
2186 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2187                                                JumpTableHeader &JTH,
2188                                                MachineBasicBlock *SwitchBB) {
2189   SDLoc dl = getCurSDLoc();
2190 
2191   // Subtract the lowest switch case value from the value being switched on and
2192   // conditional branch to default mbb if the result is greater than the
2193   // difference between smallest and largest cases.
2194   SDValue SwitchOp = getValue(JTH.SValue);
2195   EVT VT = SwitchOp.getValueType();
2196   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2197                             DAG.getConstant(JTH.First, dl, VT));
2198 
2199   // The SDNode we just created, which holds the value being switched on minus
2200   // the smallest case value, needs to be copied to a virtual register so it
2201   // can be used as an index into the jump table in a subsequent basic block.
2202   // This value may be smaller or larger than the target's pointer type, and
2203   // therefore require extension or truncating.
2204   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2205   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2206 
2207   unsigned JumpTableReg =
2208       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2209   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2210                                     JumpTableReg, SwitchOp);
2211   JT.Reg = JumpTableReg;
2212 
2213   // Emit the range check for the jump table, and branch to the default block
2214   // for the switch statement if the value being switched on exceeds the largest
2215   // case in the switch.
2216   SDValue CMP = DAG.getSetCC(
2217       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2218                                  Sub.getValueType()),
2219       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2220 
2221   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2222                                MVT::Other, CopyTo, CMP,
2223                                DAG.getBasicBlock(JT.Default));
2224 
2225   // Avoid emitting unnecessary branches to the next block.
2226   if (JT.MBB != NextBlock(SwitchBB))
2227     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2228                          DAG.getBasicBlock(JT.MBB));
2229 
2230   DAG.setRoot(BrCond);
2231 }
2232 
2233 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2234 /// variable if there exists one.
2235 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2236                                  SDValue &Chain) {
2237   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2238   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2239   MachineFunction &MF = DAG.getMachineFunction();
2240   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2241   MachineSDNode *Node =
2242       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2243   if (Global) {
2244     MachinePointerInfo MPInfo(Global);
2245     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2246                  MachineMemOperand::MODereferenceable;
2247     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2248         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2249     DAG.setNodeMemRefs(Node, {MemRef});
2250   }
2251   return SDValue(Node, 0);
2252 }
2253 
2254 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2255 /// tail spliced into a stack protector check success bb.
2256 ///
2257 /// For a high level explanation of how this fits into the stack protector
2258 /// generation see the comment on the declaration of class
2259 /// StackProtectorDescriptor.
2260 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2261                                                   MachineBasicBlock *ParentBB) {
2262 
2263   // First create the loads to the guard/stack slot for the comparison.
2264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2265   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2266 
2267   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2268   int FI = MFI.getStackProtectorIndex();
2269 
2270   SDValue Guard;
2271   SDLoc dl = getCurSDLoc();
2272   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2273   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2274   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2275 
2276   // Generate code to load the content of the guard slot.
2277   SDValue GuardVal = DAG.getLoad(
2278       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2279       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2280       MachineMemOperand::MOVolatile);
2281 
2282   if (TLI.useStackGuardXorFP())
2283     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2284 
2285   // Retrieve guard check function, nullptr if instrumentation is inlined.
2286   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2287     // The target provides a guard check function to validate the guard value.
2288     // Generate a call to that function with the content of the guard slot as
2289     // argument.
2290     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2291     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2292 
2293     TargetLowering::ArgListTy Args;
2294     TargetLowering::ArgListEntry Entry;
2295     Entry.Node = GuardVal;
2296     Entry.Ty = FnTy->getParamType(0);
2297     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2298       Entry.IsInReg = true;
2299     Args.push_back(Entry);
2300 
2301     TargetLowering::CallLoweringInfo CLI(DAG);
2302     CLI.setDebugLoc(getCurSDLoc())
2303         .setChain(DAG.getEntryNode())
2304         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2305                    getValue(GuardCheckFn), std::move(Args));
2306 
2307     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2308     DAG.setRoot(Result.second);
2309     return;
2310   }
2311 
2312   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2313   // Otherwise, emit a volatile load to retrieve the stack guard value.
2314   SDValue Chain = DAG.getEntryNode();
2315   if (TLI.useLoadStackGuardNode()) {
2316     Guard = getLoadStackGuard(DAG, dl, Chain);
2317   } else {
2318     const Value *IRGuard = TLI.getSDagStackGuard(M);
2319     SDValue GuardPtr = getValue(IRGuard);
2320 
2321     Guard =
2322         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2323                     Align, MachineMemOperand::MOVolatile);
2324   }
2325 
2326   // Perform the comparison via a subtract/getsetcc.
2327   EVT VT = Guard.getValueType();
2328   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2329 
2330   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2331                                                         *DAG.getContext(),
2332                                                         Sub.getValueType()),
2333                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2334 
2335   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2336   // branch to failure MBB.
2337   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2338                                MVT::Other, GuardVal.getOperand(0),
2339                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2340   // Otherwise branch to success MBB.
2341   SDValue Br = DAG.getNode(ISD::BR, dl,
2342                            MVT::Other, BrCond,
2343                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2344 
2345   DAG.setRoot(Br);
2346 }
2347 
2348 /// Codegen the failure basic block for a stack protector check.
2349 ///
2350 /// A failure stack protector machine basic block consists simply of a call to
2351 /// __stack_chk_fail().
2352 ///
2353 /// For a high level explanation of how this fits into the stack protector
2354 /// generation see the comment on the declaration of class
2355 /// StackProtectorDescriptor.
2356 void
2357 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2358   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2359   SDValue Chain =
2360       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2361                       None, false, getCurSDLoc(), false, false).second;
2362   DAG.setRoot(Chain);
2363 }
2364 
2365 /// visitBitTestHeader - This function emits necessary code to produce value
2366 /// suitable for "bit tests"
2367 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2368                                              MachineBasicBlock *SwitchBB) {
2369   SDLoc dl = getCurSDLoc();
2370 
2371   // Subtract the minimum value
2372   SDValue SwitchOp = getValue(B.SValue);
2373   EVT VT = SwitchOp.getValueType();
2374   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2375                             DAG.getConstant(B.First, dl, VT));
2376 
2377   // Check range
2378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2379   SDValue RangeCmp = DAG.getSetCC(
2380       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2381                                  Sub.getValueType()),
2382       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2383 
2384   // Determine the type of the test operands.
2385   bool UsePtrType = false;
2386   if (!TLI.isTypeLegal(VT))
2387     UsePtrType = true;
2388   else {
2389     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2390       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2391         // Switch table case range are encoded into series of masks.
2392         // Just use pointer type, it's guaranteed to fit.
2393         UsePtrType = true;
2394         break;
2395       }
2396   }
2397   if (UsePtrType) {
2398     VT = TLI.getPointerTy(DAG.getDataLayout());
2399     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2400   }
2401 
2402   B.RegVT = VT.getSimpleVT();
2403   B.Reg = FuncInfo.CreateReg(B.RegVT);
2404   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2405 
2406   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2407 
2408   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2409   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2410   SwitchBB->normalizeSuccProbs();
2411 
2412   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2413                                 MVT::Other, CopyTo, RangeCmp,
2414                                 DAG.getBasicBlock(B.Default));
2415 
2416   // Avoid emitting unnecessary branches to the next block.
2417   if (MBB != NextBlock(SwitchBB))
2418     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2419                           DAG.getBasicBlock(MBB));
2420 
2421   DAG.setRoot(BrRange);
2422 }
2423 
2424 /// visitBitTestCase - this function produces one "bit test"
2425 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2426                                            MachineBasicBlock* NextMBB,
2427                                            BranchProbability BranchProbToNext,
2428                                            unsigned Reg,
2429                                            BitTestCase &B,
2430                                            MachineBasicBlock *SwitchBB) {
2431   SDLoc dl = getCurSDLoc();
2432   MVT VT = BB.RegVT;
2433   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2434   SDValue Cmp;
2435   unsigned PopCount = countPopulation(B.Mask);
2436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2437   if (PopCount == 1) {
2438     // Testing for a single bit; just compare the shift count with what it
2439     // would need to be to shift a 1 bit in that position.
2440     Cmp = DAG.getSetCC(
2441         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2442         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2443         ISD::SETEQ);
2444   } else if (PopCount == BB.Range) {
2445     // There is only one zero bit in the range, test for it directly.
2446     Cmp = DAG.getSetCC(
2447         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2448         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2449         ISD::SETNE);
2450   } else {
2451     // Make desired shift
2452     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2453                                     DAG.getConstant(1, dl, VT), ShiftOp);
2454 
2455     // Emit bit tests and jumps
2456     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2457                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2458     Cmp = DAG.getSetCC(
2459         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2460         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2461   }
2462 
2463   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2464   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2465   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2466   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2467   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2468   // one as they are relative probabilities (and thus work more like weights),
2469   // and hence we need to normalize them to let the sum of them become one.
2470   SwitchBB->normalizeSuccProbs();
2471 
2472   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2473                               MVT::Other, getControlRoot(),
2474                               Cmp, DAG.getBasicBlock(B.TargetBB));
2475 
2476   // Avoid emitting unnecessary branches to the next block.
2477   if (NextMBB != NextBlock(SwitchBB))
2478     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2479                         DAG.getBasicBlock(NextMBB));
2480 
2481   DAG.setRoot(BrAnd);
2482 }
2483 
2484 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2485   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2486 
2487   // Retrieve successors. Look through artificial IR level blocks like
2488   // catchswitch for successors.
2489   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2490   const BasicBlock *EHPadBB = I.getSuccessor(1);
2491 
2492   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2493   // have to do anything here to lower funclet bundles.
2494   assert(!I.hasOperandBundlesOtherThan(
2495              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2496          "Cannot lower invokes with arbitrary operand bundles yet!");
2497 
2498   const Value *Callee(I.getCalledValue());
2499   const Function *Fn = dyn_cast<Function>(Callee);
2500   if (isa<InlineAsm>(Callee))
2501     visitInlineAsm(&I);
2502   else if (Fn && Fn->isIntrinsic()) {
2503     switch (Fn->getIntrinsicID()) {
2504     default:
2505       llvm_unreachable("Cannot invoke this intrinsic");
2506     case Intrinsic::donothing:
2507       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2508       break;
2509     case Intrinsic::experimental_patchpoint_void:
2510     case Intrinsic::experimental_patchpoint_i64:
2511       visitPatchpoint(&I, EHPadBB);
2512       break;
2513     case Intrinsic::experimental_gc_statepoint:
2514       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2515       break;
2516     }
2517   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2518     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2519     // Eventually we will support lowering the @llvm.experimental.deoptimize
2520     // intrinsic, and right now there are no plans to support other intrinsics
2521     // with deopt state.
2522     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2523   } else {
2524     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2525   }
2526 
2527   // If the value of the invoke is used outside of its defining block, make it
2528   // available as a virtual register.
2529   // We already took care of the exported value for the statepoint instruction
2530   // during call to the LowerStatepoint.
2531   if (!isStatepoint(I)) {
2532     CopyToExportRegsIfNeeded(&I);
2533   }
2534 
2535   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2536   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2537   BranchProbability EHPadBBProb =
2538       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2539           : BranchProbability::getZero();
2540   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2541 
2542   // Update successor info.
2543   addSuccessorWithProb(InvokeMBB, Return);
2544   for (auto &UnwindDest : UnwindDests) {
2545     UnwindDest.first->setIsEHPad();
2546     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2547   }
2548   InvokeMBB->normalizeSuccProbs();
2549 
2550   // Drop into normal successor.
2551   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2552                           MVT::Other, getControlRoot(),
2553                           DAG.getBasicBlock(Return)));
2554 }
2555 
2556 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2557   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2558 }
2559 
2560 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2561   assert(FuncInfo.MBB->isEHPad() &&
2562          "Call to landingpad not in landing pad!");
2563 
2564   // If there aren't registers to copy the values into (e.g., during SjLj
2565   // exceptions), then don't bother to create these DAG nodes.
2566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2567   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2568   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2569       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2570     return;
2571 
2572   // If landingpad's return type is token type, we don't create DAG nodes
2573   // for its exception pointer and selector value. The extraction of exception
2574   // pointer or selector value from token type landingpads is not currently
2575   // supported.
2576   if (LP.getType()->isTokenTy())
2577     return;
2578 
2579   SmallVector<EVT, 2> ValueVTs;
2580   SDLoc dl = getCurSDLoc();
2581   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2582   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2583 
2584   // Get the two live-in registers as SDValues. The physregs have already been
2585   // copied into virtual registers.
2586   SDValue Ops[2];
2587   if (FuncInfo.ExceptionPointerVirtReg) {
2588     Ops[0] = DAG.getZExtOrTrunc(
2589         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2590                            FuncInfo.ExceptionPointerVirtReg,
2591                            TLI.getPointerTy(DAG.getDataLayout())),
2592         dl, ValueVTs[0]);
2593   } else {
2594     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2595   }
2596   Ops[1] = DAG.getZExtOrTrunc(
2597       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2598                          FuncInfo.ExceptionSelectorVirtReg,
2599                          TLI.getPointerTy(DAG.getDataLayout())),
2600       dl, ValueVTs[1]);
2601 
2602   // Merge into one.
2603   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2604                             DAG.getVTList(ValueVTs), Ops);
2605   setValue(&LP, Res);
2606 }
2607 
2608 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2609 #ifndef NDEBUG
2610   for (const CaseCluster &CC : Clusters)
2611     assert(CC.Low == CC.High && "Input clusters must be single-case");
2612 #endif
2613 
2614   llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
2615     return a.Low->getValue().slt(b.Low->getValue());
2616   });
2617 
2618   // Merge adjacent clusters with the same destination.
2619   const unsigned N = Clusters.size();
2620   unsigned DstIndex = 0;
2621   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2622     CaseCluster &CC = Clusters[SrcIndex];
2623     const ConstantInt *CaseVal = CC.Low;
2624     MachineBasicBlock *Succ = CC.MBB;
2625 
2626     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2627         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2628       // If this case has the same successor and is a neighbour, merge it into
2629       // the previous cluster.
2630       Clusters[DstIndex - 1].High = CaseVal;
2631       Clusters[DstIndex - 1].Prob += CC.Prob;
2632     } else {
2633       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2634                    sizeof(Clusters[SrcIndex]));
2635     }
2636   }
2637   Clusters.resize(DstIndex);
2638 }
2639 
2640 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2641                                            MachineBasicBlock *Last) {
2642   // Update JTCases.
2643   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2644     if (JTCases[i].first.HeaderBB == First)
2645       JTCases[i].first.HeaderBB = Last;
2646 
2647   // Update BitTestCases.
2648   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2649     if (BitTestCases[i].Parent == First)
2650       BitTestCases[i].Parent = Last;
2651 }
2652 
2653 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2654   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2655 
2656   // Update machine-CFG edges with unique successors.
2657   SmallSet<BasicBlock*, 32> Done;
2658   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2659     BasicBlock *BB = I.getSuccessor(i);
2660     bool Inserted = Done.insert(BB).second;
2661     if (!Inserted)
2662         continue;
2663 
2664     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2665     addSuccessorWithProb(IndirectBrMBB, Succ);
2666   }
2667   IndirectBrMBB->normalizeSuccProbs();
2668 
2669   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2670                           MVT::Other, getControlRoot(),
2671                           getValue(I.getAddress())));
2672 }
2673 
2674 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2675   if (!DAG.getTarget().Options.TrapUnreachable)
2676     return;
2677 
2678   // We may be able to ignore unreachable behind a noreturn call.
2679   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2680     const BasicBlock &BB = *I.getParent();
2681     if (&I != &BB.front()) {
2682       BasicBlock::const_iterator PredI =
2683         std::prev(BasicBlock::const_iterator(&I));
2684       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2685         if (Call->doesNotReturn())
2686           return;
2687       }
2688     }
2689   }
2690 
2691   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2692 }
2693 
2694 void SelectionDAGBuilder::visitFSub(const User &I) {
2695   // -0.0 - X --> fneg
2696   Type *Ty = I.getType();
2697   if (isa<Constant>(I.getOperand(0)) &&
2698       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2699     SDValue Op2 = getValue(I.getOperand(1));
2700     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2701                              Op2.getValueType(), Op2));
2702     return;
2703   }
2704 
2705   visitBinary(I, ISD::FSUB);
2706 }
2707 
2708 /// Checks if the given instruction performs a vector reduction, in which case
2709 /// we have the freedom to alter the elements in the result as long as the
2710 /// reduction of them stays unchanged.
2711 static bool isVectorReductionOp(const User *I) {
2712   const Instruction *Inst = dyn_cast<Instruction>(I);
2713   if (!Inst || !Inst->getType()->isVectorTy())
2714     return false;
2715 
2716   auto OpCode = Inst->getOpcode();
2717   switch (OpCode) {
2718   case Instruction::Add:
2719   case Instruction::Mul:
2720   case Instruction::And:
2721   case Instruction::Or:
2722   case Instruction::Xor:
2723     break;
2724   case Instruction::FAdd:
2725   case Instruction::FMul:
2726     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2727       if (FPOp->getFastMathFlags().isFast())
2728         break;
2729     LLVM_FALLTHROUGH;
2730   default:
2731     return false;
2732   }
2733 
2734   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2735   // Ensure the reduction size is a power of 2.
2736   if (!isPowerOf2_32(ElemNum))
2737     return false;
2738 
2739   unsigned ElemNumToReduce = ElemNum;
2740 
2741   // Do DFS search on the def-use chain from the given instruction. We only
2742   // allow four kinds of operations during the search until we reach the
2743   // instruction that extracts the first element from the vector:
2744   //
2745   //   1. The reduction operation of the same opcode as the given instruction.
2746   //
2747   //   2. PHI node.
2748   //
2749   //   3. ShuffleVector instruction together with a reduction operation that
2750   //      does a partial reduction.
2751   //
2752   //   4. ExtractElement that extracts the first element from the vector, and we
2753   //      stop searching the def-use chain here.
2754   //
2755   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2756   // from 1-3 to the stack to continue the DFS. The given instruction is not
2757   // a reduction operation if we meet any other instructions other than those
2758   // listed above.
2759 
2760   SmallVector<const User *, 16> UsersToVisit{Inst};
2761   SmallPtrSet<const User *, 16> Visited;
2762   bool ReduxExtracted = false;
2763 
2764   while (!UsersToVisit.empty()) {
2765     auto User = UsersToVisit.back();
2766     UsersToVisit.pop_back();
2767     if (!Visited.insert(User).second)
2768       continue;
2769 
2770     for (const auto &U : User->users()) {
2771       auto Inst = dyn_cast<Instruction>(U);
2772       if (!Inst)
2773         return false;
2774 
2775       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2776         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2777           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2778             return false;
2779         UsersToVisit.push_back(U);
2780       } else if (const ShuffleVectorInst *ShufInst =
2781                      dyn_cast<ShuffleVectorInst>(U)) {
2782         // Detect the following pattern: A ShuffleVector instruction together
2783         // with a reduction that do partial reduction on the first and second
2784         // ElemNumToReduce / 2 elements, and store the result in
2785         // ElemNumToReduce / 2 elements in another vector.
2786 
2787         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2788         if (ResultElements < ElemNum)
2789           return false;
2790 
2791         if (ElemNumToReduce == 1)
2792           return false;
2793         if (!isa<UndefValue>(U->getOperand(1)))
2794           return false;
2795         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2796           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2797             return false;
2798         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2799           if (ShufInst->getMaskValue(i) != -1)
2800             return false;
2801 
2802         // There is only one user of this ShuffleVector instruction, which
2803         // must be a reduction operation.
2804         if (!U->hasOneUse())
2805           return false;
2806 
2807         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2808         if (!U2 || U2->getOpcode() != OpCode)
2809           return false;
2810 
2811         // Check operands of the reduction operation.
2812         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2813             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2814           UsersToVisit.push_back(U2);
2815           ElemNumToReduce /= 2;
2816         } else
2817           return false;
2818       } else if (isa<ExtractElementInst>(U)) {
2819         // At this moment we should have reduced all elements in the vector.
2820         if (ElemNumToReduce != 1)
2821           return false;
2822 
2823         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2824         if (!Val || !Val->isZero())
2825           return false;
2826 
2827         ReduxExtracted = true;
2828       } else
2829         return false;
2830     }
2831   }
2832   return ReduxExtracted;
2833 }
2834 
2835 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
2836   SDNodeFlags Flags;
2837 
2838   SDValue Op = getValue(I.getOperand(0));
2839   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
2840                                     Op, Flags);
2841   setValue(&I, UnNodeValue);
2842 }
2843 
2844 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
2845   SDNodeFlags Flags;
2846   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
2847     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
2848     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
2849   }
2850   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
2851     Flags.setExact(ExactOp->isExact());
2852   }
2853   if (isVectorReductionOp(&I)) {
2854     Flags.setVectorReduction(true);
2855     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2856   }
2857 
2858   SDValue Op1 = getValue(I.getOperand(0));
2859   SDValue Op2 = getValue(I.getOperand(1));
2860   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
2861                                      Op1, Op2, Flags);
2862   setValue(&I, BinNodeValue);
2863 }
2864 
2865 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2866   SDValue Op1 = getValue(I.getOperand(0));
2867   SDValue Op2 = getValue(I.getOperand(1));
2868 
2869   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2870       Op1.getValueType(), DAG.getDataLayout());
2871 
2872   // Coerce the shift amount to the right type if we can.
2873   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2874     unsigned ShiftSize = ShiftTy.getSizeInBits();
2875     unsigned Op2Size = Op2.getValueSizeInBits();
2876     SDLoc DL = getCurSDLoc();
2877 
2878     // If the operand is smaller than the shift count type, promote it.
2879     if (ShiftSize > Op2Size)
2880       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2881 
2882     // If the operand is larger than the shift count type but the shift
2883     // count type has enough bits to represent any shift value, truncate
2884     // it now. This is a common case and it exposes the truncate to
2885     // optimization early.
2886     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2887       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2888     // Otherwise we'll need to temporarily settle for some other convenient
2889     // type.  Type legalization will make adjustments once the shiftee is split.
2890     else
2891       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2892   }
2893 
2894   bool nuw = false;
2895   bool nsw = false;
2896   bool exact = false;
2897 
2898   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2899 
2900     if (const OverflowingBinaryOperator *OFBinOp =
2901             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2902       nuw = OFBinOp->hasNoUnsignedWrap();
2903       nsw = OFBinOp->hasNoSignedWrap();
2904     }
2905     if (const PossiblyExactOperator *ExactOp =
2906             dyn_cast<const PossiblyExactOperator>(&I))
2907       exact = ExactOp->isExact();
2908   }
2909   SDNodeFlags Flags;
2910   Flags.setExact(exact);
2911   Flags.setNoSignedWrap(nsw);
2912   Flags.setNoUnsignedWrap(nuw);
2913   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2914                             Flags);
2915   setValue(&I, Res);
2916 }
2917 
2918 void SelectionDAGBuilder::visitSDiv(const User &I) {
2919   SDValue Op1 = getValue(I.getOperand(0));
2920   SDValue Op2 = getValue(I.getOperand(1));
2921 
2922   SDNodeFlags Flags;
2923   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2924                  cast<PossiblyExactOperator>(&I)->isExact());
2925   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2926                            Op2, Flags));
2927 }
2928 
2929 void SelectionDAGBuilder::visitICmp(const User &I) {
2930   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2931   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2932     predicate = IC->getPredicate();
2933   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2934     predicate = ICmpInst::Predicate(IC->getPredicate());
2935   SDValue Op1 = getValue(I.getOperand(0));
2936   SDValue Op2 = getValue(I.getOperand(1));
2937   ISD::CondCode Opcode = getICmpCondCode(predicate);
2938 
2939   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2940                                                         I.getType());
2941   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2942 }
2943 
2944 void SelectionDAGBuilder::visitFCmp(const User &I) {
2945   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2946   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2947     predicate = FC->getPredicate();
2948   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2949     predicate = FCmpInst::Predicate(FC->getPredicate());
2950   SDValue Op1 = getValue(I.getOperand(0));
2951   SDValue Op2 = getValue(I.getOperand(1));
2952 
2953   ISD::CondCode Condition = getFCmpCondCode(predicate);
2954   auto *FPMO = dyn_cast<FPMathOperator>(&I);
2955   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
2956     Condition = getFCmpCodeWithoutNaN(Condition);
2957 
2958   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2959                                                         I.getType());
2960   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2961 }
2962 
2963 // Check if the condition of the select has one use or two users that are both
2964 // selects with the same condition.
2965 static bool hasOnlySelectUsers(const Value *Cond) {
2966   return llvm::all_of(Cond->users(), [](const Value *V) {
2967     return isa<SelectInst>(V);
2968   });
2969 }
2970 
2971 void SelectionDAGBuilder::visitSelect(const User &I) {
2972   SmallVector<EVT, 4> ValueVTs;
2973   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2974                   ValueVTs);
2975   unsigned NumValues = ValueVTs.size();
2976   if (NumValues == 0) return;
2977 
2978   SmallVector<SDValue, 4> Values(NumValues);
2979   SDValue Cond     = getValue(I.getOperand(0));
2980   SDValue LHSVal   = getValue(I.getOperand(1));
2981   SDValue RHSVal   = getValue(I.getOperand(2));
2982   auto BaseOps = {Cond};
2983   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2984     ISD::VSELECT : ISD::SELECT;
2985 
2986   // Min/max matching is only viable if all output VTs are the same.
2987   if (is_splat(ValueVTs)) {
2988     EVT VT = ValueVTs[0];
2989     LLVMContext &Ctx = *DAG.getContext();
2990     auto &TLI = DAG.getTargetLoweringInfo();
2991 
2992     // We care about the legality of the operation after it has been type
2993     // legalized.
2994     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2995            VT != TLI.getTypeToTransformTo(Ctx, VT))
2996       VT = TLI.getTypeToTransformTo(Ctx, VT);
2997 
2998     // If the vselect is legal, assume we want to leave this as a vector setcc +
2999     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3000     // min/max is legal on the scalar type.
3001     bool UseScalarMinMax = VT.isVector() &&
3002       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3003 
3004     Value *LHS, *RHS;
3005     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3006     ISD::NodeType Opc = ISD::DELETED_NODE;
3007     switch (SPR.Flavor) {
3008     case SPF_UMAX:    Opc = ISD::UMAX; break;
3009     case SPF_UMIN:    Opc = ISD::UMIN; break;
3010     case SPF_SMAX:    Opc = ISD::SMAX; break;
3011     case SPF_SMIN:    Opc = ISD::SMIN; break;
3012     case SPF_FMINNUM:
3013       switch (SPR.NaNBehavior) {
3014       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3015       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3016       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3017       case SPNB_RETURNS_ANY: {
3018         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3019           Opc = ISD::FMINNUM;
3020         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3021           Opc = ISD::FMINIMUM;
3022         else if (UseScalarMinMax)
3023           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3024             ISD::FMINNUM : ISD::FMINIMUM;
3025         break;
3026       }
3027       }
3028       break;
3029     case SPF_FMAXNUM:
3030       switch (SPR.NaNBehavior) {
3031       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3032       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3033       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3034       case SPNB_RETURNS_ANY:
3035 
3036         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3037           Opc = ISD::FMAXNUM;
3038         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3039           Opc = ISD::FMAXIMUM;
3040         else if (UseScalarMinMax)
3041           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3042             ISD::FMAXNUM : ISD::FMAXIMUM;
3043         break;
3044       }
3045       break;
3046     default: break;
3047     }
3048 
3049     if (Opc != ISD::DELETED_NODE &&
3050         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3051          (UseScalarMinMax &&
3052           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3053         // If the underlying comparison instruction is used by any other
3054         // instruction, the consumed instructions won't be destroyed, so it is
3055         // not profitable to convert to a min/max.
3056         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3057       OpCode = Opc;
3058       LHSVal = getValue(LHS);
3059       RHSVal = getValue(RHS);
3060       BaseOps = {};
3061     }
3062   }
3063 
3064   for (unsigned i = 0; i != NumValues; ++i) {
3065     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3066     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3067     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3068     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
3069                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
3070                             Ops);
3071   }
3072 
3073   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3074                            DAG.getVTList(ValueVTs), Values));
3075 }
3076 
3077 void SelectionDAGBuilder::visitTrunc(const User &I) {
3078   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3079   SDValue N = getValue(I.getOperand(0));
3080   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3081                                                         I.getType());
3082   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3083 }
3084 
3085 void SelectionDAGBuilder::visitZExt(const User &I) {
3086   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3087   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3088   SDValue N = getValue(I.getOperand(0));
3089   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3090                                                         I.getType());
3091   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3092 }
3093 
3094 void SelectionDAGBuilder::visitSExt(const User &I) {
3095   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3096   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3097   SDValue N = getValue(I.getOperand(0));
3098   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3099                                                         I.getType());
3100   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3101 }
3102 
3103 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3104   // FPTrunc is never a no-op cast, no need to check
3105   SDValue N = getValue(I.getOperand(0));
3106   SDLoc dl = getCurSDLoc();
3107   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3108   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3109   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3110                            DAG.getTargetConstant(
3111                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3112 }
3113 
3114 void SelectionDAGBuilder::visitFPExt(const User &I) {
3115   // FPExt is never a no-op cast, no need to check
3116   SDValue N = getValue(I.getOperand(0));
3117   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3118                                                         I.getType());
3119   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3120 }
3121 
3122 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3123   // FPToUI is never a no-op cast, no need to check
3124   SDValue N = getValue(I.getOperand(0));
3125   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3126                                                         I.getType());
3127   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3128 }
3129 
3130 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3131   // FPToSI is never a no-op cast, no need to check
3132   SDValue N = getValue(I.getOperand(0));
3133   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3134                                                         I.getType());
3135   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3136 }
3137 
3138 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3139   // UIToFP is never a no-op cast, no need to check
3140   SDValue N = getValue(I.getOperand(0));
3141   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3142                                                         I.getType());
3143   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3144 }
3145 
3146 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3147   // SIToFP is never a no-op cast, no need to check
3148   SDValue N = getValue(I.getOperand(0));
3149   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3150                                                         I.getType());
3151   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3152 }
3153 
3154 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3155   // What to do depends on the size of the integer and the size of the pointer.
3156   // We can either truncate, zero extend, or no-op, accordingly.
3157   SDValue N = getValue(I.getOperand(0));
3158   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3159                                                         I.getType());
3160   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3161 }
3162 
3163 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3164   // What to do depends on the size of the integer and the size of the pointer.
3165   // We can either truncate, zero extend, or no-op, accordingly.
3166   SDValue N = getValue(I.getOperand(0));
3167   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3168                                                         I.getType());
3169   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3170 }
3171 
3172 void SelectionDAGBuilder::visitBitCast(const User &I) {
3173   SDValue N = getValue(I.getOperand(0));
3174   SDLoc dl = getCurSDLoc();
3175   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3176                                                         I.getType());
3177 
3178   // BitCast assures us that source and destination are the same size so this is
3179   // either a BITCAST or a no-op.
3180   if (DestVT != N.getValueType())
3181     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3182                              DestVT, N)); // convert types.
3183   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3184   // might fold any kind of constant expression to an integer constant and that
3185   // is not what we are looking for. Only recognize a bitcast of a genuine
3186   // constant integer as an opaque constant.
3187   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3188     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3189                                  /*isOpaque*/true));
3190   else
3191     setValue(&I, N);            // noop cast.
3192 }
3193 
3194 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3195   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3196   const Value *SV = I.getOperand(0);
3197   SDValue N = getValue(SV);
3198   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3199 
3200   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3201   unsigned DestAS = I.getType()->getPointerAddressSpace();
3202 
3203   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3204     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3205 
3206   setValue(&I, N);
3207 }
3208 
3209 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3210   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3211   SDValue InVec = getValue(I.getOperand(0));
3212   SDValue InVal = getValue(I.getOperand(1));
3213   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3214                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3215   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3216                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3217                            InVec, InVal, InIdx));
3218 }
3219 
3220 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3221   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3222   SDValue InVec = getValue(I.getOperand(0));
3223   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3224                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3225   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3226                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3227                            InVec, InIdx));
3228 }
3229 
3230 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3231   SDValue Src1 = getValue(I.getOperand(0));
3232   SDValue Src2 = getValue(I.getOperand(1));
3233   SDLoc DL = getCurSDLoc();
3234 
3235   SmallVector<int, 8> Mask;
3236   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3237   unsigned MaskNumElts = Mask.size();
3238 
3239   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3240   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3241   EVT SrcVT = Src1.getValueType();
3242   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3243 
3244   if (SrcNumElts == MaskNumElts) {
3245     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3246     return;
3247   }
3248 
3249   // Normalize the shuffle vector since mask and vector length don't match.
3250   if (SrcNumElts < MaskNumElts) {
3251     // Mask is longer than the source vectors. We can use concatenate vector to
3252     // make the mask and vectors lengths match.
3253 
3254     if (MaskNumElts % SrcNumElts == 0) {
3255       // Mask length is a multiple of the source vector length.
3256       // Check if the shuffle is some kind of concatenation of the input
3257       // vectors.
3258       unsigned NumConcat = MaskNumElts / SrcNumElts;
3259       bool IsConcat = true;
3260       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3261       for (unsigned i = 0; i != MaskNumElts; ++i) {
3262         int Idx = Mask[i];
3263         if (Idx < 0)
3264           continue;
3265         // Ensure the indices in each SrcVT sized piece are sequential and that
3266         // the same source is used for the whole piece.
3267         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3268             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3269              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3270           IsConcat = false;
3271           break;
3272         }
3273         // Remember which source this index came from.
3274         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3275       }
3276 
3277       // The shuffle is concatenating multiple vectors together. Just emit
3278       // a CONCAT_VECTORS operation.
3279       if (IsConcat) {
3280         SmallVector<SDValue, 8> ConcatOps;
3281         for (auto Src : ConcatSrcs) {
3282           if (Src < 0)
3283             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3284           else if (Src == 0)
3285             ConcatOps.push_back(Src1);
3286           else
3287             ConcatOps.push_back(Src2);
3288         }
3289         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3290         return;
3291       }
3292     }
3293 
3294     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3295     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3296     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3297                                     PaddedMaskNumElts);
3298 
3299     // Pad both vectors with undefs to make them the same length as the mask.
3300     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3301 
3302     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3303     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3304     MOps1[0] = Src1;
3305     MOps2[0] = Src2;
3306 
3307     Src1 = Src1.isUndef()
3308                ? DAG.getUNDEF(PaddedVT)
3309                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3310     Src2 = Src2.isUndef()
3311                ? DAG.getUNDEF(PaddedVT)
3312                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3313 
3314     // Readjust mask for new input vector length.
3315     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3316     for (unsigned i = 0; i != MaskNumElts; ++i) {
3317       int Idx = Mask[i];
3318       if (Idx >= (int)SrcNumElts)
3319         Idx -= SrcNumElts - PaddedMaskNumElts;
3320       MappedOps[i] = Idx;
3321     }
3322 
3323     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3324 
3325     // If the concatenated vector was padded, extract a subvector with the
3326     // correct number of elements.
3327     if (MaskNumElts != PaddedMaskNumElts)
3328       Result = DAG.getNode(
3329           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3330           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3331 
3332     setValue(&I, Result);
3333     return;
3334   }
3335 
3336   if (SrcNumElts > MaskNumElts) {
3337     // Analyze the access pattern of the vector to see if we can extract
3338     // two subvectors and do the shuffle.
3339     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3340     bool CanExtract = true;
3341     for (int Idx : Mask) {
3342       unsigned Input = 0;
3343       if (Idx < 0)
3344         continue;
3345 
3346       if (Idx >= (int)SrcNumElts) {
3347         Input = 1;
3348         Idx -= SrcNumElts;
3349       }
3350 
3351       // If all the indices come from the same MaskNumElts sized portion of
3352       // the sources we can use extract. Also make sure the extract wouldn't
3353       // extract past the end of the source.
3354       int NewStartIdx = alignDown(Idx, MaskNumElts);
3355       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3356           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3357         CanExtract = false;
3358       // Make sure we always update StartIdx as we use it to track if all
3359       // elements are undef.
3360       StartIdx[Input] = NewStartIdx;
3361     }
3362 
3363     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3364       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3365       return;
3366     }
3367     if (CanExtract) {
3368       // Extract appropriate subvector and generate a vector shuffle
3369       for (unsigned Input = 0; Input < 2; ++Input) {
3370         SDValue &Src = Input == 0 ? Src1 : Src2;
3371         if (StartIdx[Input] < 0)
3372           Src = DAG.getUNDEF(VT);
3373         else {
3374           Src = DAG.getNode(
3375               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3376               DAG.getConstant(StartIdx[Input], DL,
3377                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3378         }
3379       }
3380 
3381       // Calculate new mask.
3382       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3383       for (int &Idx : MappedOps) {
3384         if (Idx >= (int)SrcNumElts)
3385           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3386         else if (Idx >= 0)
3387           Idx -= StartIdx[0];
3388       }
3389 
3390       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3391       return;
3392     }
3393   }
3394 
3395   // We can't use either concat vectors or extract subvectors so fall back to
3396   // replacing the shuffle with extract and build vector.
3397   // to insert and build vector.
3398   EVT EltVT = VT.getVectorElementType();
3399   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3400   SmallVector<SDValue,8> Ops;
3401   for (int Idx : Mask) {
3402     SDValue Res;
3403 
3404     if (Idx < 0) {
3405       Res = DAG.getUNDEF(EltVT);
3406     } else {
3407       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3408       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3409 
3410       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3411                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3412     }
3413 
3414     Ops.push_back(Res);
3415   }
3416 
3417   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3418 }
3419 
3420 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3421   ArrayRef<unsigned> Indices;
3422   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3423     Indices = IV->getIndices();
3424   else
3425     Indices = cast<ConstantExpr>(&I)->getIndices();
3426 
3427   const Value *Op0 = I.getOperand(0);
3428   const Value *Op1 = I.getOperand(1);
3429   Type *AggTy = I.getType();
3430   Type *ValTy = Op1->getType();
3431   bool IntoUndef = isa<UndefValue>(Op0);
3432   bool FromUndef = isa<UndefValue>(Op1);
3433 
3434   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3435 
3436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3437   SmallVector<EVT, 4> AggValueVTs;
3438   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3439   SmallVector<EVT, 4> ValValueVTs;
3440   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3441 
3442   unsigned NumAggValues = AggValueVTs.size();
3443   unsigned NumValValues = ValValueVTs.size();
3444   SmallVector<SDValue, 4> Values(NumAggValues);
3445 
3446   // Ignore an insertvalue that produces an empty object
3447   if (!NumAggValues) {
3448     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3449     return;
3450   }
3451 
3452   SDValue Agg = getValue(Op0);
3453   unsigned i = 0;
3454   // Copy the beginning value(s) from the original aggregate.
3455   for (; i != LinearIndex; ++i)
3456     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3457                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3458   // Copy values from the inserted value(s).
3459   if (NumValValues) {
3460     SDValue Val = getValue(Op1);
3461     for (; i != LinearIndex + NumValValues; ++i)
3462       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3463                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3464   }
3465   // Copy remaining value(s) from the original aggregate.
3466   for (; i != NumAggValues; ++i)
3467     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3468                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3469 
3470   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3471                            DAG.getVTList(AggValueVTs), Values));
3472 }
3473 
3474 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3475   ArrayRef<unsigned> Indices;
3476   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3477     Indices = EV->getIndices();
3478   else
3479     Indices = cast<ConstantExpr>(&I)->getIndices();
3480 
3481   const Value *Op0 = I.getOperand(0);
3482   Type *AggTy = Op0->getType();
3483   Type *ValTy = I.getType();
3484   bool OutOfUndef = isa<UndefValue>(Op0);
3485 
3486   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3487 
3488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3489   SmallVector<EVT, 4> ValValueVTs;
3490   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3491 
3492   unsigned NumValValues = ValValueVTs.size();
3493 
3494   // Ignore a extractvalue that produces an empty object
3495   if (!NumValValues) {
3496     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3497     return;
3498   }
3499 
3500   SmallVector<SDValue, 4> Values(NumValValues);
3501 
3502   SDValue Agg = getValue(Op0);
3503   // Copy out the selected value(s).
3504   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3505     Values[i - LinearIndex] =
3506       OutOfUndef ?
3507         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3508         SDValue(Agg.getNode(), Agg.getResNo() + i);
3509 
3510   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3511                            DAG.getVTList(ValValueVTs), Values));
3512 }
3513 
3514 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3515   Value *Op0 = I.getOperand(0);
3516   // Note that the pointer operand may be a vector of pointers. Take the scalar
3517   // element which holds a pointer.
3518   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3519   SDValue N = getValue(Op0);
3520   SDLoc dl = getCurSDLoc();
3521 
3522   // Normalize Vector GEP - all scalar operands should be converted to the
3523   // splat vector.
3524   unsigned VectorWidth = I.getType()->isVectorTy() ?
3525     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3526 
3527   if (VectorWidth && !N.getValueType().isVector()) {
3528     LLVMContext &Context = *DAG.getContext();
3529     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3530     N = DAG.getSplatBuildVector(VT, dl, N);
3531   }
3532 
3533   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3534        GTI != E; ++GTI) {
3535     const Value *Idx = GTI.getOperand();
3536     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3537       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3538       if (Field) {
3539         // N = N + Offset
3540         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3541 
3542         // In an inbounds GEP with an offset that is nonnegative even when
3543         // interpreted as signed, assume there is no unsigned overflow.
3544         SDNodeFlags Flags;
3545         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3546           Flags.setNoUnsignedWrap(true);
3547 
3548         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3549                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3550       }
3551     } else {
3552       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3553       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3554       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3555 
3556       // If this is a scalar constant or a splat vector of constants,
3557       // handle it quickly.
3558       const auto *CI = dyn_cast<ConstantInt>(Idx);
3559       if (!CI && isa<ConstantDataVector>(Idx) &&
3560           cast<ConstantDataVector>(Idx)->getSplatValue())
3561         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3562 
3563       if (CI) {
3564         if (CI->isZero())
3565           continue;
3566         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3567         LLVMContext &Context = *DAG.getContext();
3568         SDValue OffsVal = VectorWidth ?
3569           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3570           DAG.getConstant(Offs, dl, IdxTy);
3571 
3572         // In an inbouds GEP with an offset that is nonnegative even when
3573         // interpreted as signed, assume there is no unsigned overflow.
3574         SDNodeFlags Flags;
3575         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3576           Flags.setNoUnsignedWrap(true);
3577 
3578         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3579         continue;
3580       }
3581 
3582       // N = N + Idx * ElementSize;
3583       SDValue IdxN = getValue(Idx);
3584 
3585       if (!IdxN.getValueType().isVector() && VectorWidth) {
3586         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3587         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3588       }
3589 
3590       // If the index is smaller or larger than intptr_t, truncate or extend
3591       // it.
3592       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3593 
3594       // If this is a multiply by a power of two, turn it into a shl
3595       // immediately.  This is a very common case.
3596       if (ElementSize != 1) {
3597         if (ElementSize.isPowerOf2()) {
3598           unsigned Amt = ElementSize.logBase2();
3599           IdxN = DAG.getNode(ISD::SHL, dl,
3600                              N.getValueType(), IdxN,
3601                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3602         } else {
3603           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3604           IdxN = DAG.getNode(ISD::MUL, dl,
3605                              N.getValueType(), IdxN, Scale);
3606         }
3607       }
3608 
3609       N = DAG.getNode(ISD::ADD, dl,
3610                       N.getValueType(), N, IdxN);
3611     }
3612   }
3613 
3614   setValue(&I, N);
3615 }
3616 
3617 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3618   // If this is a fixed sized alloca in the entry block of the function,
3619   // allocate it statically on the stack.
3620   if (FuncInfo.StaticAllocaMap.count(&I))
3621     return;   // getValue will auto-populate this.
3622 
3623   SDLoc dl = getCurSDLoc();
3624   Type *Ty = I.getAllocatedType();
3625   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3626   auto &DL = DAG.getDataLayout();
3627   uint64_t TySize = DL.getTypeAllocSize(Ty);
3628   unsigned Align =
3629       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3630 
3631   SDValue AllocSize = getValue(I.getArraySize());
3632 
3633   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3634   if (AllocSize.getValueType() != IntPtr)
3635     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3636 
3637   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3638                           AllocSize,
3639                           DAG.getConstant(TySize, dl, IntPtr));
3640 
3641   // Handle alignment.  If the requested alignment is less than or equal to
3642   // the stack alignment, ignore it.  If the size is greater than or equal to
3643   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3644   unsigned StackAlign =
3645       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3646   if (Align <= StackAlign)
3647     Align = 0;
3648 
3649   // Round the size of the allocation up to the stack alignment size
3650   // by add SA-1 to the size. This doesn't overflow because we're computing
3651   // an address inside an alloca.
3652   SDNodeFlags Flags;
3653   Flags.setNoUnsignedWrap(true);
3654   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3655                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3656 
3657   // Mask out the low bits for alignment purposes.
3658   AllocSize =
3659       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3660                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3661 
3662   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3663   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3664   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3665   setValue(&I, DSA);
3666   DAG.setRoot(DSA.getValue(1));
3667 
3668   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3669 }
3670 
3671 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3672   if (I.isAtomic())
3673     return visitAtomicLoad(I);
3674 
3675   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3676   const Value *SV = I.getOperand(0);
3677   if (TLI.supportSwiftError()) {
3678     // Swifterror values can come from either a function parameter with
3679     // swifterror attribute or an alloca with swifterror attribute.
3680     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3681       if (Arg->hasSwiftErrorAttr())
3682         return visitLoadFromSwiftError(I);
3683     }
3684 
3685     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3686       if (Alloca->isSwiftError())
3687         return visitLoadFromSwiftError(I);
3688     }
3689   }
3690 
3691   SDValue Ptr = getValue(SV);
3692 
3693   Type *Ty = I.getType();
3694 
3695   bool isVolatile = I.isVolatile();
3696   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3697   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3698   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3699   unsigned Alignment = I.getAlignment();
3700 
3701   AAMDNodes AAInfo;
3702   I.getAAMetadata(AAInfo);
3703   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3704 
3705   SmallVector<EVT, 4> ValueVTs;
3706   SmallVector<uint64_t, 4> Offsets;
3707   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3708   unsigned NumValues = ValueVTs.size();
3709   if (NumValues == 0)
3710     return;
3711 
3712   SDValue Root;
3713   bool ConstantMemory = false;
3714   if (isVolatile || NumValues > MaxParallelChains)
3715     // Serialize volatile loads with other side effects.
3716     Root = getRoot();
3717   else if (AA &&
3718            AA->pointsToConstantMemory(MemoryLocation(
3719                SV,
3720                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3721                AAInfo))) {
3722     // Do not serialize (non-volatile) loads of constant memory with anything.
3723     Root = DAG.getEntryNode();
3724     ConstantMemory = true;
3725   } else {
3726     // Do not serialize non-volatile loads against each other.
3727     Root = DAG.getRoot();
3728   }
3729 
3730   SDLoc dl = getCurSDLoc();
3731 
3732   if (isVolatile)
3733     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3734 
3735   // An aggregate load cannot wrap around the address space, so offsets to its
3736   // parts don't wrap either.
3737   SDNodeFlags Flags;
3738   Flags.setNoUnsignedWrap(true);
3739 
3740   SmallVector<SDValue, 4> Values(NumValues);
3741   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3742   EVT PtrVT = Ptr.getValueType();
3743   unsigned ChainI = 0;
3744   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3745     // Serializing loads here may result in excessive register pressure, and
3746     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3747     // could recover a bit by hoisting nodes upward in the chain by recognizing
3748     // they are side-effect free or do not alias. The optimizer should really
3749     // avoid this case by converting large object/array copies to llvm.memcpy
3750     // (MaxParallelChains should always remain as failsafe).
3751     if (ChainI == MaxParallelChains) {
3752       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3753       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3754                                   makeArrayRef(Chains.data(), ChainI));
3755       Root = Chain;
3756       ChainI = 0;
3757     }
3758     SDValue A = DAG.getNode(ISD::ADD, dl,
3759                             PtrVT, Ptr,
3760                             DAG.getConstant(Offsets[i], dl, PtrVT),
3761                             Flags);
3762     auto MMOFlags = MachineMemOperand::MONone;
3763     if (isVolatile)
3764       MMOFlags |= MachineMemOperand::MOVolatile;
3765     if (isNonTemporal)
3766       MMOFlags |= MachineMemOperand::MONonTemporal;
3767     if (isInvariant)
3768       MMOFlags |= MachineMemOperand::MOInvariant;
3769     if (isDereferenceable)
3770       MMOFlags |= MachineMemOperand::MODereferenceable;
3771     MMOFlags |= TLI.getMMOFlags(I);
3772 
3773     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3774                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3775                             MMOFlags, AAInfo, Ranges);
3776 
3777     Values[i] = L;
3778     Chains[ChainI] = L.getValue(1);
3779   }
3780 
3781   if (!ConstantMemory) {
3782     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3783                                 makeArrayRef(Chains.data(), ChainI));
3784     if (isVolatile)
3785       DAG.setRoot(Chain);
3786     else
3787       PendingLoads.push_back(Chain);
3788   }
3789 
3790   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3791                            DAG.getVTList(ValueVTs), Values));
3792 }
3793 
3794 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3795   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3796          "call visitStoreToSwiftError when backend supports swifterror");
3797 
3798   SmallVector<EVT, 4> ValueVTs;
3799   SmallVector<uint64_t, 4> Offsets;
3800   const Value *SrcV = I.getOperand(0);
3801   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3802                   SrcV->getType(), ValueVTs, &Offsets);
3803   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3804          "expect a single EVT for swifterror");
3805 
3806   SDValue Src = getValue(SrcV);
3807   // Create a virtual register, then update the virtual register.
3808   unsigned VReg; bool CreatedVReg;
3809   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3810   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3811   // Chain can be getRoot or getControlRoot.
3812   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3813                                       SDValue(Src.getNode(), Src.getResNo()));
3814   DAG.setRoot(CopyNode);
3815   if (CreatedVReg)
3816     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3817 }
3818 
3819 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3820   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3821          "call visitLoadFromSwiftError when backend supports swifterror");
3822 
3823   assert(!I.isVolatile() &&
3824          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3825          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3826          "Support volatile, non temporal, invariant for load_from_swift_error");
3827 
3828   const Value *SV = I.getOperand(0);
3829   Type *Ty = I.getType();
3830   AAMDNodes AAInfo;
3831   I.getAAMetadata(AAInfo);
3832   assert(
3833       (!AA ||
3834        !AA->pointsToConstantMemory(MemoryLocation(
3835            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3836            AAInfo))) &&
3837       "load_from_swift_error should not be constant memory");
3838 
3839   SmallVector<EVT, 4> ValueVTs;
3840   SmallVector<uint64_t, 4> Offsets;
3841   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3842                   ValueVTs, &Offsets);
3843   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3844          "expect a single EVT for swifterror");
3845 
3846   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3847   SDValue L = DAG.getCopyFromReg(
3848       getRoot(), getCurSDLoc(),
3849       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3850       ValueVTs[0]);
3851 
3852   setValue(&I, L);
3853 }
3854 
3855 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3856   if (I.isAtomic())
3857     return visitAtomicStore(I);
3858 
3859   const Value *SrcV = I.getOperand(0);
3860   const Value *PtrV = I.getOperand(1);
3861 
3862   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3863   if (TLI.supportSwiftError()) {
3864     // Swifterror values can come from either a function parameter with
3865     // swifterror attribute or an alloca with swifterror attribute.
3866     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3867       if (Arg->hasSwiftErrorAttr())
3868         return visitStoreToSwiftError(I);
3869     }
3870 
3871     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3872       if (Alloca->isSwiftError())
3873         return visitStoreToSwiftError(I);
3874     }
3875   }
3876 
3877   SmallVector<EVT, 4> ValueVTs;
3878   SmallVector<uint64_t, 4> Offsets;
3879   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3880                   SrcV->getType(), ValueVTs, &Offsets);
3881   unsigned NumValues = ValueVTs.size();
3882   if (NumValues == 0)
3883     return;
3884 
3885   // Get the lowered operands. Note that we do this after
3886   // checking if NumResults is zero, because with zero results
3887   // the operands won't have values in the map.
3888   SDValue Src = getValue(SrcV);
3889   SDValue Ptr = getValue(PtrV);
3890 
3891   SDValue Root = getRoot();
3892   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3893   SDLoc dl = getCurSDLoc();
3894   EVT PtrVT = Ptr.getValueType();
3895   unsigned Alignment = I.getAlignment();
3896   AAMDNodes AAInfo;
3897   I.getAAMetadata(AAInfo);
3898 
3899   auto MMOFlags = MachineMemOperand::MONone;
3900   if (I.isVolatile())
3901     MMOFlags |= MachineMemOperand::MOVolatile;
3902   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3903     MMOFlags |= MachineMemOperand::MONonTemporal;
3904   MMOFlags |= TLI.getMMOFlags(I);
3905 
3906   // An aggregate load cannot wrap around the address space, so offsets to its
3907   // parts don't wrap either.
3908   SDNodeFlags Flags;
3909   Flags.setNoUnsignedWrap(true);
3910 
3911   unsigned ChainI = 0;
3912   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3913     // See visitLoad comments.
3914     if (ChainI == MaxParallelChains) {
3915       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3916                                   makeArrayRef(Chains.data(), ChainI));
3917       Root = Chain;
3918       ChainI = 0;
3919     }
3920     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3921                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
3922     SDValue St = DAG.getStore(
3923         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3924         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3925     Chains[ChainI] = St;
3926   }
3927 
3928   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3929                                   makeArrayRef(Chains.data(), ChainI));
3930   DAG.setRoot(StoreNode);
3931 }
3932 
3933 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3934                                            bool IsCompressing) {
3935   SDLoc sdl = getCurSDLoc();
3936 
3937   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3938                            unsigned& Alignment) {
3939     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3940     Src0 = I.getArgOperand(0);
3941     Ptr = I.getArgOperand(1);
3942     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3943     Mask = I.getArgOperand(3);
3944   };
3945   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3946                            unsigned& Alignment) {
3947     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3948     Src0 = I.getArgOperand(0);
3949     Ptr = I.getArgOperand(1);
3950     Mask = I.getArgOperand(2);
3951     Alignment = 0;
3952   };
3953 
3954   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3955   unsigned Alignment;
3956   if (IsCompressing)
3957     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3958   else
3959     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3960 
3961   SDValue Ptr = getValue(PtrOperand);
3962   SDValue Src0 = getValue(Src0Operand);
3963   SDValue Mask = getValue(MaskOperand);
3964 
3965   EVT VT = Src0.getValueType();
3966   if (!Alignment)
3967     Alignment = DAG.getEVTAlignment(VT);
3968 
3969   AAMDNodes AAInfo;
3970   I.getAAMetadata(AAInfo);
3971 
3972   MachineMemOperand *MMO =
3973     DAG.getMachineFunction().
3974     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3975                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3976                           Alignment, AAInfo);
3977   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3978                                          MMO, false /* Truncating */,
3979                                          IsCompressing);
3980   DAG.setRoot(StoreNode);
3981   setValue(&I, StoreNode);
3982 }
3983 
3984 // Get a uniform base for the Gather/Scatter intrinsic.
3985 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3986 // We try to represent it as a base pointer + vector of indices.
3987 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3988 // The first operand of the GEP may be a single pointer or a vector of pointers
3989 // Example:
3990 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3991 //  or
3992 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
3993 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3994 //
3995 // When the first GEP operand is a single pointer - it is the uniform base we
3996 // are looking for. If first operand of the GEP is a splat vector - we
3997 // extract the splat value and use it as a uniform base.
3998 // In all other cases the function returns 'false'.
3999 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
4000                            SDValue &Scale, SelectionDAGBuilder* SDB) {
4001   SelectionDAG& DAG = SDB->DAG;
4002   LLVMContext &Context = *DAG.getContext();
4003 
4004   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4005   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4006   if (!GEP)
4007     return false;
4008 
4009   const Value *GEPPtr = GEP->getPointerOperand();
4010   if (!GEPPtr->getType()->isVectorTy())
4011     Ptr = GEPPtr;
4012   else if (!(Ptr = getSplatValue(GEPPtr)))
4013     return false;
4014 
4015   unsigned FinalIndex = GEP->getNumOperands() - 1;
4016   Value *IndexVal = GEP->getOperand(FinalIndex);
4017 
4018   // Ensure all the other indices are 0.
4019   for (unsigned i = 1; i < FinalIndex; ++i) {
4020     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
4021     if (!C || !C->isZero())
4022       return false;
4023   }
4024 
4025   // The operands of the GEP may be defined in another basic block.
4026   // In this case we'll not find nodes for the operands.
4027   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
4028     return false;
4029 
4030   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4031   const DataLayout &DL = DAG.getDataLayout();
4032   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4033                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4034   Base = SDB->getValue(Ptr);
4035   Index = SDB->getValue(IndexVal);
4036 
4037   if (!Index.getValueType().isVector()) {
4038     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4039     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4040     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4041   }
4042   return true;
4043 }
4044 
4045 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4046   SDLoc sdl = getCurSDLoc();
4047 
4048   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4049   const Value *Ptr = I.getArgOperand(1);
4050   SDValue Src0 = getValue(I.getArgOperand(0));
4051   SDValue Mask = getValue(I.getArgOperand(3));
4052   EVT VT = Src0.getValueType();
4053   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4054   if (!Alignment)
4055     Alignment = DAG.getEVTAlignment(VT);
4056   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4057 
4058   AAMDNodes AAInfo;
4059   I.getAAMetadata(AAInfo);
4060 
4061   SDValue Base;
4062   SDValue Index;
4063   SDValue Scale;
4064   const Value *BasePtr = Ptr;
4065   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4066 
4067   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4068   MachineMemOperand *MMO = DAG.getMachineFunction().
4069     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4070                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4071                          Alignment, AAInfo);
4072   if (!UniformBase) {
4073     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4074     Index = getValue(Ptr);
4075     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4076   }
4077   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4078   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4079                                          Ops, MMO);
4080   DAG.setRoot(Scatter);
4081   setValue(&I, Scatter);
4082 }
4083 
4084 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4085   SDLoc sdl = getCurSDLoc();
4086 
4087   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4088                            unsigned& Alignment) {
4089     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4090     Ptr = I.getArgOperand(0);
4091     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4092     Mask = I.getArgOperand(2);
4093     Src0 = I.getArgOperand(3);
4094   };
4095   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4096                            unsigned& Alignment) {
4097     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4098     Ptr = I.getArgOperand(0);
4099     Alignment = 0;
4100     Mask = I.getArgOperand(1);
4101     Src0 = I.getArgOperand(2);
4102   };
4103 
4104   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4105   unsigned Alignment;
4106   if (IsExpanding)
4107     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4108   else
4109     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4110 
4111   SDValue Ptr = getValue(PtrOperand);
4112   SDValue Src0 = getValue(Src0Operand);
4113   SDValue Mask = getValue(MaskOperand);
4114 
4115   EVT VT = Src0.getValueType();
4116   if (!Alignment)
4117     Alignment = DAG.getEVTAlignment(VT);
4118 
4119   AAMDNodes AAInfo;
4120   I.getAAMetadata(AAInfo);
4121   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4122 
4123   // Do not serialize masked loads of constant memory with anything.
4124   bool AddToChain =
4125       !AA || !AA->pointsToConstantMemory(MemoryLocation(
4126                  PtrOperand,
4127                  LocationSize::precise(
4128                      DAG.getDataLayout().getTypeStoreSize(I.getType())),
4129                  AAInfo));
4130   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4131 
4132   MachineMemOperand *MMO =
4133     DAG.getMachineFunction().
4134     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4135                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4136                           Alignment, AAInfo, Ranges);
4137 
4138   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4139                                    ISD::NON_EXTLOAD, IsExpanding);
4140   if (AddToChain)
4141     PendingLoads.push_back(Load.getValue(1));
4142   setValue(&I, Load);
4143 }
4144 
4145 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4146   SDLoc sdl = getCurSDLoc();
4147 
4148   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4149   const Value *Ptr = I.getArgOperand(0);
4150   SDValue Src0 = getValue(I.getArgOperand(3));
4151   SDValue Mask = getValue(I.getArgOperand(2));
4152 
4153   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4154   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4155   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4156   if (!Alignment)
4157     Alignment = DAG.getEVTAlignment(VT);
4158 
4159   AAMDNodes AAInfo;
4160   I.getAAMetadata(AAInfo);
4161   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4162 
4163   SDValue Root = DAG.getRoot();
4164   SDValue Base;
4165   SDValue Index;
4166   SDValue Scale;
4167   const Value *BasePtr = Ptr;
4168   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4169   bool ConstantMemory = false;
4170   if (UniformBase && AA &&
4171       AA->pointsToConstantMemory(
4172           MemoryLocation(BasePtr,
4173                          LocationSize::precise(
4174                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4175                          AAInfo))) {
4176     // Do not serialize (non-volatile) loads of constant memory with anything.
4177     Root = DAG.getEntryNode();
4178     ConstantMemory = true;
4179   }
4180 
4181   MachineMemOperand *MMO =
4182     DAG.getMachineFunction().
4183     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4184                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4185                          Alignment, AAInfo, Ranges);
4186 
4187   if (!UniformBase) {
4188     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4189     Index = getValue(Ptr);
4190     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4191   }
4192   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4193   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4194                                        Ops, MMO);
4195 
4196   SDValue OutChain = Gather.getValue(1);
4197   if (!ConstantMemory)
4198     PendingLoads.push_back(OutChain);
4199   setValue(&I, Gather);
4200 }
4201 
4202 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4203   SDLoc dl = getCurSDLoc();
4204   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4205   AtomicOrdering FailureOrder = I.getFailureOrdering();
4206   SyncScope::ID SSID = I.getSyncScopeID();
4207 
4208   SDValue InChain = getRoot();
4209 
4210   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4211   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4212   SDValue L = DAG.getAtomicCmpSwap(
4213       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4214       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4215       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4216       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4217 
4218   SDValue OutChain = L.getValue(2);
4219 
4220   setValue(&I, L);
4221   DAG.setRoot(OutChain);
4222 }
4223 
4224 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4225   SDLoc dl = getCurSDLoc();
4226   ISD::NodeType NT;
4227   switch (I.getOperation()) {
4228   default: llvm_unreachable("Unknown atomicrmw operation");
4229   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4230   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4231   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4232   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4233   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4234   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4235   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4236   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4237   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4238   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4239   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4240   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4241   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4242   }
4243   AtomicOrdering Order = I.getOrdering();
4244   SyncScope::ID SSID = I.getSyncScopeID();
4245 
4246   SDValue InChain = getRoot();
4247 
4248   SDValue L =
4249     DAG.getAtomic(NT, dl,
4250                   getValue(I.getValOperand()).getSimpleValueType(),
4251                   InChain,
4252                   getValue(I.getPointerOperand()),
4253                   getValue(I.getValOperand()),
4254                   I.getPointerOperand(),
4255                   /* Alignment=*/ 0, Order, SSID);
4256 
4257   SDValue OutChain = L.getValue(1);
4258 
4259   setValue(&I, L);
4260   DAG.setRoot(OutChain);
4261 }
4262 
4263 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4264   SDLoc dl = getCurSDLoc();
4265   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4266   SDValue Ops[3];
4267   Ops[0] = getRoot();
4268   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4269                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4270   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4271                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4272   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4273 }
4274 
4275 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4276   SDLoc dl = getCurSDLoc();
4277   AtomicOrdering Order = I.getOrdering();
4278   SyncScope::ID SSID = I.getSyncScopeID();
4279 
4280   SDValue InChain = getRoot();
4281 
4282   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4283   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4284 
4285   if (!TLI.supportsUnalignedAtomics() &&
4286       I.getAlignment() < VT.getStoreSize())
4287     report_fatal_error("Cannot generate unaligned atomic load");
4288 
4289   MachineMemOperand *MMO =
4290       DAG.getMachineFunction().
4291       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4292                            MachineMemOperand::MOVolatile |
4293                            MachineMemOperand::MOLoad,
4294                            VT.getStoreSize(),
4295                            I.getAlignment() ? I.getAlignment() :
4296                                               DAG.getEVTAlignment(VT),
4297                            AAMDNodes(), nullptr, SSID, Order);
4298 
4299   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4300   SDValue L =
4301       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4302                     getValue(I.getPointerOperand()), MMO);
4303 
4304   SDValue OutChain = L.getValue(1);
4305 
4306   setValue(&I, L);
4307   DAG.setRoot(OutChain);
4308 }
4309 
4310 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4311   SDLoc dl = getCurSDLoc();
4312 
4313   AtomicOrdering Order = I.getOrdering();
4314   SyncScope::ID SSID = I.getSyncScopeID();
4315 
4316   SDValue InChain = getRoot();
4317 
4318   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4319   EVT VT =
4320       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4321 
4322   if (I.getAlignment() < VT.getStoreSize())
4323     report_fatal_error("Cannot generate unaligned atomic store");
4324 
4325   SDValue OutChain =
4326     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4327                   InChain,
4328                   getValue(I.getPointerOperand()),
4329                   getValue(I.getValueOperand()),
4330                   I.getPointerOperand(), I.getAlignment(),
4331                   Order, SSID);
4332 
4333   DAG.setRoot(OutChain);
4334 }
4335 
4336 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4337 /// node.
4338 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4339                                                unsigned Intrinsic) {
4340   // Ignore the callsite's attributes. A specific call site may be marked with
4341   // readnone, but the lowering code will expect the chain based on the
4342   // definition.
4343   const Function *F = I.getCalledFunction();
4344   bool HasChain = !F->doesNotAccessMemory();
4345   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4346 
4347   // Build the operand list.
4348   SmallVector<SDValue, 8> Ops;
4349   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4350     if (OnlyLoad) {
4351       // We don't need to serialize loads against other loads.
4352       Ops.push_back(DAG.getRoot());
4353     } else {
4354       Ops.push_back(getRoot());
4355     }
4356   }
4357 
4358   // Info is set by getTgtMemInstrinsic
4359   TargetLowering::IntrinsicInfo Info;
4360   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4361   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4362                                                DAG.getMachineFunction(),
4363                                                Intrinsic);
4364 
4365   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4366   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4367       Info.opc == ISD::INTRINSIC_W_CHAIN)
4368     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4369                                         TLI.getPointerTy(DAG.getDataLayout())));
4370 
4371   // Add all operands of the call to the operand list.
4372   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4373     SDValue Op = getValue(I.getArgOperand(i));
4374     Ops.push_back(Op);
4375   }
4376 
4377   SmallVector<EVT, 4> ValueVTs;
4378   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4379 
4380   if (HasChain)
4381     ValueVTs.push_back(MVT::Other);
4382 
4383   SDVTList VTs = DAG.getVTList(ValueVTs);
4384 
4385   // Create the node.
4386   SDValue Result;
4387   if (IsTgtIntrinsic) {
4388     // This is target intrinsic that touches memory
4389     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4390       Ops, Info.memVT,
4391       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4392       Info.flags, Info.size);
4393   } else if (!HasChain) {
4394     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4395   } else if (!I.getType()->isVoidTy()) {
4396     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4397   } else {
4398     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4399   }
4400 
4401   if (HasChain) {
4402     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4403     if (OnlyLoad)
4404       PendingLoads.push_back(Chain);
4405     else
4406       DAG.setRoot(Chain);
4407   }
4408 
4409   if (!I.getType()->isVoidTy()) {
4410     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4411       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4412       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4413     } else
4414       Result = lowerRangeToAssertZExt(DAG, I, Result);
4415 
4416     setValue(&I, Result);
4417   }
4418 }
4419 
4420 /// GetSignificand - Get the significand and build it into a floating-point
4421 /// number with exponent of 1:
4422 ///
4423 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4424 ///
4425 /// where Op is the hexadecimal representation of floating point value.
4426 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4427   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4428                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4429   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4430                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4431   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4432 }
4433 
4434 /// GetExponent - Get the exponent:
4435 ///
4436 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4437 ///
4438 /// where Op is the hexadecimal representation of floating point value.
4439 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4440                            const TargetLowering &TLI, const SDLoc &dl) {
4441   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4442                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4443   SDValue t1 = DAG.getNode(
4444       ISD::SRL, dl, MVT::i32, t0,
4445       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4446   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4447                            DAG.getConstant(127, dl, MVT::i32));
4448   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4449 }
4450 
4451 /// getF32Constant - Get 32-bit floating point constant.
4452 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4453                               const SDLoc &dl) {
4454   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4455                            MVT::f32);
4456 }
4457 
4458 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4459                                        SelectionDAG &DAG) {
4460   // TODO: What fast-math-flags should be set on the floating-point nodes?
4461 
4462   //   IntegerPartOfX = ((int32_t)(t0);
4463   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4464 
4465   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4466   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4467   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4468 
4469   //   IntegerPartOfX <<= 23;
4470   IntegerPartOfX = DAG.getNode(
4471       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4472       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4473                                   DAG.getDataLayout())));
4474 
4475   SDValue TwoToFractionalPartOfX;
4476   if (LimitFloatPrecision <= 6) {
4477     // For floating-point precision of 6:
4478     //
4479     //   TwoToFractionalPartOfX =
4480     //     0.997535578f +
4481     //       (0.735607626f + 0.252464424f * x) * x;
4482     //
4483     // error 0.0144103317, which is 6 bits
4484     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4485                              getF32Constant(DAG, 0x3e814304, dl));
4486     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4487                              getF32Constant(DAG, 0x3f3c50c8, dl));
4488     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4489     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4490                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4491   } else if (LimitFloatPrecision <= 12) {
4492     // For floating-point precision of 12:
4493     //
4494     //   TwoToFractionalPartOfX =
4495     //     0.999892986f +
4496     //       (0.696457318f +
4497     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4498     //
4499     // error 0.000107046256, which is 13 to 14 bits
4500     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4501                              getF32Constant(DAG, 0x3da235e3, dl));
4502     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4503                              getF32Constant(DAG, 0x3e65b8f3, dl));
4504     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4505     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4506                              getF32Constant(DAG, 0x3f324b07, dl));
4507     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4508     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4509                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4510   } else { // LimitFloatPrecision <= 18
4511     // For floating-point precision of 18:
4512     //
4513     //   TwoToFractionalPartOfX =
4514     //     0.999999982f +
4515     //       (0.693148872f +
4516     //         (0.240227044f +
4517     //           (0.554906021e-1f +
4518     //             (0.961591928e-2f +
4519     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4520     // error 2.47208000*10^(-7), which is better than 18 bits
4521     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4522                              getF32Constant(DAG, 0x3924b03e, dl));
4523     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4524                              getF32Constant(DAG, 0x3ab24b87, dl));
4525     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4526     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4527                              getF32Constant(DAG, 0x3c1d8c17, dl));
4528     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4529     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4530                              getF32Constant(DAG, 0x3d634a1d, dl));
4531     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4532     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4533                              getF32Constant(DAG, 0x3e75fe14, dl));
4534     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4535     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4536                               getF32Constant(DAG, 0x3f317234, dl));
4537     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4538     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4539                                          getF32Constant(DAG, 0x3f800000, dl));
4540   }
4541 
4542   // Add the exponent into the result in integer domain.
4543   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4544   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4545                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4546 }
4547 
4548 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4549 /// limited-precision mode.
4550 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4551                          const TargetLowering &TLI) {
4552   if (Op.getValueType() == MVT::f32 &&
4553       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4554 
4555     // Put the exponent in the right bit position for later addition to the
4556     // final result:
4557     //
4558     //   #define LOG2OFe 1.4426950f
4559     //   t0 = Op * LOG2OFe
4560 
4561     // TODO: What fast-math-flags should be set here?
4562     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4563                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4564     return getLimitedPrecisionExp2(t0, dl, DAG);
4565   }
4566 
4567   // No special expansion.
4568   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4569 }
4570 
4571 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4572 /// limited-precision mode.
4573 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4574                          const TargetLowering &TLI) {
4575   // TODO: What fast-math-flags should be set on the floating-point nodes?
4576 
4577   if (Op.getValueType() == MVT::f32 &&
4578       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4579     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4580 
4581     // Scale the exponent by log(2) [0.69314718f].
4582     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4583     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4584                                         getF32Constant(DAG, 0x3f317218, dl));
4585 
4586     // Get the significand and build it into a floating-point number with
4587     // exponent of 1.
4588     SDValue X = GetSignificand(DAG, Op1, dl);
4589 
4590     SDValue LogOfMantissa;
4591     if (LimitFloatPrecision <= 6) {
4592       // For floating-point precision of 6:
4593       //
4594       //   LogofMantissa =
4595       //     -1.1609546f +
4596       //       (1.4034025f - 0.23903021f * x) * x;
4597       //
4598       // error 0.0034276066, which is better than 8 bits
4599       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4600                                getF32Constant(DAG, 0xbe74c456, dl));
4601       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4602                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4603       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4604       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4605                                   getF32Constant(DAG, 0x3f949a29, dl));
4606     } else if (LimitFloatPrecision <= 12) {
4607       // For floating-point precision of 12:
4608       //
4609       //   LogOfMantissa =
4610       //     -1.7417939f +
4611       //       (2.8212026f +
4612       //         (-1.4699568f +
4613       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4614       //
4615       // error 0.000061011436, which is 14 bits
4616       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4617                                getF32Constant(DAG, 0xbd67b6d6, dl));
4618       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4619                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4620       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4621       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4622                                getF32Constant(DAG, 0x3fbc278b, dl));
4623       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4624       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4625                                getF32Constant(DAG, 0x40348e95, dl));
4626       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4627       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4628                                   getF32Constant(DAG, 0x3fdef31a, dl));
4629     } else { // LimitFloatPrecision <= 18
4630       // For floating-point precision of 18:
4631       //
4632       //   LogOfMantissa =
4633       //     -2.1072184f +
4634       //       (4.2372794f +
4635       //         (-3.7029485f +
4636       //           (2.2781945f +
4637       //             (-0.87823314f +
4638       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4639       //
4640       // error 0.0000023660568, which is better than 18 bits
4641       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4642                                getF32Constant(DAG, 0xbc91e5ac, dl));
4643       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4644                                getF32Constant(DAG, 0x3e4350aa, dl));
4645       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4646       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4647                                getF32Constant(DAG, 0x3f60d3e3, dl));
4648       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4649       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4650                                getF32Constant(DAG, 0x4011cdf0, dl));
4651       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4652       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4653                                getF32Constant(DAG, 0x406cfd1c, dl));
4654       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4655       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4656                                getF32Constant(DAG, 0x408797cb, dl));
4657       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4658       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4659                                   getF32Constant(DAG, 0x4006dcab, dl));
4660     }
4661 
4662     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4663   }
4664 
4665   // No special expansion.
4666   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4667 }
4668 
4669 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4670 /// limited-precision mode.
4671 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4672                           const TargetLowering &TLI) {
4673   // TODO: What fast-math-flags should be set on the floating-point nodes?
4674 
4675   if (Op.getValueType() == MVT::f32 &&
4676       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4677     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4678 
4679     // Get the exponent.
4680     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4681 
4682     // Get the significand and build it into a floating-point number with
4683     // exponent of 1.
4684     SDValue X = GetSignificand(DAG, Op1, dl);
4685 
4686     // Different possible minimax approximations of significand in
4687     // floating-point for various degrees of accuracy over [1,2].
4688     SDValue Log2ofMantissa;
4689     if (LimitFloatPrecision <= 6) {
4690       // For floating-point precision of 6:
4691       //
4692       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4693       //
4694       // error 0.0049451742, which is more than 7 bits
4695       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4696                                getF32Constant(DAG, 0xbeb08fe0, dl));
4697       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4698                                getF32Constant(DAG, 0x40019463, dl));
4699       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4700       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4701                                    getF32Constant(DAG, 0x3fd6633d, dl));
4702     } else if (LimitFloatPrecision <= 12) {
4703       // For floating-point precision of 12:
4704       //
4705       //   Log2ofMantissa =
4706       //     -2.51285454f +
4707       //       (4.07009056f +
4708       //         (-2.12067489f +
4709       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4710       //
4711       // error 0.0000876136000, which is better than 13 bits
4712       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4713                                getF32Constant(DAG, 0xbda7262e, dl));
4714       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4715                                getF32Constant(DAG, 0x3f25280b, dl));
4716       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4717       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4718                                getF32Constant(DAG, 0x4007b923, dl));
4719       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4720       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4721                                getF32Constant(DAG, 0x40823e2f, dl));
4722       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4723       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4724                                    getF32Constant(DAG, 0x4020d29c, dl));
4725     } else { // LimitFloatPrecision <= 18
4726       // For floating-point precision of 18:
4727       //
4728       //   Log2ofMantissa =
4729       //     -3.0400495f +
4730       //       (6.1129976f +
4731       //         (-5.3420409f +
4732       //           (3.2865683f +
4733       //             (-1.2669343f +
4734       //               (0.27515199f -
4735       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4736       //
4737       // error 0.0000018516, which is better than 18 bits
4738       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4739                                getF32Constant(DAG, 0xbcd2769e, dl));
4740       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4741                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4742       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4743       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4744                                getF32Constant(DAG, 0x3fa22ae7, dl));
4745       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4746       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4747                                getF32Constant(DAG, 0x40525723, dl));
4748       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4749       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4750                                getF32Constant(DAG, 0x40aaf200, dl));
4751       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4752       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4753                                getF32Constant(DAG, 0x40c39dad, dl));
4754       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4755       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4756                                    getF32Constant(DAG, 0x4042902c, dl));
4757     }
4758 
4759     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4760   }
4761 
4762   // No special expansion.
4763   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4764 }
4765 
4766 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4767 /// limited-precision mode.
4768 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4769                            const TargetLowering &TLI) {
4770   // TODO: What fast-math-flags should be set on the floating-point nodes?
4771 
4772   if (Op.getValueType() == MVT::f32 &&
4773       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4774     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4775 
4776     // Scale the exponent by log10(2) [0.30102999f].
4777     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4778     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4779                                         getF32Constant(DAG, 0x3e9a209a, dl));
4780 
4781     // Get the significand and build it into a floating-point number with
4782     // exponent of 1.
4783     SDValue X = GetSignificand(DAG, Op1, dl);
4784 
4785     SDValue Log10ofMantissa;
4786     if (LimitFloatPrecision <= 6) {
4787       // For floating-point precision of 6:
4788       //
4789       //   Log10ofMantissa =
4790       //     -0.50419619f +
4791       //       (0.60948995f - 0.10380950f * x) * x;
4792       //
4793       // error 0.0014886165, which is 6 bits
4794       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4795                                getF32Constant(DAG, 0xbdd49a13, dl));
4796       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4797                                getF32Constant(DAG, 0x3f1c0789, dl));
4798       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4799       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4800                                     getF32Constant(DAG, 0x3f011300, dl));
4801     } else if (LimitFloatPrecision <= 12) {
4802       // For floating-point precision of 12:
4803       //
4804       //   Log10ofMantissa =
4805       //     -0.64831180f +
4806       //       (0.91751397f +
4807       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4808       //
4809       // error 0.00019228036, which is better than 12 bits
4810       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4811                                getF32Constant(DAG, 0x3d431f31, dl));
4812       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4813                                getF32Constant(DAG, 0x3ea21fb2, dl));
4814       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4815       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4816                                getF32Constant(DAG, 0x3f6ae232, dl));
4817       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4818       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4819                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4820     } else { // LimitFloatPrecision <= 18
4821       // For floating-point precision of 18:
4822       //
4823       //   Log10ofMantissa =
4824       //     -0.84299375f +
4825       //       (1.5327582f +
4826       //         (-1.0688956f +
4827       //           (0.49102474f +
4828       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4829       //
4830       // error 0.0000037995730, which is better than 18 bits
4831       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4832                                getF32Constant(DAG, 0x3c5d51ce, dl));
4833       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4834                                getF32Constant(DAG, 0x3e00685a, dl));
4835       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4836       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4837                                getF32Constant(DAG, 0x3efb6798, dl));
4838       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4839       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4840                                getF32Constant(DAG, 0x3f88d192, dl));
4841       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4842       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4843                                getF32Constant(DAG, 0x3fc4316c, dl));
4844       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4845       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4846                                     getF32Constant(DAG, 0x3f57ce70, dl));
4847     }
4848 
4849     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4850   }
4851 
4852   // No special expansion.
4853   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4854 }
4855 
4856 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4857 /// limited-precision mode.
4858 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4859                           const TargetLowering &TLI) {
4860   if (Op.getValueType() == MVT::f32 &&
4861       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4862     return getLimitedPrecisionExp2(Op, dl, DAG);
4863 
4864   // No special expansion.
4865   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4866 }
4867 
4868 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4869 /// limited-precision mode with x == 10.0f.
4870 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4871                          SelectionDAG &DAG, const TargetLowering &TLI) {
4872   bool IsExp10 = false;
4873   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4874       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4875     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4876       APFloat Ten(10.0f);
4877       IsExp10 = LHSC->isExactlyValue(Ten);
4878     }
4879   }
4880 
4881   // TODO: What fast-math-flags should be set on the FMUL node?
4882   if (IsExp10) {
4883     // Put the exponent in the right bit position for later addition to the
4884     // final result:
4885     //
4886     //   #define LOG2OF10 3.3219281f
4887     //   t0 = Op * LOG2OF10;
4888     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4889                              getF32Constant(DAG, 0x40549a78, dl));
4890     return getLimitedPrecisionExp2(t0, dl, DAG);
4891   }
4892 
4893   // No special expansion.
4894   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4895 }
4896 
4897 /// ExpandPowI - Expand a llvm.powi intrinsic.
4898 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4899                           SelectionDAG &DAG) {
4900   // If RHS is a constant, we can expand this out to a multiplication tree,
4901   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4902   // optimizing for size, we only want to do this if the expansion would produce
4903   // a small number of multiplies, otherwise we do the full expansion.
4904   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4905     // Get the exponent as a positive value.
4906     unsigned Val = RHSC->getSExtValue();
4907     if ((int)Val < 0) Val = -Val;
4908 
4909     // powi(x, 0) -> 1.0
4910     if (Val == 0)
4911       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4912 
4913     const Function &F = DAG.getMachineFunction().getFunction();
4914     if (!F.optForSize() ||
4915         // If optimizing for size, don't insert too many multiplies.
4916         // This inserts up to 5 multiplies.
4917         countPopulation(Val) + Log2_32(Val) < 7) {
4918       // We use the simple binary decomposition method to generate the multiply
4919       // sequence.  There are more optimal ways to do this (for example,
4920       // powi(x,15) generates one more multiply than it should), but this has
4921       // the benefit of being both really simple and much better than a libcall.
4922       SDValue Res;  // Logically starts equal to 1.0
4923       SDValue CurSquare = LHS;
4924       // TODO: Intrinsics should have fast-math-flags that propagate to these
4925       // nodes.
4926       while (Val) {
4927         if (Val & 1) {
4928           if (Res.getNode())
4929             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4930           else
4931             Res = CurSquare;  // 1.0*CurSquare.
4932         }
4933 
4934         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4935                                 CurSquare, CurSquare);
4936         Val >>= 1;
4937       }
4938 
4939       // If the original was negative, invert the result, producing 1/(x*x*x).
4940       if (RHSC->getSExtValue() < 0)
4941         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4942                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4943       return Res;
4944     }
4945   }
4946 
4947   // Otherwise, expand to a libcall.
4948   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4949 }
4950 
4951 // getUnderlyingArgReg - Find underlying register used for a truncated or
4952 // bitcasted argument.
4953 static unsigned getUnderlyingArgReg(const SDValue &N) {
4954   switch (N.getOpcode()) {
4955   case ISD::CopyFromReg:
4956     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4957   case ISD::BITCAST:
4958   case ISD::AssertZext:
4959   case ISD::AssertSext:
4960   case ISD::TRUNCATE:
4961     return getUnderlyingArgReg(N.getOperand(0));
4962   default:
4963     return 0;
4964   }
4965 }
4966 
4967 /// If the DbgValueInst is a dbg_value of a function argument, create the
4968 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
4969 /// instruction selection, they will be inserted to the entry BB.
4970 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4971     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4972     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
4973   const Argument *Arg = dyn_cast<Argument>(V);
4974   if (!Arg)
4975     return false;
4976 
4977   MachineFunction &MF = DAG.getMachineFunction();
4978   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4979 
4980   bool IsIndirect = false;
4981   Optional<MachineOperand> Op;
4982   // Some arguments' frame index is recorded during argument lowering.
4983   int FI = FuncInfo.getArgumentFrameIndex(Arg);
4984   if (FI != std::numeric_limits<int>::max())
4985     Op = MachineOperand::CreateFI(FI);
4986 
4987   if (!Op && N.getNode()) {
4988     unsigned Reg = getUnderlyingArgReg(N);
4989     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4990       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4991       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4992       if (PR)
4993         Reg = PR;
4994     }
4995     if (Reg) {
4996       Op = MachineOperand::CreateReg(Reg, false);
4997       IsIndirect = IsDbgDeclare;
4998     }
4999   }
5000 
5001   if (!Op && N.getNode())
5002     // Check if frame index is available.
5003     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
5004       if (FrameIndexSDNode *FINode =
5005           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5006         Op = MachineOperand::CreateFI(FINode->getIndex());
5007 
5008   if (!Op) {
5009     // Check if ValueMap has reg number.
5010     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
5011     if (VMI != FuncInfo.ValueMap.end()) {
5012       const auto &TLI = DAG.getTargetLoweringInfo();
5013       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5014                        V->getType(), getABIRegCopyCC(V));
5015       if (RFV.occupiesMultipleRegs()) {
5016         unsigned Offset = 0;
5017         for (auto RegAndSize : RFV.getRegsAndSizes()) {
5018           Op = MachineOperand::CreateReg(RegAndSize.first, false);
5019           auto FragmentExpr = DIExpression::createFragmentExpression(
5020               Expr, Offset, RegAndSize.second);
5021           if (!FragmentExpr)
5022             continue;
5023           FuncInfo.ArgDbgValues.push_back(
5024               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5025                       Op->getReg(), Variable, *FragmentExpr));
5026           Offset += RegAndSize.second;
5027         }
5028         return true;
5029       }
5030       Op = MachineOperand::CreateReg(VMI->second, false);
5031       IsIndirect = IsDbgDeclare;
5032     }
5033   }
5034 
5035   if (!Op)
5036     return false;
5037 
5038   assert(Variable->isValidLocationForIntrinsic(DL) &&
5039          "Expected inlined-at fields to agree");
5040   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5041   FuncInfo.ArgDbgValues.push_back(
5042       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5043               *Op, Variable, Expr));
5044 
5045   return true;
5046 }
5047 
5048 /// Return the appropriate SDDbgValue based on N.
5049 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5050                                              DILocalVariable *Variable,
5051                                              DIExpression *Expr,
5052                                              const DebugLoc &dl,
5053                                              unsigned DbgSDNodeOrder) {
5054   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5055     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5056     // stack slot locations.
5057     //
5058     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5059     // debug values here after optimization:
5060     //
5061     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5062     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5063     //
5064     // Both describe the direct values of their associated variables.
5065     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5066                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5067   }
5068   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5069                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5070 }
5071 
5072 // VisualStudio defines setjmp as _setjmp
5073 #if defined(_MSC_VER) && defined(setjmp) && \
5074                          !defined(setjmp_undefined_for_msvc)
5075 #  pragma push_macro("setjmp")
5076 #  undef setjmp
5077 #  define setjmp_undefined_for_msvc
5078 #endif
5079 
5080 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5081   switch (Intrinsic) {
5082   case Intrinsic::smul_fix:
5083     return ISD::SMULFIX;
5084   case Intrinsic::umul_fix:
5085     return ISD::UMULFIX;
5086   default:
5087     llvm_unreachable("Unhandled fixed point intrinsic");
5088   }
5089 }
5090 
5091 /// Lower the call to the specified intrinsic function. If we want to emit this
5092 /// as a call to a named external function, return the name. Otherwise, lower it
5093 /// and return null.
5094 const char *
5095 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
5096   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5097   SDLoc sdl = getCurSDLoc();
5098   DebugLoc dl = getCurDebugLoc();
5099   SDValue Res;
5100 
5101   switch (Intrinsic) {
5102   default:
5103     // By default, turn this into a target intrinsic node.
5104     visitTargetIntrinsic(I, Intrinsic);
5105     return nullptr;
5106   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5107   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5108   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5109   case Intrinsic::returnaddress:
5110     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5111                              TLI.getPointerTy(DAG.getDataLayout()),
5112                              getValue(I.getArgOperand(0))));
5113     return nullptr;
5114   case Intrinsic::addressofreturnaddress:
5115     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5116                              TLI.getPointerTy(DAG.getDataLayout())));
5117     return nullptr;
5118   case Intrinsic::sponentry:
5119     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5120                              TLI.getPointerTy(DAG.getDataLayout())));
5121     return nullptr;
5122   case Intrinsic::frameaddress:
5123     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5124                              TLI.getPointerTy(DAG.getDataLayout()),
5125                              getValue(I.getArgOperand(0))));
5126     return nullptr;
5127   case Intrinsic::read_register: {
5128     Value *Reg = I.getArgOperand(0);
5129     SDValue Chain = getRoot();
5130     SDValue RegName =
5131         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5132     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5133     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5134       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5135     setValue(&I, Res);
5136     DAG.setRoot(Res.getValue(1));
5137     return nullptr;
5138   }
5139   case Intrinsic::write_register: {
5140     Value *Reg = I.getArgOperand(0);
5141     Value *RegValue = I.getArgOperand(1);
5142     SDValue Chain = getRoot();
5143     SDValue RegName =
5144         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5145     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5146                             RegName, getValue(RegValue)));
5147     return nullptr;
5148   }
5149   case Intrinsic::setjmp:
5150     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5151   case Intrinsic::longjmp:
5152     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5153   case Intrinsic::memcpy: {
5154     const auto &MCI = cast<MemCpyInst>(I);
5155     SDValue Op1 = getValue(I.getArgOperand(0));
5156     SDValue Op2 = getValue(I.getArgOperand(1));
5157     SDValue Op3 = getValue(I.getArgOperand(2));
5158     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5159     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5160     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5161     unsigned Align = MinAlign(DstAlign, SrcAlign);
5162     bool isVol = MCI.isVolatile();
5163     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5164     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5165     // node.
5166     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5167                                false, isTC,
5168                                MachinePointerInfo(I.getArgOperand(0)),
5169                                MachinePointerInfo(I.getArgOperand(1)));
5170     updateDAGForMaybeTailCall(MC);
5171     return nullptr;
5172   }
5173   case Intrinsic::memset: {
5174     const auto &MSI = cast<MemSetInst>(I);
5175     SDValue Op1 = getValue(I.getArgOperand(0));
5176     SDValue Op2 = getValue(I.getArgOperand(1));
5177     SDValue Op3 = getValue(I.getArgOperand(2));
5178     // @llvm.memset defines 0 and 1 to both mean no alignment.
5179     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5180     bool isVol = MSI.isVolatile();
5181     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5182     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5183                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5184     updateDAGForMaybeTailCall(MS);
5185     return nullptr;
5186   }
5187   case Intrinsic::memmove: {
5188     const auto &MMI = cast<MemMoveInst>(I);
5189     SDValue Op1 = getValue(I.getArgOperand(0));
5190     SDValue Op2 = getValue(I.getArgOperand(1));
5191     SDValue Op3 = getValue(I.getArgOperand(2));
5192     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5193     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5194     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5195     unsigned Align = MinAlign(DstAlign, SrcAlign);
5196     bool isVol = MMI.isVolatile();
5197     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5198     // FIXME: Support passing different dest/src alignments to the memmove DAG
5199     // node.
5200     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5201                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5202                                 MachinePointerInfo(I.getArgOperand(1)));
5203     updateDAGForMaybeTailCall(MM);
5204     return nullptr;
5205   }
5206   case Intrinsic::memcpy_element_unordered_atomic: {
5207     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5208     SDValue Dst = getValue(MI.getRawDest());
5209     SDValue Src = getValue(MI.getRawSource());
5210     SDValue Length = getValue(MI.getLength());
5211 
5212     unsigned DstAlign = MI.getDestAlignment();
5213     unsigned SrcAlign = MI.getSourceAlignment();
5214     Type *LengthTy = MI.getLength()->getType();
5215     unsigned ElemSz = MI.getElementSizeInBytes();
5216     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5217     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5218                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5219                                      MachinePointerInfo(MI.getRawDest()),
5220                                      MachinePointerInfo(MI.getRawSource()));
5221     updateDAGForMaybeTailCall(MC);
5222     return nullptr;
5223   }
5224   case Intrinsic::memmove_element_unordered_atomic: {
5225     auto &MI = cast<AtomicMemMoveInst>(I);
5226     SDValue Dst = getValue(MI.getRawDest());
5227     SDValue Src = getValue(MI.getRawSource());
5228     SDValue Length = getValue(MI.getLength());
5229 
5230     unsigned DstAlign = MI.getDestAlignment();
5231     unsigned SrcAlign = MI.getSourceAlignment();
5232     Type *LengthTy = MI.getLength()->getType();
5233     unsigned ElemSz = MI.getElementSizeInBytes();
5234     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5235     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5236                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5237                                       MachinePointerInfo(MI.getRawDest()),
5238                                       MachinePointerInfo(MI.getRawSource()));
5239     updateDAGForMaybeTailCall(MC);
5240     return nullptr;
5241   }
5242   case Intrinsic::memset_element_unordered_atomic: {
5243     auto &MI = cast<AtomicMemSetInst>(I);
5244     SDValue Dst = getValue(MI.getRawDest());
5245     SDValue Val = getValue(MI.getValue());
5246     SDValue Length = getValue(MI.getLength());
5247 
5248     unsigned DstAlign = MI.getDestAlignment();
5249     Type *LengthTy = MI.getLength()->getType();
5250     unsigned ElemSz = MI.getElementSizeInBytes();
5251     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5252     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5253                                      LengthTy, ElemSz, isTC,
5254                                      MachinePointerInfo(MI.getRawDest()));
5255     updateDAGForMaybeTailCall(MC);
5256     return nullptr;
5257   }
5258   case Intrinsic::dbg_addr:
5259   case Intrinsic::dbg_declare: {
5260     const auto &DI = cast<DbgVariableIntrinsic>(I);
5261     DILocalVariable *Variable = DI.getVariable();
5262     DIExpression *Expression = DI.getExpression();
5263     dropDanglingDebugInfo(Variable, Expression);
5264     assert(Variable && "Missing variable");
5265 
5266     // Check if address has undef value.
5267     const Value *Address = DI.getVariableLocation();
5268     if (!Address || isa<UndefValue>(Address) ||
5269         (Address->use_empty() && !isa<Argument>(Address))) {
5270       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5271       return nullptr;
5272     }
5273 
5274     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5275 
5276     // Check if this variable can be described by a frame index, typically
5277     // either as a static alloca or a byval parameter.
5278     int FI = std::numeric_limits<int>::max();
5279     if (const auto *AI =
5280             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5281       if (AI->isStaticAlloca()) {
5282         auto I = FuncInfo.StaticAllocaMap.find(AI);
5283         if (I != FuncInfo.StaticAllocaMap.end())
5284           FI = I->second;
5285       }
5286     } else if (const auto *Arg = dyn_cast<Argument>(
5287                    Address->stripInBoundsConstantOffsets())) {
5288       FI = FuncInfo.getArgumentFrameIndex(Arg);
5289     }
5290 
5291     // llvm.dbg.addr is control dependent and always generates indirect
5292     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5293     // the MachineFunction variable table.
5294     if (FI != std::numeric_limits<int>::max()) {
5295       if (Intrinsic == Intrinsic::dbg_addr) {
5296         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5297             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5298         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5299       }
5300       return nullptr;
5301     }
5302 
5303     SDValue &N = NodeMap[Address];
5304     if (!N.getNode() && isa<Argument>(Address))
5305       // Check unused arguments map.
5306       N = UnusedArgNodeMap[Address];
5307     SDDbgValue *SDV;
5308     if (N.getNode()) {
5309       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5310         Address = BCI->getOperand(0);
5311       // Parameters are handled specially.
5312       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5313       if (isParameter && FINode) {
5314         // Byval parameter. We have a frame index at this point.
5315         SDV =
5316             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5317                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5318       } else if (isa<Argument>(Address)) {
5319         // Address is an argument, so try to emit its dbg value using
5320         // virtual register info from the FuncInfo.ValueMap.
5321         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5322         return nullptr;
5323       } else {
5324         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5325                               true, dl, SDNodeOrder);
5326       }
5327       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5328     } else {
5329       // If Address is an argument then try to emit its dbg value using
5330       // virtual register info from the FuncInfo.ValueMap.
5331       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5332                                     N)) {
5333         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5334       }
5335     }
5336     return nullptr;
5337   }
5338   case Intrinsic::dbg_label: {
5339     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5340     DILabel *Label = DI.getLabel();
5341     assert(Label && "Missing label");
5342 
5343     SDDbgLabel *SDV;
5344     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5345     DAG.AddDbgLabel(SDV);
5346     return nullptr;
5347   }
5348   case Intrinsic::dbg_value: {
5349     const DbgValueInst &DI = cast<DbgValueInst>(I);
5350     assert(DI.getVariable() && "Missing variable");
5351 
5352     DILocalVariable *Variable = DI.getVariable();
5353     DIExpression *Expression = DI.getExpression();
5354     dropDanglingDebugInfo(Variable, Expression);
5355     const Value *V = DI.getValue();
5356     if (!V)
5357       return nullptr;
5358 
5359     SDDbgValue *SDV;
5360     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
5361         isa<ConstantPointerNull>(V)) {
5362       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5363       DAG.AddDbgValue(SDV, nullptr, false);
5364       return nullptr;
5365     }
5366 
5367     // If the Value is a frame index, we can create a FrameIndex debug value
5368     // without relying on the DAG at all.
5369     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
5370       auto SI = FuncInfo.StaticAllocaMap.find(AI);
5371       if (SI != FuncInfo.StaticAllocaMap.end()) {
5372         auto SDV =
5373             DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
5374                                       /*IsIndirect*/ false, dl, SDNodeOrder);
5375         // Do not attach the SDNodeDbgValue to an SDNode: this variable location
5376         // is still available even if the SDNode gets optimized out.
5377         DAG.AddDbgValue(SDV, nullptr, false);
5378         return nullptr;
5379       }
5380     }
5381 
5382     // Do not use getValue() in here; we don't want to generate code at
5383     // this point if it hasn't been done yet.
5384     SDValue N = NodeMap[V];
5385     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5386       N = UnusedArgNodeMap[V];
5387     if (N.getNode()) {
5388       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5389         return nullptr;
5390       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5391       DAG.AddDbgValue(SDV, N.getNode(), false);
5392       return nullptr;
5393     }
5394 
5395     // The value is not used in this block yet (or it would have an SDNode).
5396     // We still want the value to appear for the user if possible -- if it has
5397     // an associated VReg, we can refer to that instead.
5398     if (!isa<Argument>(V)) {
5399       auto VMI = FuncInfo.ValueMap.find(V);
5400       if (VMI != FuncInfo.ValueMap.end()) {
5401         unsigned Reg = VMI->second;
5402         // If this is a PHI node, it may be split up into several MI PHI nodes
5403         // (in FunctionLoweringInfo::set).
5404         RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
5405                          V->getType(), None);
5406         if (RFV.occupiesMultipleRegs()) {
5407           unsigned Offset = 0;
5408           unsigned BitsToDescribe = 0;
5409           if (auto VarSize = Variable->getSizeInBits())
5410             BitsToDescribe = *VarSize;
5411           if (auto Fragment = Expression->getFragmentInfo())
5412             BitsToDescribe = Fragment->SizeInBits;
5413           for (auto RegAndSize : RFV.getRegsAndSizes()) {
5414             unsigned RegisterSize = RegAndSize.second;
5415             // Bail out if all bits are described already.
5416             if (Offset >= BitsToDescribe)
5417               break;
5418             unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
5419                 ? BitsToDescribe - Offset
5420                 : RegisterSize;
5421             auto FragmentExpr = DIExpression::createFragmentExpression(
5422                 Expression, Offset, FragmentSize);
5423             if (!FragmentExpr)
5424                 continue;
5425             SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
5426                                       false, dl, SDNodeOrder);
5427             DAG.AddDbgValue(SDV, nullptr, false);
5428             Offset += RegisterSize;
5429           }
5430         } else {
5431           SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
5432                                     SDNodeOrder);
5433           DAG.AddDbgValue(SDV, nullptr, false);
5434         }
5435         return nullptr;
5436       }
5437     }
5438 
5439     // TODO: When we get here we will either drop the dbg.value completely, or
5440     // we try to move it forward by letting it dangle for awhile. So we should
5441     // probably add an extra DbgValue to the DAG here, with a reference to
5442     // "noreg", to indicate that we have lost the debug location for the
5443     // variable.
5444 
5445     if (!V->use_empty() ) {
5446       // Do not call getValue(V) yet, as we don't want to generate code.
5447       // Remember it for later.
5448       DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5449       return nullptr;
5450     }
5451 
5452     LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5453     LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5454     return nullptr;
5455   }
5456 
5457   case Intrinsic::eh_typeid_for: {
5458     // Find the type id for the given typeinfo.
5459     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5460     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5461     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5462     setValue(&I, Res);
5463     return nullptr;
5464   }
5465 
5466   case Intrinsic::eh_return_i32:
5467   case Intrinsic::eh_return_i64:
5468     DAG.getMachineFunction().setCallsEHReturn(true);
5469     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5470                             MVT::Other,
5471                             getControlRoot(),
5472                             getValue(I.getArgOperand(0)),
5473                             getValue(I.getArgOperand(1))));
5474     return nullptr;
5475   case Intrinsic::eh_unwind_init:
5476     DAG.getMachineFunction().setCallsUnwindInit(true);
5477     return nullptr;
5478   case Intrinsic::eh_dwarf_cfa:
5479     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5480                              TLI.getPointerTy(DAG.getDataLayout()),
5481                              getValue(I.getArgOperand(0))));
5482     return nullptr;
5483   case Intrinsic::eh_sjlj_callsite: {
5484     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5485     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5486     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5487     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5488 
5489     MMI.setCurrentCallSite(CI->getZExtValue());
5490     return nullptr;
5491   }
5492   case Intrinsic::eh_sjlj_functioncontext: {
5493     // Get and store the index of the function context.
5494     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5495     AllocaInst *FnCtx =
5496       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5497     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5498     MFI.setFunctionContextIndex(FI);
5499     return nullptr;
5500   }
5501   case Intrinsic::eh_sjlj_setjmp: {
5502     SDValue Ops[2];
5503     Ops[0] = getRoot();
5504     Ops[1] = getValue(I.getArgOperand(0));
5505     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5506                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5507     setValue(&I, Op.getValue(0));
5508     DAG.setRoot(Op.getValue(1));
5509     return nullptr;
5510   }
5511   case Intrinsic::eh_sjlj_longjmp:
5512     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5513                             getRoot(), getValue(I.getArgOperand(0))));
5514     return nullptr;
5515   case Intrinsic::eh_sjlj_setup_dispatch:
5516     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5517                             getRoot()));
5518     return nullptr;
5519   case Intrinsic::masked_gather:
5520     visitMaskedGather(I);
5521     return nullptr;
5522   case Intrinsic::masked_load:
5523     visitMaskedLoad(I);
5524     return nullptr;
5525   case Intrinsic::masked_scatter:
5526     visitMaskedScatter(I);
5527     return nullptr;
5528   case Intrinsic::masked_store:
5529     visitMaskedStore(I);
5530     return nullptr;
5531   case Intrinsic::masked_expandload:
5532     visitMaskedLoad(I, true /* IsExpanding */);
5533     return nullptr;
5534   case Intrinsic::masked_compressstore:
5535     visitMaskedStore(I, true /* IsCompressing */);
5536     return nullptr;
5537   case Intrinsic::x86_mmx_pslli_w:
5538   case Intrinsic::x86_mmx_pslli_d:
5539   case Intrinsic::x86_mmx_pslli_q:
5540   case Intrinsic::x86_mmx_psrli_w:
5541   case Intrinsic::x86_mmx_psrli_d:
5542   case Intrinsic::x86_mmx_psrli_q:
5543   case Intrinsic::x86_mmx_psrai_w:
5544   case Intrinsic::x86_mmx_psrai_d: {
5545     SDValue ShAmt = getValue(I.getArgOperand(1));
5546     if (isa<ConstantSDNode>(ShAmt)) {
5547       visitTargetIntrinsic(I, Intrinsic);
5548       return nullptr;
5549     }
5550     unsigned NewIntrinsic = 0;
5551     EVT ShAmtVT = MVT::v2i32;
5552     switch (Intrinsic) {
5553     case Intrinsic::x86_mmx_pslli_w:
5554       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5555       break;
5556     case Intrinsic::x86_mmx_pslli_d:
5557       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5558       break;
5559     case Intrinsic::x86_mmx_pslli_q:
5560       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5561       break;
5562     case Intrinsic::x86_mmx_psrli_w:
5563       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5564       break;
5565     case Intrinsic::x86_mmx_psrli_d:
5566       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5567       break;
5568     case Intrinsic::x86_mmx_psrli_q:
5569       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5570       break;
5571     case Intrinsic::x86_mmx_psrai_w:
5572       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5573       break;
5574     case Intrinsic::x86_mmx_psrai_d:
5575       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5576       break;
5577     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5578     }
5579 
5580     // The vector shift intrinsics with scalars uses 32b shift amounts but
5581     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5582     // to be zero.
5583     // We must do this early because v2i32 is not a legal type.
5584     SDValue ShOps[2];
5585     ShOps[0] = ShAmt;
5586     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5587     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5588     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5589     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5590     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5591                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5592                        getValue(I.getArgOperand(0)), ShAmt);
5593     setValue(&I, Res);
5594     return nullptr;
5595   }
5596   case Intrinsic::powi:
5597     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5598                             getValue(I.getArgOperand(1)), DAG));
5599     return nullptr;
5600   case Intrinsic::log:
5601     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5602     return nullptr;
5603   case Intrinsic::log2:
5604     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5605     return nullptr;
5606   case Intrinsic::log10:
5607     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5608     return nullptr;
5609   case Intrinsic::exp:
5610     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5611     return nullptr;
5612   case Intrinsic::exp2:
5613     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5614     return nullptr;
5615   case Intrinsic::pow:
5616     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5617                            getValue(I.getArgOperand(1)), DAG, TLI));
5618     return nullptr;
5619   case Intrinsic::sqrt:
5620   case Intrinsic::fabs:
5621   case Intrinsic::sin:
5622   case Intrinsic::cos:
5623   case Intrinsic::floor:
5624   case Intrinsic::ceil:
5625   case Intrinsic::trunc:
5626   case Intrinsic::rint:
5627   case Intrinsic::nearbyint:
5628   case Intrinsic::round:
5629   case Intrinsic::canonicalize: {
5630     unsigned Opcode;
5631     switch (Intrinsic) {
5632     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5633     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5634     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5635     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5636     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5637     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5638     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5639     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5640     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5641     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5642     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5643     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5644     }
5645 
5646     setValue(&I, DAG.getNode(Opcode, sdl,
5647                              getValue(I.getArgOperand(0)).getValueType(),
5648                              getValue(I.getArgOperand(0))));
5649     return nullptr;
5650   }
5651   case Intrinsic::minnum: {
5652     auto VT = getValue(I.getArgOperand(0)).getValueType();
5653     unsigned Opc =
5654         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
5655             ? ISD::FMINIMUM
5656             : ISD::FMINNUM;
5657     setValue(&I, DAG.getNode(Opc, sdl, VT,
5658                              getValue(I.getArgOperand(0)),
5659                              getValue(I.getArgOperand(1))));
5660     return nullptr;
5661   }
5662   case Intrinsic::maxnum: {
5663     auto VT = getValue(I.getArgOperand(0)).getValueType();
5664     unsigned Opc =
5665         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
5666             ? ISD::FMAXIMUM
5667             : ISD::FMAXNUM;
5668     setValue(&I, DAG.getNode(Opc, sdl, VT,
5669                              getValue(I.getArgOperand(0)),
5670                              getValue(I.getArgOperand(1))));
5671     return nullptr;
5672   }
5673   case Intrinsic::minimum:
5674     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
5675                              getValue(I.getArgOperand(0)).getValueType(),
5676                              getValue(I.getArgOperand(0)),
5677                              getValue(I.getArgOperand(1))));
5678     return nullptr;
5679   case Intrinsic::maximum:
5680     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
5681                              getValue(I.getArgOperand(0)).getValueType(),
5682                              getValue(I.getArgOperand(0)),
5683                              getValue(I.getArgOperand(1))));
5684     return nullptr;
5685   case Intrinsic::copysign:
5686     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5687                              getValue(I.getArgOperand(0)).getValueType(),
5688                              getValue(I.getArgOperand(0)),
5689                              getValue(I.getArgOperand(1))));
5690     return nullptr;
5691   case Intrinsic::fma:
5692     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5693                              getValue(I.getArgOperand(0)).getValueType(),
5694                              getValue(I.getArgOperand(0)),
5695                              getValue(I.getArgOperand(1)),
5696                              getValue(I.getArgOperand(2))));
5697     return nullptr;
5698   case Intrinsic::experimental_constrained_fadd:
5699   case Intrinsic::experimental_constrained_fsub:
5700   case Intrinsic::experimental_constrained_fmul:
5701   case Intrinsic::experimental_constrained_fdiv:
5702   case Intrinsic::experimental_constrained_frem:
5703   case Intrinsic::experimental_constrained_fma:
5704   case Intrinsic::experimental_constrained_sqrt:
5705   case Intrinsic::experimental_constrained_pow:
5706   case Intrinsic::experimental_constrained_powi:
5707   case Intrinsic::experimental_constrained_sin:
5708   case Intrinsic::experimental_constrained_cos:
5709   case Intrinsic::experimental_constrained_exp:
5710   case Intrinsic::experimental_constrained_exp2:
5711   case Intrinsic::experimental_constrained_log:
5712   case Intrinsic::experimental_constrained_log10:
5713   case Intrinsic::experimental_constrained_log2:
5714   case Intrinsic::experimental_constrained_rint:
5715   case Intrinsic::experimental_constrained_nearbyint:
5716   case Intrinsic::experimental_constrained_maxnum:
5717   case Intrinsic::experimental_constrained_minnum:
5718   case Intrinsic::experimental_constrained_ceil:
5719   case Intrinsic::experimental_constrained_floor:
5720   case Intrinsic::experimental_constrained_round:
5721   case Intrinsic::experimental_constrained_trunc:
5722     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5723     return nullptr;
5724   case Intrinsic::fmuladd: {
5725     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5726     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5727         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5728       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5729                                getValue(I.getArgOperand(0)).getValueType(),
5730                                getValue(I.getArgOperand(0)),
5731                                getValue(I.getArgOperand(1)),
5732                                getValue(I.getArgOperand(2))));
5733     } else {
5734       // TODO: Intrinsic calls should have fast-math-flags.
5735       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5736                                 getValue(I.getArgOperand(0)).getValueType(),
5737                                 getValue(I.getArgOperand(0)),
5738                                 getValue(I.getArgOperand(1)));
5739       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5740                                 getValue(I.getArgOperand(0)).getValueType(),
5741                                 Mul,
5742                                 getValue(I.getArgOperand(2)));
5743       setValue(&I, Add);
5744     }
5745     return nullptr;
5746   }
5747   case Intrinsic::convert_to_fp16:
5748     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5749                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5750                                          getValue(I.getArgOperand(0)),
5751                                          DAG.getTargetConstant(0, sdl,
5752                                                                MVT::i32))));
5753     return nullptr;
5754   case Intrinsic::convert_from_fp16:
5755     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5756                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5757                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5758                                          getValue(I.getArgOperand(0)))));
5759     return nullptr;
5760   case Intrinsic::pcmarker: {
5761     SDValue Tmp = getValue(I.getArgOperand(0));
5762     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5763     return nullptr;
5764   }
5765   case Intrinsic::readcyclecounter: {
5766     SDValue Op = getRoot();
5767     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5768                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5769     setValue(&I, Res);
5770     DAG.setRoot(Res.getValue(1));
5771     return nullptr;
5772   }
5773   case Intrinsic::bitreverse:
5774     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5775                              getValue(I.getArgOperand(0)).getValueType(),
5776                              getValue(I.getArgOperand(0))));
5777     return nullptr;
5778   case Intrinsic::bswap:
5779     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5780                              getValue(I.getArgOperand(0)).getValueType(),
5781                              getValue(I.getArgOperand(0))));
5782     return nullptr;
5783   case Intrinsic::cttz: {
5784     SDValue Arg = getValue(I.getArgOperand(0));
5785     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5786     EVT Ty = Arg.getValueType();
5787     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5788                              sdl, Ty, Arg));
5789     return nullptr;
5790   }
5791   case Intrinsic::ctlz: {
5792     SDValue Arg = getValue(I.getArgOperand(0));
5793     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5794     EVT Ty = Arg.getValueType();
5795     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5796                              sdl, Ty, Arg));
5797     return nullptr;
5798   }
5799   case Intrinsic::ctpop: {
5800     SDValue Arg = getValue(I.getArgOperand(0));
5801     EVT Ty = Arg.getValueType();
5802     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5803     return nullptr;
5804   }
5805   case Intrinsic::fshl:
5806   case Intrinsic::fshr: {
5807     bool IsFSHL = Intrinsic == Intrinsic::fshl;
5808     SDValue X = getValue(I.getArgOperand(0));
5809     SDValue Y = getValue(I.getArgOperand(1));
5810     SDValue Z = getValue(I.getArgOperand(2));
5811     EVT VT = X.getValueType();
5812     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
5813     SDValue Zero = DAG.getConstant(0, sdl, VT);
5814     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
5815 
5816     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
5817     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
5818       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
5819       return nullptr;
5820     }
5821 
5822     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
5823     // avoid the select that is necessary in the general case to filter out
5824     // the 0-shift possibility that leads to UB.
5825     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
5826       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
5827       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
5828         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
5829         return nullptr;
5830       }
5831 
5832       // Some targets only rotate one way. Try the opposite direction.
5833       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
5834       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
5835         // Negate the shift amount because it is safe to ignore the high bits.
5836         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5837         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
5838         return nullptr;
5839       }
5840 
5841       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
5842       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
5843       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5844       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
5845       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
5846       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
5847       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
5848       return nullptr;
5849     }
5850 
5851     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
5852     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
5853     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
5854     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
5855     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
5856     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
5857 
5858     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
5859     // and that is undefined. We must compare and select to avoid UB.
5860     EVT CCVT = MVT::i1;
5861     if (VT.isVector())
5862       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
5863 
5864     // For fshl, 0-shift returns the 1st arg (X).
5865     // For fshr, 0-shift returns the 2nd arg (Y).
5866     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
5867     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
5868     return nullptr;
5869   }
5870   case Intrinsic::sadd_sat: {
5871     SDValue Op1 = getValue(I.getArgOperand(0));
5872     SDValue Op2 = getValue(I.getArgOperand(1));
5873     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
5874     return nullptr;
5875   }
5876   case Intrinsic::uadd_sat: {
5877     SDValue Op1 = getValue(I.getArgOperand(0));
5878     SDValue Op2 = getValue(I.getArgOperand(1));
5879     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
5880     return nullptr;
5881   }
5882   case Intrinsic::ssub_sat: {
5883     SDValue Op1 = getValue(I.getArgOperand(0));
5884     SDValue Op2 = getValue(I.getArgOperand(1));
5885     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
5886     return nullptr;
5887   }
5888   case Intrinsic::usub_sat: {
5889     SDValue Op1 = getValue(I.getArgOperand(0));
5890     SDValue Op2 = getValue(I.getArgOperand(1));
5891     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
5892     return nullptr;
5893   }
5894   case Intrinsic::smul_fix:
5895   case Intrinsic::umul_fix: {
5896     SDValue Op1 = getValue(I.getArgOperand(0));
5897     SDValue Op2 = getValue(I.getArgOperand(1));
5898     SDValue Op3 = getValue(I.getArgOperand(2));
5899     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
5900                              Op1.getValueType(), Op1, Op2, Op3));
5901     return nullptr;
5902   }
5903   case Intrinsic::stacksave: {
5904     SDValue Op = getRoot();
5905     Res = DAG.getNode(
5906         ISD::STACKSAVE, sdl,
5907         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5908     setValue(&I, Res);
5909     DAG.setRoot(Res.getValue(1));
5910     return nullptr;
5911   }
5912   case Intrinsic::stackrestore:
5913     Res = getValue(I.getArgOperand(0));
5914     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5915     return nullptr;
5916   case Intrinsic::get_dynamic_area_offset: {
5917     SDValue Op = getRoot();
5918     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5919     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5920     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5921     // target.
5922     if (PtrTy != ResTy)
5923       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5924                          " intrinsic!");
5925     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5926                       Op);
5927     DAG.setRoot(Op);
5928     setValue(&I, Res);
5929     return nullptr;
5930   }
5931   case Intrinsic::stackguard: {
5932     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5933     MachineFunction &MF = DAG.getMachineFunction();
5934     const Module &M = *MF.getFunction().getParent();
5935     SDValue Chain = getRoot();
5936     if (TLI.useLoadStackGuardNode()) {
5937       Res = getLoadStackGuard(DAG, sdl, Chain);
5938     } else {
5939       const Value *Global = TLI.getSDagStackGuard(M);
5940       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5941       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5942                         MachinePointerInfo(Global, 0), Align,
5943                         MachineMemOperand::MOVolatile);
5944     }
5945     if (TLI.useStackGuardXorFP())
5946       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
5947     DAG.setRoot(Chain);
5948     setValue(&I, Res);
5949     return nullptr;
5950   }
5951   case Intrinsic::stackprotector: {
5952     // Emit code into the DAG to store the stack guard onto the stack.
5953     MachineFunction &MF = DAG.getMachineFunction();
5954     MachineFrameInfo &MFI = MF.getFrameInfo();
5955     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5956     SDValue Src, Chain = getRoot();
5957 
5958     if (TLI.useLoadStackGuardNode())
5959       Src = getLoadStackGuard(DAG, sdl, Chain);
5960     else
5961       Src = getValue(I.getArgOperand(0));   // The guard's value.
5962 
5963     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5964 
5965     int FI = FuncInfo.StaticAllocaMap[Slot];
5966     MFI.setStackProtectorIndex(FI);
5967 
5968     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5969 
5970     // Store the stack protector onto the stack.
5971     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5972                                                  DAG.getMachineFunction(), FI),
5973                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5974     setValue(&I, Res);
5975     DAG.setRoot(Res);
5976     return nullptr;
5977   }
5978   case Intrinsic::objectsize: {
5979     // If we don't know by now, we're never going to know.
5980     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5981 
5982     assert(CI && "Non-constant type in __builtin_object_size?");
5983 
5984     SDValue Arg = getValue(I.getCalledValue());
5985     EVT Ty = Arg.getValueType();
5986 
5987     if (CI->isZero())
5988       Res = DAG.getConstant(-1ULL, sdl, Ty);
5989     else
5990       Res = DAG.getConstant(0, sdl, Ty);
5991 
5992     setValue(&I, Res);
5993     return nullptr;
5994   }
5995 
5996   case Intrinsic::is_constant:
5997     // If this wasn't constant-folded away by now, then it's not a
5998     // constant.
5999     setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
6000     return nullptr;
6001 
6002   case Intrinsic::annotation:
6003   case Intrinsic::ptr_annotation:
6004   case Intrinsic::launder_invariant_group:
6005   case Intrinsic::strip_invariant_group:
6006     // Drop the intrinsic, but forward the value
6007     setValue(&I, getValue(I.getOperand(0)));
6008     return nullptr;
6009   case Intrinsic::assume:
6010   case Intrinsic::var_annotation:
6011   case Intrinsic::sideeffect:
6012     // Discard annotate attributes, assumptions, and artificial side-effects.
6013     return nullptr;
6014 
6015   case Intrinsic::codeview_annotation: {
6016     // Emit a label associated with this metadata.
6017     MachineFunction &MF = DAG.getMachineFunction();
6018     MCSymbol *Label =
6019         MF.getMMI().getContext().createTempSymbol("annotation", true);
6020     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6021     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6022     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6023     DAG.setRoot(Res);
6024     return nullptr;
6025   }
6026 
6027   case Intrinsic::init_trampoline: {
6028     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6029 
6030     SDValue Ops[6];
6031     Ops[0] = getRoot();
6032     Ops[1] = getValue(I.getArgOperand(0));
6033     Ops[2] = getValue(I.getArgOperand(1));
6034     Ops[3] = getValue(I.getArgOperand(2));
6035     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6036     Ops[5] = DAG.getSrcValue(F);
6037 
6038     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6039 
6040     DAG.setRoot(Res);
6041     return nullptr;
6042   }
6043   case Intrinsic::adjust_trampoline:
6044     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6045                              TLI.getPointerTy(DAG.getDataLayout()),
6046                              getValue(I.getArgOperand(0))));
6047     return nullptr;
6048   case Intrinsic::gcroot: {
6049     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6050            "only valid in functions with gc specified, enforced by Verifier");
6051     assert(GFI && "implied by previous");
6052     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6053     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6054 
6055     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6056     GFI->addStackRoot(FI->getIndex(), TypeMap);
6057     return nullptr;
6058   }
6059   case Intrinsic::gcread:
6060   case Intrinsic::gcwrite:
6061     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6062   case Intrinsic::flt_rounds:
6063     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6064     return nullptr;
6065 
6066   case Intrinsic::expect:
6067     // Just replace __builtin_expect(exp, c) with EXP.
6068     setValue(&I, getValue(I.getArgOperand(0)));
6069     return nullptr;
6070 
6071   case Intrinsic::debugtrap:
6072   case Intrinsic::trap: {
6073     StringRef TrapFuncName =
6074         I.getAttributes()
6075             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6076             .getValueAsString();
6077     if (TrapFuncName.empty()) {
6078       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6079         ISD::TRAP : ISD::DEBUGTRAP;
6080       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6081       return nullptr;
6082     }
6083     TargetLowering::ArgListTy Args;
6084 
6085     TargetLowering::CallLoweringInfo CLI(DAG);
6086     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6087         CallingConv::C, I.getType(),
6088         DAG.getExternalSymbol(TrapFuncName.data(),
6089                               TLI.getPointerTy(DAG.getDataLayout())),
6090         std::move(Args));
6091 
6092     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6093     DAG.setRoot(Result.second);
6094     return nullptr;
6095   }
6096 
6097   case Intrinsic::uadd_with_overflow:
6098   case Intrinsic::sadd_with_overflow:
6099   case Intrinsic::usub_with_overflow:
6100   case Intrinsic::ssub_with_overflow:
6101   case Intrinsic::umul_with_overflow:
6102   case Intrinsic::smul_with_overflow: {
6103     ISD::NodeType Op;
6104     switch (Intrinsic) {
6105     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6106     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6107     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6108     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6109     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6110     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6111     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6112     }
6113     SDValue Op1 = getValue(I.getArgOperand(0));
6114     SDValue Op2 = getValue(I.getArgOperand(1));
6115 
6116     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
6117     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6118     return nullptr;
6119   }
6120   case Intrinsic::prefetch: {
6121     SDValue Ops[5];
6122     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6123     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6124     Ops[0] = DAG.getRoot();
6125     Ops[1] = getValue(I.getArgOperand(0));
6126     Ops[2] = getValue(I.getArgOperand(1));
6127     Ops[3] = getValue(I.getArgOperand(2));
6128     Ops[4] = getValue(I.getArgOperand(3));
6129     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6130                                              DAG.getVTList(MVT::Other), Ops,
6131                                              EVT::getIntegerVT(*Context, 8),
6132                                              MachinePointerInfo(I.getArgOperand(0)),
6133                                              0, /* align */
6134                                              Flags);
6135 
6136     // Chain the prefetch in parallell with any pending loads, to stay out of
6137     // the way of later optimizations.
6138     PendingLoads.push_back(Result);
6139     Result = getRoot();
6140     DAG.setRoot(Result);
6141     return nullptr;
6142   }
6143   case Intrinsic::lifetime_start:
6144   case Intrinsic::lifetime_end: {
6145     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6146     // Stack coloring is not enabled in O0, discard region information.
6147     if (TM.getOptLevel() == CodeGenOpt::None)
6148       return nullptr;
6149 
6150     SmallVector<Value *, 4> Allocas;
6151     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
6152 
6153     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
6154            E = Allocas.end(); Object != E; ++Object) {
6155       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6156 
6157       // Could not find an Alloca.
6158       if (!LifetimeObject)
6159         continue;
6160 
6161       // First check that the Alloca is static, otherwise it won't have a
6162       // valid frame index.
6163       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6164       if (SI == FuncInfo.StaticAllocaMap.end())
6165         return nullptr;
6166 
6167       int FI = SI->second;
6168 
6169       SDValue Ops[2];
6170       Ops[0] = getRoot();
6171       Ops[1] =
6172           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
6173       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
6174 
6175       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
6176       DAG.setRoot(Res);
6177     }
6178     return nullptr;
6179   }
6180   case Intrinsic::invariant_start:
6181     // Discard region information.
6182     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6183     return nullptr;
6184   case Intrinsic::invariant_end:
6185     // Discard region information.
6186     return nullptr;
6187   case Intrinsic::clear_cache:
6188     return TLI.getClearCacheBuiltinName();
6189   case Intrinsic::donothing:
6190     // ignore
6191     return nullptr;
6192   case Intrinsic::experimental_stackmap:
6193     visitStackmap(I);
6194     return nullptr;
6195   case Intrinsic::experimental_patchpoint_void:
6196   case Intrinsic::experimental_patchpoint_i64:
6197     visitPatchpoint(&I);
6198     return nullptr;
6199   case Intrinsic::experimental_gc_statepoint:
6200     LowerStatepoint(ImmutableStatepoint(&I));
6201     return nullptr;
6202   case Intrinsic::experimental_gc_result:
6203     visitGCResult(cast<GCResultInst>(I));
6204     return nullptr;
6205   case Intrinsic::experimental_gc_relocate:
6206     visitGCRelocate(cast<GCRelocateInst>(I));
6207     return nullptr;
6208   case Intrinsic::instrprof_increment:
6209     llvm_unreachable("instrprof failed to lower an increment");
6210   case Intrinsic::instrprof_value_profile:
6211     llvm_unreachable("instrprof failed to lower a value profiling call");
6212   case Intrinsic::localescape: {
6213     MachineFunction &MF = DAG.getMachineFunction();
6214     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6215 
6216     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6217     // is the same on all targets.
6218     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6219       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6220       if (isa<ConstantPointerNull>(Arg))
6221         continue; // Skip null pointers. They represent a hole in index space.
6222       AllocaInst *Slot = cast<AllocaInst>(Arg);
6223       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6224              "can only escape static allocas");
6225       int FI = FuncInfo.StaticAllocaMap[Slot];
6226       MCSymbol *FrameAllocSym =
6227           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6228               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6229       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6230               TII->get(TargetOpcode::LOCAL_ESCAPE))
6231           .addSym(FrameAllocSym)
6232           .addFrameIndex(FI);
6233     }
6234 
6235     return nullptr;
6236   }
6237 
6238   case Intrinsic::localrecover: {
6239     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6240     MachineFunction &MF = DAG.getMachineFunction();
6241     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6242 
6243     // Get the symbol that defines the frame offset.
6244     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6245     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6246     unsigned IdxVal =
6247         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6248     MCSymbol *FrameAllocSym =
6249         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6250             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6251 
6252     // Create a MCSymbol for the label to avoid any target lowering
6253     // that would make this PC relative.
6254     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6255     SDValue OffsetVal =
6256         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6257 
6258     // Add the offset to the FP.
6259     Value *FP = I.getArgOperand(1);
6260     SDValue FPVal = getValue(FP);
6261     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6262     setValue(&I, Add);
6263 
6264     return nullptr;
6265   }
6266 
6267   case Intrinsic::eh_exceptionpointer:
6268   case Intrinsic::eh_exceptioncode: {
6269     // Get the exception pointer vreg, copy from it, and resize it to fit.
6270     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6271     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6272     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6273     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6274     SDValue N =
6275         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6276     if (Intrinsic == Intrinsic::eh_exceptioncode)
6277       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6278     setValue(&I, N);
6279     return nullptr;
6280   }
6281   case Intrinsic::xray_customevent: {
6282     // Here we want to make sure that the intrinsic behaves as if it has a
6283     // specific calling convention, and only for x86_64.
6284     // FIXME: Support other platforms later.
6285     const auto &Triple = DAG.getTarget().getTargetTriple();
6286     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6287       return nullptr;
6288 
6289     SDLoc DL = getCurSDLoc();
6290     SmallVector<SDValue, 8> Ops;
6291 
6292     // We want to say that we always want the arguments in registers.
6293     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6294     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6295     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6296     SDValue Chain = getRoot();
6297     Ops.push_back(LogEntryVal);
6298     Ops.push_back(StrSizeVal);
6299     Ops.push_back(Chain);
6300 
6301     // We need to enforce the calling convention for the callsite, so that
6302     // argument ordering is enforced correctly, and that register allocation can
6303     // see that some registers may be assumed clobbered and have to preserve
6304     // them across calls to the intrinsic.
6305     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6306                                            DL, NodeTys, Ops);
6307     SDValue patchableNode = SDValue(MN, 0);
6308     DAG.setRoot(patchableNode);
6309     setValue(&I, patchableNode);
6310     return nullptr;
6311   }
6312   case Intrinsic::xray_typedevent: {
6313     // Here we want to make sure that the intrinsic behaves as if it has a
6314     // specific calling convention, and only for x86_64.
6315     // FIXME: Support other platforms later.
6316     const auto &Triple = DAG.getTarget().getTargetTriple();
6317     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6318       return nullptr;
6319 
6320     SDLoc DL = getCurSDLoc();
6321     SmallVector<SDValue, 8> Ops;
6322 
6323     // We want to say that we always want the arguments in registers.
6324     // It's unclear to me how manipulating the selection DAG here forces callers
6325     // to provide arguments in registers instead of on the stack.
6326     SDValue LogTypeId = getValue(I.getArgOperand(0));
6327     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6328     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6329     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6330     SDValue Chain = getRoot();
6331     Ops.push_back(LogTypeId);
6332     Ops.push_back(LogEntryVal);
6333     Ops.push_back(StrSizeVal);
6334     Ops.push_back(Chain);
6335 
6336     // We need to enforce the calling convention for the callsite, so that
6337     // argument ordering is enforced correctly, and that register allocation can
6338     // see that some registers may be assumed clobbered and have to preserve
6339     // them across calls to the intrinsic.
6340     MachineSDNode *MN = DAG.getMachineNode(
6341         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6342     SDValue patchableNode = SDValue(MN, 0);
6343     DAG.setRoot(patchableNode);
6344     setValue(&I, patchableNode);
6345     return nullptr;
6346   }
6347   case Intrinsic::experimental_deoptimize:
6348     LowerDeoptimizeCall(&I);
6349     return nullptr;
6350 
6351   case Intrinsic::experimental_vector_reduce_fadd:
6352   case Intrinsic::experimental_vector_reduce_fmul:
6353   case Intrinsic::experimental_vector_reduce_add:
6354   case Intrinsic::experimental_vector_reduce_mul:
6355   case Intrinsic::experimental_vector_reduce_and:
6356   case Intrinsic::experimental_vector_reduce_or:
6357   case Intrinsic::experimental_vector_reduce_xor:
6358   case Intrinsic::experimental_vector_reduce_smax:
6359   case Intrinsic::experimental_vector_reduce_smin:
6360   case Intrinsic::experimental_vector_reduce_umax:
6361   case Intrinsic::experimental_vector_reduce_umin:
6362   case Intrinsic::experimental_vector_reduce_fmax:
6363   case Intrinsic::experimental_vector_reduce_fmin:
6364     visitVectorReduce(I, Intrinsic);
6365     return nullptr;
6366 
6367   case Intrinsic::icall_branch_funnel: {
6368     SmallVector<SDValue, 16> Ops;
6369     Ops.push_back(DAG.getRoot());
6370     Ops.push_back(getValue(I.getArgOperand(0)));
6371 
6372     int64_t Offset;
6373     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6374         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6375     if (!Base)
6376       report_fatal_error(
6377           "llvm.icall.branch.funnel operand must be a GlobalValue");
6378     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6379 
6380     struct BranchFunnelTarget {
6381       int64_t Offset;
6382       SDValue Target;
6383     };
6384     SmallVector<BranchFunnelTarget, 8> Targets;
6385 
6386     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6387       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6388           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6389       if (ElemBase != Base)
6390         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6391                            "to the same GlobalValue");
6392 
6393       SDValue Val = getValue(I.getArgOperand(Op + 1));
6394       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6395       if (!GA)
6396         report_fatal_error(
6397             "llvm.icall.branch.funnel operand must be a GlobalValue");
6398       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6399                                      GA->getGlobal(), getCurSDLoc(),
6400                                      Val.getValueType(), GA->getOffset())});
6401     }
6402     llvm::sort(Targets,
6403                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6404                  return T1.Offset < T2.Offset;
6405                });
6406 
6407     for (auto &T : Targets) {
6408       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6409       Ops.push_back(T.Target);
6410     }
6411 
6412     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6413                                  getCurSDLoc(), MVT::Other, Ops),
6414               0);
6415     DAG.setRoot(N);
6416     setValue(&I, N);
6417     HasTailCall = true;
6418     return nullptr;
6419   }
6420 
6421   case Intrinsic::wasm_landingpad_index:
6422     // Information this intrinsic contained has been transferred to
6423     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6424     // delete it now.
6425     return nullptr;
6426   }
6427 }
6428 
6429 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6430     const ConstrainedFPIntrinsic &FPI) {
6431   SDLoc sdl = getCurSDLoc();
6432   unsigned Opcode;
6433   switch (FPI.getIntrinsicID()) {
6434   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6435   case Intrinsic::experimental_constrained_fadd:
6436     Opcode = ISD::STRICT_FADD;
6437     break;
6438   case Intrinsic::experimental_constrained_fsub:
6439     Opcode = ISD::STRICT_FSUB;
6440     break;
6441   case Intrinsic::experimental_constrained_fmul:
6442     Opcode = ISD::STRICT_FMUL;
6443     break;
6444   case Intrinsic::experimental_constrained_fdiv:
6445     Opcode = ISD::STRICT_FDIV;
6446     break;
6447   case Intrinsic::experimental_constrained_frem:
6448     Opcode = ISD::STRICT_FREM;
6449     break;
6450   case Intrinsic::experimental_constrained_fma:
6451     Opcode = ISD::STRICT_FMA;
6452     break;
6453   case Intrinsic::experimental_constrained_sqrt:
6454     Opcode = ISD::STRICT_FSQRT;
6455     break;
6456   case Intrinsic::experimental_constrained_pow:
6457     Opcode = ISD::STRICT_FPOW;
6458     break;
6459   case Intrinsic::experimental_constrained_powi:
6460     Opcode = ISD::STRICT_FPOWI;
6461     break;
6462   case Intrinsic::experimental_constrained_sin:
6463     Opcode = ISD::STRICT_FSIN;
6464     break;
6465   case Intrinsic::experimental_constrained_cos:
6466     Opcode = ISD::STRICT_FCOS;
6467     break;
6468   case Intrinsic::experimental_constrained_exp:
6469     Opcode = ISD::STRICT_FEXP;
6470     break;
6471   case Intrinsic::experimental_constrained_exp2:
6472     Opcode = ISD::STRICT_FEXP2;
6473     break;
6474   case Intrinsic::experimental_constrained_log:
6475     Opcode = ISD::STRICT_FLOG;
6476     break;
6477   case Intrinsic::experimental_constrained_log10:
6478     Opcode = ISD::STRICT_FLOG10;
6479     break;
6480   case Intrinsic::experimental_constrained_log2:
6481     Opcode = ISD::STRICT_FLOG2;
6482     break;
6483   case Intrinsic::experimental_constrained_rint:
6484     Opcode = ISD::STRICT_FRINT;
6485     break;
6486   case Intrinsic::experimental_constrained_nearbyint:
6487     Opcode = ISD::STRICT_FNEARBYINT;
6488     break;
6489   case Intrinsic::experimental_constrained_maxnum:
6490     Opcode = ISD::STRICT_FMAXNUM;
6491     break;
6492   case Intrinsic::experimental_constrained_minnum:
6493     Opcode = ISD::STRICT_FMINNUM;
6494     break;
6495   case Intrinsic::experimental_constrained_ceil:
6496     Opcode = ISD::STRICT_FCEIL;
6497     break;
6498   case Intrinsic::experimental_constrained_floor:
6499     Opcode = ISD::STRICT_FFLOOR;
6500     break;
6501   case Intrinsic::experimental_constrained_round:
6502     Opcode = ISD::STRICT_FROUND;
6503     break;
6504   case Intrinsic::experimental_constrained_trunc:
6505     Opcode = ISD::STRICT_FTRUNC;
6506     break;
6507   }
6508   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6509   SDValue Chain = getRoot();
6510   SmallVector<EVT, 4> ValueVTs;
6511   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6512   ValueVTs.push_back(MVT::Other); // Out chain
6513 
6514   SDVTList VTs = DAG.getVTList(ValueVTs);
6515   SDValue Result;
6516   if (FPI.isUnaryOp())
6517     Result = DAG.getNode(Opcode, sdl, VTs,
6518                          { Chain, getValue(FPI.getArgOperand(0)) });
6519   else if (FPI.isTernaryOp())
6520     Result = DAG.getNode(Opcode, sdl, VTs,
6521                          { Chain, getValue(FPI.getArgOperand(0)),
6522                                   getValue(FPI.getArgOperand(1)),
6523                                   getValue(FPI.getArgOperand(2)) });
6524   else
6525     Result = DAG.getNode(Opcode, sdl, VTs,
6526                          { Chain, getValue(FPI.getArgOperand(0)),
6527                            getValue(FPI.getArgOperand(1))  });
6528 
6529   assert(Result.getNode()->getNumValues() == 2);
6530   SDValue OutChain = Result.getValue(1);
6531   DAG.setRoot(OutChain);
6532   SDValue FPResult = Result.getValue(0);
6533   setValue(&FPI, FPResult);
6534 }
6535 
6536 std::pair<SDValue, SDValue>
6537 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6538                                     const BasicBlock *EHPadBB) {
6539   MachineFunction &MF = DAG.getMachineFunction();
6540   MachineModuleInfo &MMI = MF.getMMI();
6541   MCSymbol *BeginLabel = nullptr;
6542 
6543   if (EHPadBB) {
6544     // Insert a label before the invoke call to mark the try range.  This can be
6545     // used to detect deletion of the invoke via the MachineModuleInfo.
6546     BeginLabel = MMI.getContext().createTempSymbol();
6547 
6548     // For SjLj, keep track of which landing pads go with which invokes
6549     // so as to maintain the ordering of pads in the LSDA.
6550     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6551     if (CallSiteIndex) {
6552       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6553       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6554 
6555       // Now that the call site is handled, stop tracking it.
6556       MMI.setCurrentCallSite(0);
6557     }
6558 
6559     // Both PendingLoads and PendingExports must be flushed here;
6560     // this call might not return.
6561     (void)getRoot();
6562     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6563 
6564     CLI.setChain(getRoot());
6565   }
6566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6567   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6568 
6569   assert((CLI.IsTailCall || Result.second.getNode()) &&
6570          "Non-null chain expected with non-tail call!");
6571   assert((Result.second.getNode() || !Result.first.getNode()) &&
6572          "Null value expected with tail call!");
6573 
6574   if (!Result.second.getNode()) {
6575     // As a special case, a null chain means that a tail call has been emitted
6576     // and the DAG root is already updated.
6577     HasTailCall = true;
6578 
6579     // Since there's no actual continuation from this block, nothing can be
6580     // relying on us setting vregs for them.
6581     PendingExports.clear();
6582   } else {
6583     DAG.setRoot(Result.second);
6584   }
6585 
6586   if (EHPadBB) {
6587     // Insert a label at the end of the invoke call to mark the try range.  This
6588     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6589     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6590     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6591 
6592     // Inform MachineModuleInfo of range.
6593     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6594     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6595     // actually use outlined funclets and their LSDA info style.
6596     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6597       assert(CLI.CS);
6598       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6599       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6600                                 BeginLabel, EndLabel);
6601     } else if (!isScopedEHPersonality(Pers)) {
6602       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6603     }
6604   }
6605 
6606   return Result;
6607 }
6608 
6609 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6610                                       bool isTailCall,
6611                                       const BasicBlock *EHPadBB) {
6612   auto &DL = DAG.getDataLayout();
6613   FunctionType *FTy = CS.getFunctionType();
6614   Type *RetTy = CS.getType();
6615 
6616   TargetLowering::ArgListTy Args;
6617   Args.reserve(CS.arg_size());
6618 
6619   const Value *SwiftErrorVal = nullptr;
6620   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6621 
6622   // We can't tail call inside a function with a swifterror argument. Lowering
6623   // does not support this yet. It would have to move into the swifterror
6624   // register before the call.
6625   auto *Caller = CS.getInstruction()->getParent()->getParent();
6626   if (TLI.supportSwiftError() &&
6627       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6628     isTailCall = false;
6629 
6630   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6631        i != e; ++i) {
6632     TargetLowering::ArgListEntry Entry;
6633     const Value *V = *i;
6634 
6635     // Skip empty types
6636     if (V->getType()->isEmptyTy())
6637       continue;
6638 
6639     SDValue ArgNode = getValue(V);
6640     Entry.Node = ArgNode; Entry.Ty = V->getType();
6641 
6642     Entry.setAttributes(&CS, i - CS.arg_begin());
6643 
6644     // Use swifterror virtual register as input to the call.
6645     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6646       SwiftErrorVal = V;
6647       // We find the virtual register for the actual swifterror argument.
6648       // Instead of using the Value, we use the virtual register instead.
6649       Entry.Node = DAG.getRegister(FuncInfo
6650                                        .getOrCreateSwiftErrorVRegUseAt(
6651                                            CS.getInstruction(), FuncInfo.MBB, V)
6652                                        .first,
6653                                    EVT(TLI.getPointerTy(DL)));
6654     }
6655 
6656     Args.push_back(Entry);
6657 
6658     // If we have an explicit sret argument that is an Instruction, (i.e., it
6659     // might point to function-local memory), we can't meaningfully tail-call.
6660     if (Entry.IsSRet && isa<Instruction>(V))
6661       isTailCall = false;
6662   }
6663 
6664   // Check if target-independent constraints permit a tail call here.
6665   // Target-dependent constraints are checked within TLI->LowerCallTo.
6666   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6667     isTailCall = false;
6668 
6669   // Disable tail calls if there is an swifterror argument. Targets have not
6670   // been updated to support tail calls.
6671   if (TLI.supportSwiftError() && SwiftErrorVal)
6672     isTailCall = false;
6673 
6674   TargetLowering::CallLoweringInfo CLI(DAG);
6675   CLI.setDebugLoc(getCurSDLoc())
6676       .setChain(getRoot())
6677       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6678       .setTailCall(isTailCall)
6679       .setConvergent(CS.isConvergent());
6680   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6681 
6682   if (Result.first.getNode()) {
6683     const Instruction *Inst = CS.getInstruction();
6684     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6685     setValue(Inst, Result.first);
6686   }
6687 
6688   // The last element of CLI.InVals has the SDValue for swifterror return.
6689   // Here we copy it to a virtual register and update SwiftErrorMap for
6690   // book-keeping.
6691   if (SwiftErrorVal && TLI.supportSwiftError()) {
6692     // Get the last element of InVals.
6693     SDValue Src = CLI.InVals.back();
6694     unsigned VReg; bool CreatedVReg;
6695     std::tie(VReg, CreatedVReg) =
6696         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6697     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6698     // We update the virtual register for the actual swifterror argument.
6699     if (CreatedVReg)
6700       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6701     DAG.setRoot(CopyNode);
6702   }
6703 }
6704 
6705 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6706                              SelectionDAGBuilder &Builder) {
6707   // Check to see if this load can be trivially constant folded, e.g. if the
6708   // input is from a string literal.
6709   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6710     // Cast pointer to the type we really want to load.
6711     Type *LoadTy =
6712         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6713     if (LoadVT.isVector())
6714       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6715 
6716     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6717                                          PointerType::getUnqual(LoadTy));
6718 
6719     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6720             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6721       return Builder.getValue(LoadCst);
6722   }
6723 
6724   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6725   // still constant memory, the input chain can be the entry node.
6726   SDValue Root;
6727   bool ConstantMemory = false;
6728 
6729   // Do not serialize (non-volatile) loads of constant memory with anything.
6730   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6731     Root = Builder.DAG.getEntryNode();
6732     ConstantMemory = true;
6733   } else {
6734     // Do not serialize non-volatile loads against each other.
6735     Root = Builder.DAG.getRoot();
6736   }
6737 
6738   SDValue Ptr = Builder.getValue(PtrVal);
6739   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6740                                         Ptr, MachinePointerInfo(PtrVal),
6741                                         /* Alignment = */ 1);
6742 
6743   if (!ConstantMemory)
6744     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6745   return LoadVal;
6746 }
6747 
6748 /// Record the value for an instruction that produces an integer result,
6749 /// converting the type where necessary.
6750 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6751                                                   SDValue Value,
6752                                                   bool IsSigned) {
6753   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6754                                                     I.getType(), true);
6755   if (IsSigned)
6756     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6757   else
6758     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6759   setValue(&I, Value);
6760 }
6761 
6762 /// See if we can lower a memcmp call into an optimized form. If so, return
6763 /// true and lower it. Otherwise return false, and it will be lowered like a
6764 /// normal call.
6765 /// The caller already checked that \p I calls the appropriate LibFunc with a
6766 /// correct prototype.
6767 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6768   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6769   const Value *Size = I.getArgOperand(2);
6770   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6771   if (CSize && CSize->getZExtValue() == 0) {
6772     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6773                                                           I.getType(), true);
6774     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6775     return true;
6776   }
6777 
6778   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6779   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6780       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6781       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6782   if (Res.first.getNode()) {
6783     processIntegerCallValue(I, Res.first, true);
6784     PendingLoads.push_back(Res.second);
6785     return true;
6786   }
6787 
6788   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6789   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6790   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6791     return false;
6792 
6793   // If the target has a fast compare for the given size, it will return a
6794   // preferred load type for that size. Require that the load VT is legal and
6795   // that the target supports unaligned loads of that type. Otherwise, return
6796   // INVALID.
6797   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6798     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6799     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6800     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6801       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6802       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6803       // TODO: Check alignment of src and dest ptrs.
6804       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6805       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6806       if (!TLI.isTypeLegal(LVT) ||
6807           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6808           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6809         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6810     }
6811 
6812     return LVT;
6813   };
6814 
6815   // This turns into unaligned loads. We only do this if the target natively
6816   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6817   // we'll only produce a small number of byte loads.
6818   MVT LoadVT;
6819   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6820   switch (NumBitsToCompare) {
6821   default:
6822     return false;
6823   case 16:
6824     LoadVT = MVT::i16;
6825     break;
6826   case 32:
6827     LoadVT = MVT::i32;
6828     break;
6829   case 64:
6830   case 128:
6831   case 256:
6832     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6833     break;
6834   }
6835 
6836   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6837     return false;
6838 
6839   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6840   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6841 
6842   // Bitcast to a wide integer type if the loads are vectors.
6843   if (LoadVT.isVector()) {
6844     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6845     LoadL = DAG.getBitcast(CmpVT, LoadL);
6846     LoadR = DAG.getBitcast(CmpVT, LoadR);
6847   }
6848 
6849   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6850   processIntegerCallValue(I, Cmp, false);
6851   return true;
6852 }
6853 
6854 /// See if we can lower a memchr call into an optimized form. If so, return
6855 /// true and lower it. Otherwise return false, and it will be lowered like a
6856 /// normal call.
6857 /// The caller already checked that \p I calls the appropriate LibFunc with a
6858 /// correct prototype.
6859 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6860   const Value *Src = I.getArgOperand(0);
6861   const Value *Char = I.getArgOperand(1);
6862   const Value *Length = I.getArgOperand(2);
6863 
6864   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6865   std::pair<SDValue, SDValue> Res =
6866     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6867                                 getValue(Src), getValue(Char), getValue(Length),
6868                                 MachinePointerInfo(Src));
6869   if (Res.first.getNode()) {
6870     setValue(&I, Res.first);
6871     PendingLoads.push_back(Res.second);
6872     return true;
6873   }
6874 
6875   return false;
6876 }
6877 
6878 /// See if we can lower a mempcpy call into an optimized form. If so, return
6879 /// true and lower it. Otherwise return false, and it will be lowered like a
6880 /// normal call.
6881 /// The caller already checked that \p I calls the appropriate LibFunc with a
6882 /// correct prototype.
6883 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6884   SDValue Dst = getValue(I.getArgOperand(0));
6885   SDValue Src = getValue(I.getArgOperand(1));
6886   SDValue Size = getValue(I.getArgOperand(2));
6887 
6888   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6889   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6890   unsigned Align = std::min(DstAlign, SrcAlign);
6891   if (Align == 0) // Alignment of one or both could not be inferred.
6892     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6893 
6894   bool isVol = false;
6895   SDLoc sdl = getCurSDLoc();
6896 
6897   // In the mempcpy context we need to pass in a false value for isTailCall
6898   // because the return pointer needs to be adjusted by the size of
6899   // the copied memory.
6900   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6901                              false, /*isTailCall=*/false,
6902                              MachinePointerInfo(I.getArgOperand(0)),
6903                              MachinePointerInfo(I.getArgOperand(1)));
6904   assert(MC.getNode() != nullptr &&
6905          "** memcpy should not be lowered as TailCall in mempcpy context **");
6906   DAG.setRoot(MC);
6907 
6908   // Check if Size needs to be truncated or extended.
6909   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6910 
6911   // Adjust return pointer to point just past the last dst byte.
6912   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6913                                     Dst, Size);
6914   setValue(&I, DstPlusSize);
6915   return true;
6916 }
6917 
6918 /// See if we can lower a strcpy call into an optimized form.  If so, return
6919 /// true and lower it, otherwise return false and it will be lowered like a
6920 /// normal call.
6921 /// The caller already checked that \p I calls the appropriate LibFunc with a
6922 /// correct prototype.
6923 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6924   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6925 
6926   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6927   std::pair<SDValue, SDValue> Res =
6928     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6929                                 getValue(Arg0), getValue(Arg1),
6930                                 MachinePointerInfo(Arg0),
6931                                 MachinePointerInfo(Arg1), isStpcpy);
6932   if (Res.first.getNode()) {
6933     setValue(&I, Res.first);
6934     DAG.setRoot(Res.second);
6935     return true;
6936   }
6937 
6938   return false;
6939 }
6940 
6941 /// See if we can lower a strcmp call into an optimized form.  If so, return
6942 /// true and lower it, otherwise return false and it will be lowered like a
6943 /// normal call.
6944 /// The caller already checked that \p I calls the appropriate LibFunc with a
6945 /// correct prototype.
6946 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6947   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6948 
6949   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6950   std::pair<SDValue, SDValue> Res =
6951     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6952                                 getValue(Arg0), getValue(Arg1),
6953                                 MachinePointerInfo(Arg0),
6954                                 MachinePointerInfo(Arg1));
6955   if (Res.first.getNode()) {
6956     processIntegerCallValue(I, Res.first, true);
6957     PendingLoads.push_back(Res.second);
6958     return true;
6959   }
6960 
6961   return false;
6962 }
6963 
6964 /// See if we can lower a strlen call into an optimized form.  If so, return
6965 /// true and lower it, otherwise return false and it will be lowered like a
6966 /// normal call.
6967 /// The caller already checked that \p I calls the appropriate LibFunc with a
6968 /// correct prototype.
6969 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6970   const Value *Arg0 = I.getArgOperand(0);
6971 
6972   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6973   std::pair<SDValue, SDValue> Res =
6974     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6975                                 getValue(Arg0), MachinePointerInfo(Arg0));
6976   if (Res.first.getNode()) {
6977     processIntegerCallValue(I, Res.first, false);
6978     PendingLoads.push_back(Res.second);
6979     return true;
6980   }
6981 
6982   return false;
6983 }
6984 
6985 /// See if we can lower a strnlen call into an optimized form.  If so, return
6986 /// true and lower it, otherwise return false and it will be lowered like a
6987 /// normal call.
6988 /// The caller already checked that \p I calls the appropriate LibFunc with a
6989 /// correct prototype.
6990 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6991   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6992 
6993   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6994   std::pair<SDValue, SDValue> Res =
6995     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6996                                  getValue(Arg0), getValue(Arg1),
6997                                  MachinePointerInfo(Arg0));
6998   if (Res.first.getNode()) {
6999     processIntegerCallValue(I, Res.first, false);
7000     PendingLoads.push_back(Res.second);
7001     return true;
7002   }
7003 
7004   return false;
7005 }
7006 
7007 /// See if we can lower a unary floating-point operation into an SDNode with
7008 /// the specified Opcode.  If so, return true and lower it, otherwise return
7009 /// false and it will be lowered like a normal call.
7010 /// The caller already checked that \p I calls the appropriate LibFunc with a
7011 /// correct prototype.
7012 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7013                                               unsigned Opcode) {
7014   // We already checked this call's prototype; verify it doesn't modify errno.
7015   if (!I.onlyReadsMemory())
7016     return false;
7017 
7018   SDValue Tmp = getValue(I.getArgOperand(0));
7019   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7020   return true;
7021 }
7022 
7023 /// See if we can lower a binary floating-point operation into an SDNode with
7024 /// the specified Opcode. If so, return true and lower it. Otherwise return
7025 /// false, and it will be lowered like a normal call.
7026 /// The caller already checked that \p I calls the appropriate LibFunc with a
7027 /// correct prototype.
7028 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7029                                                unsigned Opcode) {
7030   // We already checked this call's prototype; verify it doesn't modify errno.
7031   if (!I.onlyReadsMemory())
7032     return false;
7033 
7034   SDValue Tmp0 = getValue(I.getArgOperand(0));
7035   SDValue Tmp1 = getValue(I.getArgOperand(1));
7036   EVT VT = Tmp0.getValueType();
7037   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7038   return true;
7039 }
7040 
7041 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7042   // Handle inline assembly differently.
7043   if (isa<InlineAsm>(I.getCalledValue())) {
7044     visitInlineAsm(&I);
7045     return;
7046   }
7047 
7048   const char *RenameFn = nullptr;
7049   if (Function *F = I.getCalledFunction()) {
7050     if (F->isDeclaration()) {
7051       // Is this an LLVM intrinsic or a target-specific intrinsic?
7052       unsigned IID = F->getIntrinsicID();
7053       if (!IID)
7054         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7055           IID = II->getIntrinsicID(F);
7056 
7057       if (IID) {
7058         RenameFn = visitIntrinsicCall(I, IID);
7059         if (!RenameFn)
7060           return;
7061       }
7062     }
7063 
7064     // Check for well-known libc/libm calls.  If the function is internal, it
7065     // can't be a library call.  Don't do the check if marked as nobuiltin for
7066     // some reason or the call site requires strict floating point semantics.
7067     LibFunc Func;
7068     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7069         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7070         LibInfo->hasOptimizedCodeGen(Func)) {
7071       switch (Func) {
7072       default: break;
7073       case LibFunc_copysign:
7074       case LibFunc_copysignf:
7075       case LibFunc_copysignl:
7076         // We already checked this call's prototype; verify it doesn't modify
7077         // errno.
7078         if (I.onlyReadsMemory()) {
7079           SDValue LHS = getValue(I.getArgOperand(0));
7080           SDValue RHS = getValue(I.getArgOperand(1));
7081           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7082                                    LHS.getValueType(), LHS, RHS));
7083           return;
7084         }
7085         break;
7086       case LibFunc_fabs:
7087       case LibFunc_fabsf:
7088       case LibFunc_fabsl:
7089         if (visitUnaryFloatCall(I, ISD::FABS))
7090           return;
7091         break;
7092       case LibFunc_fmin:
7093       case LibFunc_fminf:
7094       case LibFunc_fminl:
7095         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7096           return;
7097         break;
7098       case LibFunc_fmax:
7099       case LibFunc_fmaxf:
7100       case LibFunc_fmaxl:
7101         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7102           return;
7103         break;
7104       case LibFunc_sin:
7105       case LibFunc_sinf:
7106       case LibFunc_sinl:
7107         if (visitUnaryFloatCall(I, ISD::FSIN))
7108           return;
7109         break;
7110       case LibFunc_cos:
7111       case LibFunc_cosf:
7112       case LibFunc_cosl:
7113         if (visitUnaryFloatCall(I, ISD::FCOS))
7114           return;
7115         break;
7116       case LibFunc_sqrt:
7117       case LibFunc_sqrtf:
7118       case LibFunc_sqrtl:
7119       case LibFunc_sqrt_finite:
7120       case LibFunc_sqrtf_finite:
7121       case LibFunc_sqrtl_finite:
7122         if (visitUnaryFloatCall(I, ISD::FSQRT))
7123           return;
7124         break;
7125       case LibFunc_floor:
7126       case LibFunc_floorf:
7127       case LibFunc_floorl:
7128         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7129           return;
7130         break;
7131       case LibFunc_nearbyint:
7132       case LibFunc_nearbyintf:
7133       case LibFunc_nearbyintl:
7134         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7135           return;
7136         break;
7137       case LibFunc_ceil:
7138       case LibFunc_ceilf:
7139       case LibFunc_ceill:
7140         if (visitUnaryFloatCall(I, ISD::FCEIL))
7141           return;
7142         break;
7143       case LibFunc_rint:
7144       case LibFunc_rintf:
7145       case LibFunc_rintl:
7146         if (visitUnaryFloatCall(I, ISD::FRINT))
7147           return;
7148         break;
7149       case LibFunc_round:
7150       case LibFunc_roundf:
7151       case LibFunc_roundl:
7152         if (visitUnaryFloatCall(I, ISD::FROUND))
7153           return;
7154         break;
7155       case LibFunc_trunc:
7156       case LibFunc_truncf:
7157       case LibFunc_truncl:
7158         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7159           return;
7160         break;
7161       case LibFunc_log2:
7162       case LibFunc_log2f:
7163       case LibFunc_log2l:
7164         if (visitUnaryFloatCall(I, ISD::FLOG2))
7165           return;
7166         break;
7167       case LibFunc_exp2:
7168       case LibFunc_exp2f:
7169       case LibFunc_exp2l:
7170         if (visitUnaryFloatCall(I, ISD::FEXP2))
7171           return;
7172         break;
7173       case LibFunc_memcmp:
7174         if (visitMemCmpCall(I))
7175           return;
7176         break;
7177       case LibFunc_mempcpy:
7178         if (visitMemPCpyCall(I))
7179           return;
7180         break;
7181       case LibFunc_memchr:
7182         if (visitMemChrCall(I))
7183           return;
7184         break;
7185       case LibFunc_strcpy:
7186         if (visitStrCpyCall(I, false))
7187           return;
7188         break;
7189       case LibFunc_stpcpy:
7190         if (visitStrCpyCall(I, true))
7191           return;
7192         break;
7193       case LibFunc_strcmp:
7194         if (visitStrCmpCall(I))
7195           return;
7196         break;
7197       case LibFunc_strlen:
7198         if (visitStrLenCall(I))
7199           return;
7200         break;
7201       case LibFunc_strnlen:
7202         if (visitStrNLenCall(I))
7203           return;
7204         break;
7205       }
7206     }
7207   }
7208 
7209   SDValue Callee;
7210   if (!RenameFn)
7211     Callee = getValue(I.getCalledValue());
7212   else
7213     Callee = DAG.getExternalSymbol(
7214         RenameFn,
7215         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7216 
7217   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7218   // have to do anything here to lower funclet bundles.
7219   assert(!I.hasOperandBundlesOtherThan(
7220              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7221          "Cannot lower calls with arbitrary operand bundles!");
7222 
7223   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7224     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7225   else
7226     // Check if we can potentially perform a tail call. More detailed checking
7227     // is be done within LowerCallTo, after more information about the call is
7228     // known.
7229     LowerCallTo(&I, Callee, I.isTailCall());
7230 }
7231 
7232 namespace {
7233 
7234 /// AsmOperandInfo - This contains information for each constraint that we are
7235 /// lowering.
7236 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7237 public:
7238   /// CallOperand - If this is the result output operand or a clobber
7239   /// this is null, otherwise it is the incoming operand to the CallInst.
7240   /// This gets modified as the asm is processed.
7241   SDValue CallOperand;
7242 
7243   /// AssignedRegs - If this is a register or register class operand, this
7244   /// contains the set of register corresponding to the operand.
7245   RegsForValue AssignedRegs;
7246 
7247   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7248     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7249   }
7250 
7251   /// Whether or not this operand accesses memory
7252   bool hasMemory(const TargetLowering &TLI) const {
7253     // Indirect operand accesses access memory.
7254     if (isIndirect)
7255       return true;
7256 
7257     for (const auto &Code : Codes)
7258       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7259         return true;
7260 
7261     return false;
7262   }
7263 
7264   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7265   /// corresponds to.  If there is no Value* for this operand, it returns
7266   /// MVT::Other.
7267   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7268                            const DataLayout &DL) const {
7269     if (!CallOperandVal) return MVT::Other;
7270 
7271     if (isa<BasicBlock>(CallOperandVal))
7272       return TLI.getPointerTy(DL);
7273 
7274     llvm::Type *OpTy = CallOperandVal->getType();
7275 
7276     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7277     // If this is an indirect operand, the operand is a pointer to the
7278     // accessed type.
7279     if (isIndirect) {
7280       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7281       if (!PtrTy)
7282         report_fatal_error("Indirect operand for inline asm not a pointer!");
7283       OpTy = PtrTy->getElementType();
7284     }
7285 
7286     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7287     if (StructType *STy = dyn_cast<StructType>(OpTy))
7288       if (STy->getNumElements() == 1)
7289         OpTy = STy->getElementType(0);
7290 
7291     // If OpTy is not a single value, it may be a struct/union that we
7292     // can tile with integers.
7293     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7294       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7295       switch (BitSize) {
7296       default: break;
7297       case 1:
7298       case 8:
7299       case 16:
7300       case 32:
7301       case 64:
7302       case 128:
7303         OpTy = IntegerType::get(Context, BitSize);
7304         break;
7305       }
7306     }
7307 
7308     return TLI.getValueType(DL, OpTy, true);
7309   }
7310 };
7311 
7312 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7313 
7314 } // end anonymous namespace
7315 
7316 /// Make sure that the output operand \p OpInfo and its corresponding input
7317 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7318 /// out).
7319 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7320                                SDISelAsmOperandInfo &MatchingOpInfo,
7321                                SelectionDAG &DAG) {
7322   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7323     return;
7324 
7325   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7326   const auto &TLI = DAG.getTargetLoweringInfo();
7327 
7328   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7329       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7330                                        OpInfo.ConstraintVT);
7331   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7332       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7333                                        MatchingOpInfo.ConstraintVT);
7334   if ((OpInfo.ConstraintVT.isInteger() !=
7335        MatchingOpInfo.ConstraintVT.isInteger()) ||
7336       (MatchRC.second != InputRC.second)) {
7337     // FIXME: error out in a more elegant fashion
7338     report_fatal_error("Unsupported asm: input constraint"
7339                        " with a matching output constraint of"
7340                        " incompatible type!");
7341   }
7342   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7343 }
7344 
7345 /// Get a direct memory input to behave well as an indirect operand.
7346 /// This may introduce stores, hence the need for a \p Chain.
7347 /// \return The (possibly updated) chain.
7348 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7349                                         SDISelAsmOperandInfo &OpInfo,
7350                                         SelectionDAG &DAG) {
7351   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7352 
7353   // If we don't have an indirect input, put it in the constpool if we can,
7354   // otherwise spill it to a stack slot.
7355   // TODO: This isn't quite right. We need to handle these according to
7356   // the addressing mode that the constraint wants. Also, this may take
7357   // an additional register for the computation and we don't want that
7358   // either.
7359 
7360   // If the operand is a float, integer, or vector constant, spill to a
7361   // constant pool entry to get its address.
7362   const Value *OpVal = OpInfo.CallOperandVal;
7363   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7364       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7365     OpInfo.CallOperand = DAG.getConstantPool(
7366         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7367     return Chain;
7368   }
7369 
7370   // Otherwise, create a stack slot and emit a store to it before the asm.
7371   Type *Ty = OpVal->getType();
7372   auto &DL = DAG.getDataLayout();
7373   uint64_t TySize = DL.getTypeAllocSize(Ty);
7374   unsigned Align = DL.getPrefTypeAlignment(Ty);
7375   MachineFunction &MF = DAG.getMachineFunction();
7376   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7377   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7378   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7379                        MachinePointerInfo::getFixedStack(MF, SSFI));
7380   OpInfo.CallOperand = StackSlot;
7381 
7382   return Chain;
7383 }
7384 
7385 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7386 /// specified operand.  We prefer to assign virtual registers, to allow the
7387 /// register allocator to handle the assignment process.  However, if the asm
7388 /// uses features that we can't model on machineinstrs, we have SDISel do the
7389 /// allocation.  This produces generally horrible, but correct, code.
7390 ///
7391 ///   OpInfo describes the operand
7392 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7393 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7394                                  SDISelAsmOperandInfo &OpInfo,
7395                                  SDISelAsmOperandInfo &RefOpInfo) {
7396   LLVMContext &Context = *DAG.getContext();
7397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7398 
7399   MachineFunction &MF = DAG.getMachineFunction();
7400   SmallVector<unsigned, 4> Regs;
7401   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7402 
7403   // No work to do for memory operations.
7404   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7405     return;
7406 
7407   // If this is a constraint for a single physreg, or a constraint for a
7408   // register class, find it.
7409   unsigned AssignedReg;
7410   const TargetRegisterClass *RC;
7411   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7412       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7413   // RC is unset only on failure. Return immediately.
7414   if (!RC)
7415     return;
7416 
7417   // Get the actual register value type.  This is important, because the user
7418   // may have asked for (e.g.) the AX register in i32 type.  We need to
7419   // remember that AX is actually i16 to get the right extension.
7420   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7421 
7422   if (OpInfo.ConstraintVT != MVT::Other) {
7423     // If this is an FP operand in an integer register (or visa versa), or more
7424     // generally if the operand value disagrees with the register class we plan
7425     // to stick it in, fix the operand type.
7426     //
7427     // If this is an input value, the bitcast to the new type is done now.
7428     // Bitcast for output value is done at the end of visitInlineAsm().
7429     if ((OpInfo.Type == InlineAsm::isOutput ||
7430          OpInfo.Type == InlineAsm::isInput) &&
7431         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7432       // Try to convert to the first EVT that the reg class contains.  If the
7433       // types are identical size, use a bitcast to convert (e.g. two differing
7434       // vector types).  Note: output bitcast is done at the end of
7435       // visitInlineAsm().
7436       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7437         // Exclude indirect inputs while they are unsupported because the code
7438         // to perform the load is missing and thus OpInfo.CallOperand still
7439         // refers to the input address rather than the pointed-to value.
7440         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7441           OpInfo.CallOperand =
7442               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7443         OpInfo.ConstraintVT = RegVT;
7444         // If the operand is an FP value and we want it in integer registers,
7445         // use the corresponding integer type. This turns an f64 value into
7446         // i64, which can be passed with two i32 values on a 32-bit machine.
7447       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7448         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7449         if (OpInfo.Type == InlineAsm::isInput)
7450           OpInfo.CallOperand =
7451               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7452         OpInfo.ConstraintVT = VT;
7453       }
7454     }
7455   }
7456 
7457   // No need to allocate a matching input constraint since the constraint it's
7458   // matching to has already been allocated.
7459   if (OpInfo.isMatchingInputConstraint())
7460     return;
7461 
7462   EVT ValueVT = OpInfo.ConstraintVT;
7463   if (OpInfo.ConstraintVT == MVT::Other)
7464     ValueVT = RegVT;
7465 
7466   // Initialize NumRegs.
7467   unsigned NumRegs = 1;
7468   if (OpInfo.ConstraintVT != MVT::Other)
7469     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7470 
7471   // If this is a constraint for a specific physical register, like {r17},
7472   // assign it now.
7473 
7474   // If this associated to a specific register, initialize iterator to correct
7475   // place. If virtual, make sure we have enough registers
7476 
7477   // Initialize iterator if necessary
7478   TargetRegisterClass::iterator I = RC->begin();
7479   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7480 
7481   // Do not check for single registers.
7482   if (AssignedReg) {
7483       for (; *I != AssignedReg; ++I)
7484         assert(I != RC->end() && "AssignedReg should be member of RC");
7485   }
7486 
7487   for (; NumRegs; --NumRegs, ++I) {
7488     assert(I != RC->end() && "Ran out of registers to allocate!");
7489     auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC);
7490     Regs.push_back(R);
7491   }
7492 
7493   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7494 }
7495 
7496 static unsigned
7497 findMatchingInlineAsmOperand(unsigned OperandNo,
7498                              const std::vector<SDValue> &AsmNodeOperands) {
7499   // Scan until we find the definition we already emitted of this operand.
7500   unsigned CurOp = InlineAsm::Op_FirstOperand;
7501   for (; OperandNo; --OperandNo) {
7502     // Advance to the next operand.
7503     unsigned OpFlag =
7504         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7505     assert((InlineAsm::isRegDefKind(OpFlag) ||
7506             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7507             InlineAsm::isMemKind(OpFlag)) &&
7508            "Skipped past definitions?");
7509     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7510   }
7511   return CurOp;
7512 }
7513 
7514 namespace {
7515 
7516 class ExtraFlags {
7517   unsigned Flags = 0;
7518 
7519 public:
7520   explicit ExtraFlags(ImmutableCallSite CS) {
7521     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7522     if (IA->hasSideEffects())
7523       Flags |= InlineAsm::Extra_HasSideEffects;
7524     if (IA->isAlignStack())
7525       Flags |= InlineAsm::Extra_IsAlignStack;
7526     if (CS.isConvergent())
7527       Flags |= InlineAsm::Extra_IsConvergent;
7528     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7529   }
7530 
7531   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7532     // Ideally, we would only check against memory constraints.  However, the
7533     // meaning of an Other constraint can be target-specific and we can't easily
7534     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7535     // for Other constraints as well.
7536     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7537         OpInfo.ConstraintType == TargetLowering::C_Other) {
7538       if (OpInfo.Type == InlineAsm::isInput)
7539         Flags |= InlineAsm::Extra_MayLoad;
7540       else if (OpInfo.Type == InlineAsm::isOutput)
7541         Flags |= InlineAsm::Extra_MayStore;
7542       else if (OpInfo.Type == InlineAsm::isClobber)
7543         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7544     }
7545   }
7546 
7547   unsigned get() const { return Flags; }
7548 };
7549 
7550 } // end anonymous namespace
7551 
7552 /// visitInlineAsm - Handle a call to an InlineAsm object.
7553 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7554   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7555 
7556   /// ConstraintOperands - Information about all of the constraints.
7557   SDISelAsmOperandInfoVector ConstraintOperands;
7558 
7559   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7560   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7561       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7562 
7563   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7564   // AsmDialect, MayLoad, MayStore).
7565   bool HasSideEffect = IA->hasSideEffects();
7566   ExtraFlags ExtraInfo(CS);
7567 
7568   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7569   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7570   for (auto &T : TargetConstraints) {
7571     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7572     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7573 
7574     // Compute the value type for each operand.
7575     if (OpInfo.Type == InlineAsm::isInput ||
7576         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7577       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7578 
7579       // Process the call argument. BasicBlocks are labels, currently appearing
7580       // only in asm's.
7581       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7582         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7583       } else {
7584         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7585       }
7586 
7587       OpInfo.ConstraintVT =
7588           OpInfo
7589               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7590               .getSimpleVT();
7591     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7592       // The return value of the call is this value.  As such, there is no
7593       // corresponding argument.
7594       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7595       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7596         OpInfo.ConstraintVT = TLI.getSimpleValueType(
7597             DAG.getDataLayout(), STy->getElementType(ResNo));
7598       } else {
7599         assert(ResNo == 0 && "Asm only has one result!");
7600         OpInfo.ConstraintVT =
7601             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7602       }
7603       ++ResNo;
7604     } else {
7605       OpInfo.ConstraintVT = MVT::Other;
7606     }
7607 
7608     if (!HasSideEffect)
7609       HasSideEffect = OpInfo.hasMemory(TLI);
7610 
7611     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7612     // FIXME: Could we compute this on OpInfo rather than T?
7613 
7614     // Compute the constraint code and ConstraintType to use.
7615     TLI.ComputeConstraintToUse(T, SDValue());
7616 
7617     ExtraInfo.update(T);
7618   }
7619 
7620   // We won't need to flush pending loads if this asm doesn't touch
7621   // memory and is nonvolatile.
7622   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
7623 
7624   // Second pass over the constraints: compute which constraint option to use.
7625   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7626     // If this is an output operand with a matching input operand, look up the
7627     // matching input. If their types mismatch, e.g. one is an integer, the
7628     // other is floating point, or their sizes are different, flag it as an
7629     // error.
7630     if (OpInfo.hasMatchingInput()) {
7631       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7632       patchMatchingInput(OpInfo, Input, DAG);
7633     }
7634 
7635     // Compute the constraint code and ConstraintType to use.
7636     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7637 
7638     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7639         OpInfo.Type == InlineAsm::isClobber)
7640       continue;
7641 
7642     // If this is a memory input, and if the operand is not indirect, do what we
7643     // need to provide an address for the memory input.
7644     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7645         !OpInfo.isIndirect) {
7646       assert((OpInfo.isMultipleAlternative ||
7647               (OpInfo.Type == InlineAsm::isInput)) &&
7648              "Can only indirectify direct input operands!");
7649 
7650       // Memory operands really want the address of the value.
7651       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7652 
7653       // There is no longer a Value* corresponding to this operand.
7654       OpInfo.CallOperandVal = nullptr;
7655 
7656       // It is now an indirect operand.
7657       OpInfo.isIndirect = true;
7658     }
7659 
7660   }
7661 
7662   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7663   std::vector<SDValue> AsmNodeOperands;
7664   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7665   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7666       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7667 
7668   // If we have a !srcloc metadata node associated with it, we want to attach
7669   // this to the ultimately generated inline asm machineinstr.  To do this, we
7670   // pass in the third operand as this (potentially null) inline asm MDNode.
7671   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7672   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7673 
7674   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7675   // bits as operand 3.
7676   AsmNodeOperands.push_back(DAG.getTargetConstant(
7677       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7678 
7679   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
7680   // this, assign virtual and physical registers for inputs and otput.
7681   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7682     // Assign Registers.
7683     SDISelAsmOperandInfo &RefOpInfo =
7684         OpInfo.isMatchingInputConstraint()
7685             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7686             : OpInfo;
7687     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
7688 
7689     switch (OpInfo.Type) {
7690     case InlineAsm::isOutput:
7691       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7692           (OpInfo.ConstraintType == TargetLowering::C_Other &&
7693            OpInfo.isIndirect)) {
7694         unsigned ConstraintID =
7695             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7696         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7697                "Failed to convert memory constraint code to constraint id.");
7698 
7699         // Add information to the INLINEASM node to know about this output.
7700         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7701         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7702         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7703                                                         MVT::i32));
7704         AsmNodeOperands.push_back(OpInfo.CallOperand);
7705         break;
7706       } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
7707                   !OpInfo.isIndirect) ||
7708                  OpInfo.ConstraintType == TargetLowering::C_Register ||
7709                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
7710         // Otherwise, this outputs to a register (directly for C_Register /
7711         // C_RegisterClass, and a target-defined fashion for C_Other). Find a
7712         // register that we can use.
7713         if (OpInfo.AssignedRegs.Regs.empty()) {
7714           emitInlineAsmError(
7715               CS, "couldn't allocate output register for constraint '" +
7716                       Twine(OpInfo.ConstraintCode) + "'");
7717           return;
7718         }
7719 
7720         // Add information to the INLINEASM node to know that this register is
7721         // set.
7722         OpInfo.AssignedRegs.AddInlineAsmOperands(
7723             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
7724                                   : InlineAsm::Kind_RegDef,
7725             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7726       }
7727       break;
7728 
7729     case InlineAsm::isInput: {
7730       SDValue InOperandVal = OpInfo.CallOperand;
7731 
7732       if (OpInfo.isMatchingInputConstraint()) {
7733         // If this is required to match an output register we have already set,
7734         // just use its register.
7735         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7736                                                   AsmNodeOperands);
7737         unsigned OpFlag =
7738           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7739         if (InlineAsm::isRegDefKind(OpFlag) ||
7740             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7741           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7742           if (OpInfo.isIndirect) {
7743             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7744             emitInlineAsmError(CS, "inline asm not supported yet:"
7745                                    " don't know how to handle tied "
7746                                    "indirect register inputs");
7747             return;
7748           }
7749 
7750           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7751           SmallVector<unsigned, 4> Regs;
7752 
7753           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
7754             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
7755             MachineRegisterInfo &RegInfo =
7756                 DAG.getMachineFunction().getRegInfo();
7757             for (unsigned i = 0; i != NumRegs; ++i)
7758               Regs.push_back(RegInfo.createVirtualRegister(RC));
7759           } else {
7760             emitInlineAsmError(CS, "inline asm error: This value type register "
7761                                    "class is not natively supported!");
7762             return;
7763           }
7764 
7765           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7766 
7767           SDLoc dl = getCurSDLoc();
7768           // Use the produced MatchedRegs object to
7769           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7770                                     CS.getInstruction());
7771           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7772                                            true, OpInfo.getMatchedOperand(), dl,
7773                                            DAG, AsmNodeOperands);
7774           break;
7775         }
7776 
7777         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7778         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7779                "Unexpected number of operands");
7780         // Add information to the INLINEASM node to know about this input.
7781         // See InlineAsm.h isUseOperandTiedToDef.
7782         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7783         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7784                                                     OpInfo.getMatchedOperand());
7785         AsmNodeOperands.push_back(DAG.getTargetConstant(
7786             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7787         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7788         break;
7789       }
7790 
7791       // Treat indirect 'X' constraint as memory.
7792       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7793           OpInfo.isIndirect)
7794         OpInfo.ConstraintType = TargetLowering::C_Memory;
7795 
7796       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7797         std::vector<SDValue> Ops;
7798         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7799                                           Ops, DAG);
7800         if (Ops.empty()) {
7801           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7802                                      Twine(OpInfo.ConstraintCode) + "'");
7803           return;
7804         }
7805 
7806         // Add information to the INLINEASM node to know about this input.
7807         unsigned ResOpType =
7808           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7809         AsmNodeOperands.push_back(DAG.getTargetConstant(
7810             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7811         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7812         break;
7813       }
7814 
7815       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7816         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7817         assert(InOperandVal.getValueType() ==
7818                    TLI.getPointerTy(DAG.getDataLayout()) &&
7819                "Memory operands expect pointer values");
7820 
7821         unsigned ConstraintID =
7822             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7823         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7824                "Failed to convert memory constraint code to constraint id.");
7825 
7826         // Add information to the INLINEASM node to know about this input.
7827         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7828         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7829         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7830                                                         getCurSDLoc(),
7831                                                         MVT::i32));
7832         AsmNodeOperands.push_back(InOperandVal);
7833         break;
7834       }
7835 
7836       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7837               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7838              "Unknown constraint type!");
7839 
7840       // TODO: Support this.
7841       if (OpInfo.isIndirect) {
7842         emitInlineAsmError(
7843             CS, "Don't know how to handle indirect register inputs yet "
7844                 "for constraint '" +
7845                     Twine(OpInfo.ConstraintCode) + "'");
7846         return;
7847       }
7848 
7849       // Copy the input into the appropriate registers.
7850       if (OpInfo.AssignedRegs.Regs.empty()) {
7851         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7852                                    Twine(OpInfo.ConstraintCode) + "'");
7853         return;
7854       }
7855 
7856       SDLoc dl = getCurSDLoc();
7857 
7858       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7859                                         Chain, &Flag, CS.getInstruction());
7860 
7861       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7862                                                dl, DAG, AsmNodeOperands);
7863       break;
7864     }
7865     case InlineAsm::isClobber:
7866       // Add the clobbered value to the operand list, so that the register
7867       // allocator is aware that the physreg got clobbered.
7868       if (!OpInfo.AssignedRegs.Regs.empty())
7869         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7870                                                  false, 0, getCurSDLoc(), DAG,
7871                                                  AsmNodeOperands);
7872       break;
7873     }
7874   }
7875 
7876   // Finish up input operands.  Set the input chain and add the flag last.
7877   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7878   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7879 
7880   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7881                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7882   Flag = Chain.getValue(1);
7883 
7884   // Do additional work to generate outputs.
7885 
7886   SmallVector<EVT, 1> ResultVTs;
7887   SmallVector<SDValue, 1> ResultValues;
7888   SmallVector<SDValue, 8> OutChains;
7889 
7890   llvm::Type *CSResultType = CS.getType();
7891   ArrayRef<Type *> ResultTypes;
7892   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
7893     ResultTypes = StructResult->elements();
7894   else if (!CSResultType->isVoidTy())
7895     ResultTypes = makeArrayRef(CSResultType);
7896 
7897   auto CurResultType = ResultTypes.begin();
7898   auto handleRegAssign = [&](SDValue V) {
7899     assert(CurResultType != ResultTypes.end() && "Unexpected value");
7900     assert((*CurResultType)->isSized() && "Unexpected unsized type");
7901     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
7902     ++CurResultType;
7903     // If the type of the inline asm call site return value is different but has
7904     // same size as the type of the asm output bitcast it.  One example of this
7905     // is for vectors with different width / number of elements.  This can
7906     // happen for register classes that can contain multiple different value
7907     // types.  The preg or vreg allocated may not have the same VT as was
7908     // expected.
7909     //
7910     // This can also happen for a return value that disagrees with the register
7911     // class it is put in, eg. a double in a general-purpose register on a
7912     // 32-bit machine.
7913     if (ResultVT != V.getValueType() &&
7914         ResultVT.getSizeInBits() == V.getValueSizeInBits())
7915       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
7916     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
7917              V.getValueType().isInteger()) {
7918       // If a result value was tied to an input value, the computed result
7919       // may have a wider width than the expected result.  Extract the
7920       // relevant portion.
7921       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
7922     }
7923     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
7924     ResultVTs.push_back(ResultVT);
7925     ResultValues.push_back(V);
7926   };
7927 
7928   // Deal with output operands.
7929   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7930     if (OpInfo.Type == InlineAsm::isOutput) {
7931       SDValue Val;
7932       // Skip trivial output operands.
7933       if (OpInfo.AssignedRegs.Regs.empty())
7934         continue;
7935 
7936       switch (OpInfo.ConstraintType) {
7937       case TargetLowering::C_Register:
7938       case TargetLowering::C_RegisterClass:
7939         Val = OpInfo.AssignedRegs.getCopyFromRegs(
7940             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
7941         break;
7942       case TargetLowering::C_Other:
7943         Val = TLI.LowerAsmOutputForConstraint(Chain, &Flag, getCurSDLoc(),
7944                                               OpInfo, DAG);
7945         break;
7946       case TargetLowering::C_Memory:
7947         break; // Already handled.
7948       case TargetLowering::C_Unknown:
7949         assert(false && "Unexpected unknown constraint");
7950       }
7951 
7952       // Indirect output manifest as stores. Record output chains.
7953       if (OpInfo.isIndirect) {
7954 
7955         const Value *Ptr = OpInfo.CallOperandVal;
7956         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
7957         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
7958                                      MachinePointerInfo(Ptr));
7959         OutChains.push_back(Store);
7960       } else {
7961         // generate CopyFromRegs to associated registers.
7962         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7963         if (Val.getOpcode() == ISD::MERGE_VALUES) {
7964           for (const SDValue &V : Val->op_values())
7965             handleRegAssign(V);
7966         } else
7967           handleRegAssign(Val);
7968       }
7969     }
7970   }
7971 
7972   // Set results.
7973   if (!ResultValues.empty()) {
7974     assert(CurResultType == ResultTypes.end() &&
7975            "Mismatch in number of ResultTypes");
7976     assert(ResultValues.size() == ResultTypes.size() &&
7977            "Mismatch in number of output operands in asm result");
7978 
7979     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
7980                             DAG.getVTList(ResultVTs), ResultValues);
7981     setValue(CS.getInstruction(), V);
7982   }
7983 
7984   // Collect store chains.
7985   if (!OutChains.empty())
7986     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7987 
7988   // Only Update Root if inline assembly has a memory effect.
7989   if (ResultValues.empty() || HasSideEffect || !OutChains.empty())
7990     DAG.setRoot(Chain);
7991 }
7992 
7993 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7994                                              const Twine &Message) {
7995   LLVMContext &Ctx = *DAG.getContext();
7996   Ctx.emitError(CS.getInstruction(), Message);
7997 
7998   // Make sure we leave the DAG in a valid state
7999   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8000   SmallVector<EVT, 1> ValueVTs;
8001   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8002 
8003   if (ValueVTs.empty())
8004     return;
8005 
8006   SmallVector<SDValue, 1> Ops;
8007   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8008     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8009 
8010   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8011 }
8012 
8013 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8014   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8015                           MVT::Other, getRoot(),
8016                           getValue(I.getArgOperand(0)),
8017                           DAG.getSrcValue(I.getArgOperand(0))));
8018 }
8019 
8020 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8021   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8022   const DataLayout &DL = DAG.getDataLayout();
8023   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
8024                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
8025                            DAG.getSrcValue(I.getOperand(0)),
8026                            DL.getABITypeAlignment(I.getType()));
8027   setValue(&I, V);
8028   DAG.setRoot(V.getValue(1));
8029 }
8030 
8031 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8032   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8033                           MVT::Other, getRoot(),
8034                           getValue(I.getArgOperand(0)),
8035                           DAG.getSrcValue(I.getArgOperand(0))));
8036 }
8037 
8038 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8039   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8040                           MVT::Other, getRoot(),
8041                           getValue(I.getArgOperand(0)),
8042                           getValue(I.getArgOperand(1)),
8043                           DAG.getSrcValue(I.getArgOperand(0)),
8044                           DAG.getSrcValue(I.getArgOperand(1))));
8045 }
8046 
8047 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8048                                                     const Instruction &I,
8049                                                     SDValue Op) {
8050   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8051   if (!Range)
8052     return Op;
8053 
8054   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8055   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
8056     return Op;
8057 
8058   APInt Lo = CR.getUnsignedMin();
8059   if (!Lo.isMinValue())
8060     return Op;
8061 
8062   APInt Hi = CR.getUnsignedMax();
8063   unsigned Bits = std::max(Hi.getActiveBits(),
8064                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8065 
8066   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8067 
8068   SDLoc SL = getCurSDLoc();
8069 
8070   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8071                              DAG.getValueType(SmallVT));
8072   unsigned NumVals = Op.getNode()->getNumValues();
8073   if (NumVals == 1)
8074     return ZExt;
8075 
8076   SmallVector<SDValue, 4> Ops;
8077 
8078   Ops.push_back(ZExt);
8079   for (unsigned I = 1; I != NumVals; ++I)
8080     Ops.push_back(Op.getValue(I));
8081 
8082   return DAG.getMergeValues(Ops, SL);
8083 }
8084 
8085 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8086 /// the call being lowered.
8087 ///
8088 /// This is a helper for lowering intrinsics that follow a target calling
8089 /// convention or require stack pointer adjustment. Only a subset of the
8090 /// intrinsic's operands need to participate in the calling convention.
8091 void SelectionDAGBuilder::populateCallLoweringInfo(
8092     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
8093     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8094     bool IsPatchPoint) {
8095   TargetLowering::ArgListTy Args;
8096   Args.reserve(NumArgs);
8097 
8098   // Populate the argument list.
8099   // Attributes for args start at offset 1, after the return attribute.
8100   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8101        ArgI != ArgE; ++ArgI) {
8102     const Value *V = CS->getOperand(ArgI);
8103 
8104     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8105 
8106     TargetLowering::ArgListEntry Entry;
8107     Entry.Node = getValue(V);
8108     Entry.Ty = V->getType();
8109     Entry.setAttributes(&CS, ArgI);
8110     Args.push_back(Entry);
8111   }
8112 
8113   CLI.setDebugLoc(getCurSDLoc())
8114       .setChain(getRoot())
8115       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
8116       .setDiscardResult(CS->use_empty())
8117       .setIsPatchPoint(IsPatchPoint);
8118 }
8119 
8120 /// Add a stack map intrinsic call's live variable operands to a stackmap
8121 /// or patchpoint target node's operand list.
8122 ///
8123 /// Constants are converted to TargetConstants purely as an optimization to
8124 /// avoid constant materialization and register allocation.
8125 ///
8126 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8127 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8128 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8129 /// address materialization and register allocation, but may also be required
8130 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8131 /// alloca in the entry block, then the runtime may assume that the alloca's
8132 /// StackMap location can be read immediately after compilation and that the
8133 /// location is valid at any point during execution (this is similar to the
8134 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8135 /// only available in a register, then the runtime would need to trap when
8136 /// execution reaches the StackMap in order to read the alloca's location.
8137 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8138                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8139                                 SelectionDAGBuilder &Builder) {
8140   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8141     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8142     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8143       Ops.push_back(
8144         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8145       Ops.push_back(
8146         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8147     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8148       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8149       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8150           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8151     } else
8152       Ops.push_back(OpVal);
8153   }
8154 }
8155 
8156 /// Lower llvm.experimental.stackmap directly to its target opcode.
8157 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8158   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8159   //                                  [live variables...])
8160 
8161   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8162 
8163   SDValue Chain, InFlag, Callee, NullPtr;
8164   SmallVector<SDValue, 32> Ops;
8165 
8166   SDLoc DL = getCurSDLoc();
8167   Callee = getValue(CI.getCalledValue());
8168   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8169 
8170   // The stackmap intrinsic only records the live variables (the arguemnts
8171   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8172   // intrinsic, this won't be lowered to a function call. This means we don't
8173   // have to worry about calling conventions and target specific lowering code.
8174   // Instead we perform the call lowering right here.
8175   //
8176   // chain, flag = CALLSEQ_START(chain, 0, 0)
8177   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8178   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8179   //
8180   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8181   InFlag = Chain.getValue(1);
8182 
8183   // Add the <id> and <numBytes> constants.
8184   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8185   Ops.push_back(DAG.getTargetConstant(
8186                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8187   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8188   Ops.push_back(DAG.getTargetConstant(
8189                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8190                   MVT::i32));
8191 
8192   // Push live variables for the stack map.
8193   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8194 
8195   // We are not pushing any register mask info here on the operands list,
8196   // because the stackmap doesn't clobber anything.
8197 
8198   // Push the chain and the glue flag.
8199   Ops.push_back(Chain);
8200   Ops.push_back(InFlag);
8201 
8202   // Create the STACKMAP node.
8203   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8204   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8205   Chain = SDValue(SM, 0);
8206   InFlag = Chain.getValue(1);
8207 
8208   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8209 
8210   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8211 
8212   // Set the root to the target-lowered call chain.
8213   DAG.setRoot(Chain);
8214 
8215   // Inform the Frame Information that we have a stackmap in this function.
8216   FuncInfo.MF->getFrameInfo().setHasStackMap();
8217 }
8218 
8219 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8220 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8221                                           const BasicBlock *EHPadBB) {
8222   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8223   //                                                 i32 <numBytes>,
8224   //                                                 i8* <target>,
8225   //                                                 i32 <numArgs>,
8226   //                                                 [Args...],
8227   //                                                 [live variables...])
8228 
8229   CallingConv::ID CC = CS.getCallingConv();
8230   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8231   bool HasDef = !CS->getType()->isVoidTy();
8232   SDLoc dl = getCurSDLoc();
8233   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8234 
8235   // Handle immediate and symbolic callees.
8236   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8237     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8238                                    /*isTarget=*/true);
8239   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8240     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8241                                          SDLoc(SymbolicCallee),
8242                                          SymbolicCallee->getValueType(0));
8243 
8244   // Get the real number of arguments participating in the call <numArgs>
8245   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8246   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8247 
8248   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8249   // Intrinsics include all meta-operands up to but not including CC.
8250   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8251   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8252          "Not enough arguments provided to the patchpoint intrinsic");
8253 
8254   // For AnyRegCC the arguments are lowered later on manually.
8255   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8256   Type *ReturnTy =
8257     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8258 
8259   TargetLowering::CallLoweringInfo CLI(DAG);
8260   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
8261                            true);
8262   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8263 
8264   SDNode *CallEnd = Result.second.getNode();
8265   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8266     CallEnd = CallEnd->getOperand(0).getNode();
8267 
8268   /// Get a call instruction from the call sequence chain.
8269   /// Tail calls are not allowed.
8270   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8271          "Expected a callseq node.");
8272   SDNode *Call = CallEnd->getOperand(0).getNode();
8273   bool HasGlue = Call->getGluedNode();
8274 
8275   // Replace the target specific call node with the patchable intrinsic.
8276   SmallVector<SDValue, 8> Ops;
8277 
8278   // Add the <id> and <numBytes> constants.
8279   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8280   Ops.push_back(DAG.getTargetConstant(
8281                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8282   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8283   Ops.push_back(DAG.getTargetConstant(
8284                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8285                   MVT::i32));
8286 
8287   // Add the callee.
8288   Ops.push_back(Callee);
8289 
8290   // Adjust <numArgs> to account for any arguments that have been passed on the
8291   // stack instead.
8292   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8293   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8294   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8295   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8296 
8297   // Add the calling convention
8298   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8299 
8300   // Add the arguments we omitted previously. The register allocator should
8301   // place these in any free register.
8302   if (IsAnyRegCC)
8303     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8304       Ops.push_back(getValue(CS.getArgument(i)));
8305 
8306   // Push the arguments from the call instruction up to the register mask.
8307   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8308   Ops.append(Call->op_begin() + 2, e);
8309 
8310   // Push live variables for the stack map.
8311   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8312 
8313   // Push the register mask info.
8314   if (HasGlue)
8315     Ops.push_back(*(Call->op_end()-2));
8316   else
8317     Ops.push_back(*(Call->op_end()-1));
8318 
8319   // Push the chain (this is originally the first operand of the call, but
8320   // becomes now the last or second to last operand).
8321   Ops.push_back(*(Call->op_begin()));
8322 
8323   // Push the glue flag (last operand).
8324   if (HasGlue)
8325     Ops.push_back(*(Call->op_end()-1));
8326 
8327   SDVTList NodeTys;
8328   if (IsAnyRegCC && HasDef) {
8329     // Create the return types based on the intrinsic definition
8330     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8331     SmallVector<EVT, 3> ValueVTs;
8332     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8333     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8334 
8335     // There is always a chain and a glue type at the end
8336     ValueVTs.push_back(MVT::Other);
8337     ValueVTs.push_back(MVT::Glue);
8338     NodeTys = DAG.getVTList(ValueVTs);
8339   } else
8340     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8341 
8342   // Replace the target specific call node with a PATCHPOINT node.
8343   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8344                                          dl, NodeTys, Ops);
8345 
8346   // Update the NodeMap.
8347   if (HasDef) {
8348     if (IsAnyRegCC)
8349       setValue(CS.getInstruction(), SDValue(MN, 0));
8350     else
8351       setValue(CS.getInstruction(), Result.first);
8352   }
8353 
8354   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8355   // call sequence. Furthermore the location of the chain and glue can change
8356   // when the AnyReg calling convention is used and the intrinsic returns a
8357   // value.
8358   if (IsAnyRegCC && HasDef) {
8359     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8360     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8361     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8362   } else
8363     DAG.ReplaceAllUsesWith(Call, MN);
8364   DAG.DeleteNode(Call);
8365 
8366   // Inform the Frame Information that we have a patchpoint in this function.
8367   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8368 }
8369 
8370 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8371                                             unsigned Intrinsic) {
8372   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8373   SDValue Op1 = getValue(I.getArgOperand(0));
8374   SDValue Op2;
8375   if (I.getNumArgOperands() > 1)
8376     Op2 = getValue(I.getArgOperand(1));
8377   SDLoc dl = getCurSDLoc();
8378   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8379   SDValue Res;
8380   FastMathFlags FMF;
8381   if (isa<FPMathOperator>(I))
8382     FMF = I.getFastMathFlags();
8383 
8384   switch (Intrinsic) {
8385   case Intrinsic::experimental_vector_reduce_fadd:
8386     if (FMF.isFast())
8387       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8388     else
8389       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8390     break;
8391   case Intrinsic::experimental_vector_reduce_fmul:
8392     if (FMF.isFast())
8393       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8394     else
8395       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8396     break;
8397   case Intrinsic::experimental_vector_reduce_add:
8398     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8399     break;
8400   case Intrinsic::experimental_vector_reduce_mul:
8401     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8402     break;
8403   case Intrinsic::experimental_vector_reduce_and:
8404     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8405     break;
8406   case Intrinsic::experimental_vector_reduce_or:
8407     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8408     break;
8409   case Intrinsic::experimental_vector_reduce_xor:
8410     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8411     break;
8412   case Intrinsic::experimental_vector_reduce_smax:
8413     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8414     break;
8415   case Intrinsic::experimental_vector_reduce_smin:
8416     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8417     break;
8418   case Intrinsic::experimental_vector_reduce_umax:
8419     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8420     break;
8421   case Intrinsic::experimental_vector_reduce_umin:
8422     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8423     break;
8424   case Intrinsic::experimental_vector_reduce_fmax:
8425     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8426     break;
8427   case Intrinsic::experimental_vector_reduce_fmin:
8428     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8429     break;
8430   default:
8431     llvm_unreachable("Unhandled vector reduce intrinsic");
8432   }
8433   setValue(&I, Res);
8434 }
8435 
8436 /// Returns an AttributeList representing the attributes applied to the return
8437 /// value of the given call.
8438 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8439   SmallVector<Attribute::AttrKind, 2> Attrs;
8440   if (CLI.RetSExt)
8441     Attrs.push_back(Attribute::SExt);
8442   if (CLI.RetZExt)
8443     Attrs.push_back(Attribute::ZExt);
8444   if (CLI.IsInReg)
8445     Attrs.push_back(Attribute::InReg);
8446 
8447   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8448                             Attrs);
8449 }
8450 
8451 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8452 /// implementation, which just calls LowerCall.
8453 /// FIXME: When all targets are
8454 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8455 std::pair<SDValue, SDValue>
8456 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8457   // Handle the incoming return values from the call.
8458   CLI.Ins.clear();
8459   Type *OrigRetTy = CLI.RetTy;
8460   SmallVector<EVT, 4> RetTys;
8461   SmallVector<uint64_t, 4> Offsets;
8462   auto &DL = CLI.DAG.getDataLayout();
8463   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8464 
8465   if (CLI.IsPostTypeLegalization) {
8466     // If we are lowering a libcall after legalization, split the return type.
8467     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8468     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8469     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8470       EVT RetVT = OldRetTys[i];
8471       uint64_t Offset = OldOffsets[i];
8472       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8473       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8474       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8475       RetTys.append(NumRegs, RegisterVT);
8476       for (unsigned j = 0; j != NumRegs; ++j)
8477         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8478     }
8479   }
8480 
8481   SmallVector<ISD::OutputArg, 4> Outs;
8482   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8483 
8484   bool CanLowerReturn =
8485       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8486                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8487 
8488   SDValue DemoteStackSlot;
8489   int DemoteStackIdx = -100;
8490   if (!CanLowerReturn) {
8491     // FIXME: equivalent assert?
8492     // assert(!CS.hasInAllocaArgument() &&
8493     //        "sret demotion is incompatible with inalloca");
8494     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8495     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8496     MachineFunction &MF = CLI.DAG.getMachineFunction();
8497     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8498     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8499                                               DL.getAllocaAddrSpace());
8500 
8501     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8502     ArgListEntry Entry;
8503     Entry.Node = DemoteStackSlot;
8504     Entry.Ty = StackSlotPtrType;
8505     Entry.IsSExt = false;
8506     Entry.IsZExt = false;
8507     Entry.IsInReg = false;
8508     Entry.IsSRet = true;
8509     Entry.IsNest = false;
8510     Entry.IsByVal = false;
8511     Entry.IsReturned = false;
8512     Entry.IsSwiftSelf = false;
8513     Entry.IsSwiftError = false;
8514     Entry.Alignment = Align;
8515     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8516     CLI.NumFixedArgs += 1;
8517     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8518 
8519     // sret demotion isn't compatible with tail-calls, since the sret argument
8520     // points into the callers stack frame.
8521     CLI.IsTailCall = false;
8522   } else {
8523     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8524       EVT VT = RetTys[I];
8525       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8526                                                      CLI.CallConv, VT);
8527       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8528                                                        CLI.CallConv, VT);
8529       for (unsigned i = 0; i != NumRegs; ++i) {
8530         ISD::InputArg MyFlags;
8531         MyFlags.VT = RegisterVT;
8532         MyFlags.ArgVT = VT;
8533         MyFlags.Used = CLI.IsReturnValueUsed;
8534         if (CLI.RetSExt)
8535           MyFlags.Flags.setSExt();
8536         if (CLI.RetZExt)
8537           MyFlags.Flags.setZExt();
8538         if (CLI.IsInReg)
8539           MyFlags.Flags.setInReg();
8540         CLI.Ins.push_back(MyFlags);
8541       }
8542     }
8543   }
8544 
8545   // We push in swifterror return as the last element of CLI.Ins.
8546   ArgListTy &Args = CLI.getArgs();
8547   if (supportSwiftError()) {
8548     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8549       if (Args[i].IsSwiftError) {
8550         ISD::InputArg MyFlags;
8551         MyFlags.VT = getPointerTy(DL);
8552         MyFlags.ArgVT = EVT(getPointerTy(DL));
8553         MyFlags.Flags.setSwiftError();
8554         CLI.Ins.push_back(MyFlags);
8555       }
8556     }
8557   }
8558 
8559   // Handle all of the outgoing arguments.
8560   CLI.Outs.clear();
8561   CLI.OutVals.clear();
8562   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8563     SmallVector<EVT, 4> ValueVTs;
8564     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8565     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8566     Type *FinalType = Args[i].Ty;
8567     if (Args[i].IsByVal)
8568       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8569     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8570         FinalType, CLI.CallConv, CLI.IsVarArg);
8571     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8572          ++Value) {
8573       EVT VT = ValueVTs[Value];
8574       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8575       SDValue Op = SDValue(Args[i].Node.getNode(),
8576                            Args[i].Node.getResNo() + Value);
8577       ISD::ArgFlagsTy Flags;
8578 
8579       // Certain targets (such as MIPS), may have a different ABI alignment
8580       // for a type depending on the context. Give the target a chance to
8581       // specify the alignment it wants.
8582       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8583 
8584       if (Args[i].IsZExt)
8585         Flags.setZExt();
8586       if (Args[i].IsSExt)
8587         Flags.setSExt();
8588       if (Args[i].IsInReg) {
8589         // If we are using vectorcall calling convention, a structure that is
8590         // passed InReg - is surely an HVA
8591         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8592             isa<StructType>(FinalType)) {
8593           // The first value of a structure is marked
8594           if (0 == Value)
8595             Flags.setHvaStart();
8596           Flags.setHva();
8597         }
8598         // Set InReg Flag
8599         Flags.setInReg();
8600       }
8601       if (Args[i].IsSRet)
8602         Flags.setSRet();
8603       if (Args[i].IsSwiftSelf)
8604         Flags.setSwiftSelf();
8605       if (Args[i].IsSwiftError)
8606         Flags.setSwiftError();
8607       if (Args[i].IsByVal)
8608         Flags.setByVal();
8609       if (Args[i].IsInAlloca) {
8610         Flags.setInAlloca();
8611         // Set the byval flag for CCAssignFn callbacks that don't know about
8612         // inalloca.  This way we can know how many bytes we should've allocated
8613         // and how many bytes a callee cleanup function will pop.  If we port
8614         // inalloca to more targets, we'll have to add custom inalloca handling
8615         // in the various CC lowering callbacks.
8616         Flags.setByVal();
8617       }
8618       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8619         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8620         Type *ElementTy = Ty->getElementType();
8621         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8622         // For ByVal, alignment should come from FE.  BE will guess if this
8623         // info is not there but there are cases it cannot get right.
8624         unsigned FrameAlign;
8625         if (Args[i].Alignment)
8626           FrameAlign = Args[i].Alignment;
8627         else
8628           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8629         Flags.setByValAlign(FrameAlign);
8630       }
8631       if (Args[i].IsNest)
8632         Flags.setNest();
8633       if (NeedsRegBlock)
8634         Flags.setInConsecutiveRegs();
8635       Flags.setOrigAlign(OriginalAlignment);
8636 
8637       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8638                                                  CLI.CallConv, VT);
8639       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8640                                                         CLI.CallConv, VT);
8641       SmallVector<SDValue, 4> Parts(NumParts);
8642       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8643 
8644       if (Args[i].IsSExt)
8645         ExtendKind = ISD::SIGN_EXTEND;
8646       else if (Args[i].IsZExt)
8647         ExtendKind = ISD::ZERO_EXTEND;
8648 
8649       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8650       // for now.
8651       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8652           CanLowerReturn) {
8653         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8654                "unexpected use of 'returned'");
8655         // Before passing 'returned' to the target lowering code, ensure that
8656         // either the register MVT and the actual EVT are the same size or that
8657         // the return value and argument are extended in the same way; in these
8658         // cases it's safe to pass the argument register value unchanged as the
8659         // return register value (although it's at the target's option whether
8660         // to do so)
8661         // TODO: allow code generation to take advantage of partially preserved
8662         // registers rather than clobbering the entire register when the
8663         // parameter extension method is not compatible with the return
8664         // extension method
8665         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8666             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8667              CLI.RetZExt == Args[i].IsZExt))
8668           Flags.setReturned();
8669       }
8670 
8671       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8672                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
8673 
8674       for (unsigned j = 0; j != NumParts; ++j) {
8675         // if it isn't first piece, alignment must be 1
8676         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8677                                i < CLI.NumFixedArgs,
8678                                i, j*Parts[j].getValueType().getStoreSize());
8679         if (NumParts > 1 && j == 0)
8680           MyFlags.Flags.setSplit();
8681         else if (j != 0) {
8682           MyFlags.Flags.setOrigAlign(1);
8683           if (j == NumParts - 1)
8684             MyFlags.Flags.setSplitEnd();
8685         }
8686 
8687         CLI.Outs.push_back(MyFlags);
8688         CLI.OutVals.push_back(Parts[j]);
8689       }
8690 
8691       if (NeedsRegBlock && Value == NumValues - 1)
8692         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8693     }
8694   }
8695 
8696   SmallVector<SDValue, 4> InVals;
8697   CLI.Chain = LowerCall(CLI, InVals);
8698 
8699   // Update CLI.InVals to use outside of this function.
8700   CLI.InVals = InVals;
8701 
8702   // Verify that the target's LowerCall behaved as expected.
8703   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8704          "LowerCall didn't return a valid chain!");
8705   assert((!CLI.IsTailCall || InVals.empty()) &&
8706          "LowerCall emitted a return value for a tail call!");
8707   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8708          "LowerCall didn't emit the correct number of values!");
8709 
8710   // For a tail call, the return value is merely live-out and there aren't
8711   // any nodes in the DAG representing it. Return a special value to
8712   // indicate that a tail call has been emitted and no more Instructions
8713   // should be processed in the current block.
8714   if (CLI.IsTailCall) {
8715     CLI.DAG.setRoot(CLI.Chain);
8716     return std::make_pair(SDValue(), SDValue());
8717   }
8718 
8719 #ifndef NDEBUG
8720   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8721     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8722     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8723            "LowerCall emitted a value with the wrong type!");
8724   }
8725 #endif
8726 
8727   SmallVector<SDValue, 4> ReturnValues;
8728   if (!CanLowerReturn) {
8729     // The instruction result is the result of loading from the
8730     // hidden sret parameter.
8731     SmallVector<EVT, 1> PVTs;
8732     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8733 
8734     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8735     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8736     EVT PtrVT = PVTs[0];
8737 
8738     unsigned NumValues = RetTys.size();
8739     ReturnValues.resize(NumValues);
8740     SmallVector<SDValue, 4> Chains(NumValues);
8741 
8742     // An aggregate return value cannot wrap around the address space, so
8743     // offsets to its parts don't wrap either.
8744     SDNodeFlags Flags;
8745     Flags.setNoUnsignedWrap(true);
8746 
8747     for (unsigned i = 0; i < NumValues; ++i) {
8748       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8749                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8750                                                         PtrVT), Flags);
8751       SDValue L = CLI.DAG.getLoad(
8752           RetTys[i], CLI.DL, CLI.Chain, Add,
8753           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8754                                             DemoteStackIdx, Offsets[i]),
8755           /* Alignment = */ 1);
8756       ReturnValues[i] = L;
8757       Chains[i] = L.getValue(1);
8758     }
8759 
8760     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8761   } else {
8762     // Collect the legal value parts into potentially illegal values
8763     // that correspond to the original function's return values.
8764     Optional<ISD::NodeType> AssertOp;
8765     if (CLI.RetSExt)
8766       AssertOp = ISD::AssertSext;
8767     else if (CLI.RetZExt)
8768       AssertOp = ISD::AssertZext;
8769     unsigned CurReg = 0;
8770     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8771       EVT VT = RetTys[I];
8772       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8773                                                      CLI.CallConv, VT);
8774       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8775                                                        CLI.CallConv, VT);
8776 
8777       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8778                                               NumRegs, RegisterVT, VT, nullptr,
8779                                               CLI.CallConv, AssertOp));
8780       CurReg += NumRegs;
8781     }
8782 
8783     // For a function returning void, there is no return value. We can't create
8784     // such a node, so we just return a null return value in that case. In
8785     // that case, nothing will actually look at the value.
8786     if (ReturnValues.empty())
8787       return std::make_pair(SDValue(), CLI.Chain);
8788   }
8789 
8790   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8791                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8792   return std::make_pair(Res, CLI.Chain);
8793 }
8794 
8795 void TargetLowering::LowerOperationWrapper(SDNode *N,
8796                                            SmallVectorImpl<SDValue> &Results,
8797                                            SelectionDAG &DAG) const {
8798   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8799     Results.push_back(Res);
8800 }
8801 
8802 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8803   llvm_unreachable("LowerOperation not implemented for this target!");
8804 }
8805 
8806 void
8807 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8808   SDValue Op = getNonRegisterValue(V);
8809   assert((Op.getOpcode() != ISD::CopyFromReg ||
8810           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8811          "Copy from a reg to the same reg!");
8812   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8813 
8814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8815   // If this is an InlineAsm we have to match the registers required, not the
8816   // notional registers required by the type.
8817 
8818   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
8819                    None); // This is not an ABI copy.
8820   SDValue Chain = DAG.getEntryNode();
8821 
8822   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8823                               FuncInfo.PreferredExtendType.end())
8824                                  ? ISD::ANY_EXTEND
8825                                  : FuncInfo.PreferredExtendType[V];
8826   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8827   PendingExports.push_back(Chain);
8828 }
8829 
8830 #include "llvm/CodeGen/SelectionDAGISel.h"
8831 
8832 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8833 /// entry block, return true.  This includes arguments used by switches, since
8834 /// the switch may expand into multiple basic blocks.
8835 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8836   // With FastISel active, we may be splitting blocks, so force creation
8837   // of virtual registers for all non-dead arguments.
8838   if (FastISel)
8839     return A->use_empty();
8840 
8841   const BasicBlock &Entry = A->getParent()->front();
8842   for (const User *U : A->users())
8843     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8844       return false;  // Use not in entry block.
8845 
8846   return true;
8847 }
8848 
8849 using ArgCopyElisionMapTy =
8850     DenseMap<const Argument *,
8851              std::pair<const AllocaInst *, const StoreInst *>>;
8852 
8853 /// Scan the entry block of the function in FuncInfo for arguments that look
8854 /// like copies into a local alloca. Record any copied arguments in
8855 /// ArgCopyElisionCandidates.
8856 static void
8857 findArgumentCopyElisionCandidates(const DataLayout &DL,
8858                                   FunctionLoweringInfo *FuncInfo,
8859                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8860   // Record the state of every static alloca used in the entry block. Argument
8861   // allocas are all used in the entry block, so we need approximately as many
8862   // entries as we have arguments.
8863   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8864   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8865   unsigned NumArgs = FuncInfo->Fn->arg_size();
8866   StaticAllocas.reserve(NumArgs * 2);
8867 
8868   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8869     if (!V)
8870       return nullptr;
8871     V = V->stripPointerCasts();
8872     const auto *AI = dyn_cast<AllocaInst>(V);
8873     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8874       return nullptr;
8875     auto Iter = StaticAllocas.insert({AI, Unknown});
8876     return &Iter.first->second;
8877   };
8878 
8879   // Look for stores of arguments to static allocas. Look through bitcasts and
8880   // GEPs to handle type coercions, as long as the alloca is fully initialized
8881   // by the store. Any non-store use of an alloca escapes it and any subsequent
8882   // unanalyzed store might write it.
8883   // FIXME: Handle structs initialized with multiple stores.
8884   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8885     // Look for stores, and handle non-store uses conservatively.
8886     const auto *SI = dyn_cast<StoreInst>(&I);
8887     if (!SI) {
8888       // We will look through cast uses, so ignore them completely.
8889       if (I.isCast())
8890         continue;
8891       // Ignore debug info intrinsics, they don't escape or store to allocas.
8892       if (isa<DbgInfoIntrinsic>(I))
8893         continue;
8894       // This is an unknown instruction. Assume it escapes or writes to all
8895       // static alloca operands.
8896       for (const Use &U : I.operands()) {
8897         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
8898           *Info = StaticAllocaInfo::Clobbered;
8899       }
8900       continue;
8901     }
8902 
8903     // If the stored value is a static alloca, mark it as escaped.
8904     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
8905       *Info = StaticAllocaInfo::Clobbered;
8906 
8907     // Check if the destination is a static alloca.
8908     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
8909     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
8910     if (!Info)
8911       continue;
8912     const AllocaInst *AI = cast<AllocaInst>(Dst);
8913 
8914     // Skip allocas that have been initialized or clobbered.
8915     if (*Info != StaticAllocaInfo::Unknown)
8916       continue;
8917 
8918     // Check if the stored value is an argument, and that this store fully
8919     // initializes the alloca. Don't elide copies from the same argument twice.
8920     const Value *Val = SI->getValueOperand()->stripPointerCasts();
8921     const auto *Arg = dyn_cast<Argument>(Val);
8922     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
8923         Arg->getType()->isEmptyTy() ||
8924         DL.getTypeStoreSize(Arg->getType()) !=
8925             DL.getTypeAllocSize(AI->getAllocatedType()) ||
8926         ArgCopyElisionCandidates.count(Arg)) {
8927       *Info = StaticAllocaInfo::Clobbered;
8928       continue;
8929     }
8930 
8931     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
8932                       << '\n');
8933 
8934     // Mark this alloca and store for argument copy elision.
8935     *Info = StaticAllocaInfo::Elidable;
8936     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
8937 
8938     // Stop scanning if we've seen all arguments. This will happen early in -O0
8939     // builds, which is useful, because -O0 builds have large entry blocks and
8940     // many allocas.
8941     if (ArgCopyElisionCandidates.size() == NumArgs)
8942       break;
8943   }
8944 }
8945 
8946 /// Try to elide argument copies from memory into a local alloca. Succeeds if
8947 /// ArgVal is a load from a suitable fixed stack object.
8948 static void tryToElideArgumentCopy(
8949     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
8950     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
8951     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
8952     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
8953     SDValue ArgVal, bool &ArgHasUses) {
8954   // Check if this is a load from a fixed stack object.
8955   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
8956   if (!LNode)
8957     return;
8958   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
8959   if (!FINode)
8960     return;
8961 
8962   // Check that the fixed stack object is the right size and alignment.
8963   // Look at the alignment that the user wrote on the alloca instead of looking
8964   // at the stack object.
8965   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
8966   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
8967   const AllocaInst *AI = ArgCopyIter->second.first;
8968   int FixedIndex = FINode->getIndex();
8969   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
8970   int OldIndex = AllocaIndex;
8971   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
8972   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
8973     LLVM_DEBUG(
8974         dbgs() << "  argument copy elision failed due to bad fixed stack "
8975                   "object size\n");
8976     return;
8977   }
8978   unsigned RequiredAlignment = AI->getAlignment();
8979   if (!RequiredAlignment) {
8980     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
8981         AI->getAllocatedType());
8982   }
8983   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
8984     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
8985                          "greater than stack argument alignment ("
8986                       << RequiredAlignment << " vs "
8987                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
8988     return;
8989   }
8990 
8991   // Perform the elision. Delete the old stack object and replace its only use
8992   // in the variable info map. Mark the stack object as mutable.
8993   LLVM_DEBUG({
8994     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
8995            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
8996            << '\n';
8997   });
8998   MFI.RemoveStackObject(OldIndex);
8999   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9000   AllocaIndex = FixedIndex;
9001   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9002   Chains.push_back(ArgVal.getValue(1));
9003 
9004   // Avoid emitting code for the store implementing the copy.
9005   const StoreInst *SI = ArgCopyIter->second.second;
9006   ElidedArgCopyInstrs.insert(SI);
9007 
9008   // Check for uses of the argument again so that we can avoid exporting ArgVal
9009   // if it is't used by anything other than the store.
9010   for (const Value *U : Arg.users()) {
9011     if (U != SI) {
9012       ArgHasUses = true;
9013       break;
9014     }
9015   }
9016 }
9017 
9018 void SelectionDAGISel::LowerArguments(const Function &F) {
9019   SelectionDAG &DAG = SDB->DAG;
9020   SDLoc dl = SDB->getCurSDLoc();
9021   const DataLayout &DL = DAG.getDataLayout();
9022   SmallVector<ISD::InputArg, 16> Ins;
9023 
9024   if (!FuncInfo->CanLowerReturn) {
9025     // Put in an sret pointer parameter before all the other parameters.
9026     SmallVector<EVT, 1> ValueVTs;
9027     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9028                     F.getReturnType()->getPointerTo(
9029                         DAG.getDataLayout().getAllocaAddrSpace()),
9030                     ValueVTs);
9031 
9032     // NOTE: Assuming that a pointer will never break down to more than one VT
9033     // or one register.
9034     ISD::ArgFlagsTy Flags;
9035     Flags.setSRet();
9036     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9037     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9038                          ISD::InputArg::NoArgIndex, 0);
9039     Ins.push_back(RetArg);
9040   }
9041 
9042   // Look for stores of arguments to static allocas. Mark such arguments with a
9043   // flag to ask the target to give us the memory location of that argument if
9044   // available.
9045   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9046   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9047 
9048   // Set up the incoming argument description vector.
9049   for (const Argument &Arg : F.args()) {
9050     unsigned ArgNo = Arg.getArgNo();
9051     SmallVector<EVT, 4> ValueVTs;
9052     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9053     bool isArgValueUsed = !Arg.use_empty();
9054     unsigned PartBase = 0;
9055     Type *FinalType = Arg.getType();
9056     if (Arg.hasAttribute(Attribute::ByVal))
9057       FinalType = cast<PointerType>(FinalType)->getElementType();
9058     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9059         FinalType, F.getCallingConv(), F.isVarArg());
9060     for (unsigned Value = 0, NumValues = ValueVTs.size();
9061          Value != NumValues; ++Value) {
9062       EVT VT = ValueVTs[Value];
9063       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9064       ISD::ArgFlagsTy Flags;
9065 
9066       // Certain targets (such as MIPS), may have a different ABI alignment
9067       // for a type depending on the context. Give the target a chance to
9068       // specify the alignment it wants.
9069       unsigned OriginalAlignment =
9070           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9071 
9072       if (Arg.hasAttribute(Attribute::ZExt))
9073         Flags.setZExt();
9074       if (Arg.hasAttribute(Attribute::SExt))
9075         Flags.setSExt();
9076       if (Arg.hasAttribute(Attribute::InReg)) {
9077         // If we are using vectorcall calling convention, a structure that is
9078         // passed InReg - is surely an HVA
9079         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9080             isa<StructType>(Arg.getType())) {
9081           // The first value of a structure is marked
9082           if (0 == Value)
9083             Flags.setHvaStart();
9084           Flags.setHva();
9085         }
9086         // Set InReg Flag
9087         Flags.setInReg();
9088       }
9089       if (Arg.hasAttribute(Attribute::StructRet))
9090         Flags.setSRet();
9091       if (Arg.hasAttribute(Attribute::SwiftSelf))
9092         Flags.setSwiftSelf();
9093       if (Arg.hasAttribute(Attribute::SwiftError))
9094         Flags.setSwiftError();
9095       if (Arg.hasAttribute(Attribute::ByVal))
9096         Flags.setByVal();
9097       if (Arg.hasAttribute(Attribute::InAlloca)) {
9098         Flags.setInAlloca();
9099         // Set the byval flag for CCAssignFn callbacks that don't know about
9100         // inalloca.  This way we can know how many bytes we should've allocated
9101         // and how many bytes a callee cleanup function will pop.  If we port
9102         // inalloca to more targets, we'll have to add custom inalloca handling
9103         // in the various CC lowering callbacks.
9104         Flags.setByVal();
9105       }
9106       if (F.getCallingConv() == CallingConv::X86_INTR) {
9107         // IA Interrupt passes frame (1st parameter) by value in the stack.
9108         if (ArgNo == 0)
9109           Flags.setByVal();
9110       }
9111       if (Flags.isByVal() || Flags.isInAlloca()) {
9112         PointerType *Ty = cast<PointerType>(Arg.getType());
9113         Type *ElementTy = Ty->getElementType();
9114         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
9115         // For ByVal, alignment should be passed from FE.  BE will guess if
9116         // this info is not there but there are cases it cannot get right.
9117         unsigned FrameAlign;
9118         if (Arg.getParamAlignment())
9119           FrameAlign = Arg.getParamAlignment();
9120         else
9121           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9122         Flags.setByValAlign(FrameAlign);
9123       }
9124       if (Arg.hasAttribute(Attribute::Nest))
9125         Flags.setNest();
9126       if (NeedsRegBlock)
9127         Flags.setInConsecutiveRegs();
9128       Flags.setOrigAlign(OriginalAlignment);
9129       if (ArgCopyElisionCandidates.count(&Arg))
9130         Flags.setCopyElisionCandidate();
9131 
9132       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9133           *CurDAG->getContext(), F.getCallingConv(), VT);
9134       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9135           *CurDAG->getContext(), F.getCallingConv(), VT);
9136       for (unsigned i = 0; i != NumRegs; ++i) {
9137         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9138                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9139         if (NumRegs > 1 && i == 0)
9140           MyFlags.Flags.setSplit();
9141         // if it isn't first piece, alignment must be 1
9142         else if (i > 0) {
9143           MyFlags.Flags.setOrigAlign(1);
9144           if (i == NumRegs - 1)
9145             MyFlags.Flags.setSplitEnd();
9146         }
9147         Ins.push_back(MyFlags);
9148       }
9149       if (NeedsRegBlock && Value == NumValues - 1)
9150         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9151       PartBase += VT.getStoreSize();
9152     }
9153   }
9154 
9155   // Call the target to set up the argument values.
9156   SmallVector<SDValue, 8> InVals;
9157   SDValue NewRoot = TLI->LowerFormalArguments(
9158       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9159 
9160   // Verify that the target's LowerFormalArguments behaved as expected.
9161   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9162          "LowerFormalArguments didn't return a valid chain!");
9163   assert(InVals.size() == Ins.size() &&
9164          "LowerFormalArguments didn't emit the correct number of values!");
9165   LLVM_DEBUG({
9166     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9167       assert(InVals[i].getNode() &&
9168              "LowerFormalArguments emitted a null value!");
9169       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9170              "LowerFormalArguments emitted a value with the wrong type!");
9171     }
9172   });
9173 
9174   // Update the DAG with the new chain value resulting from argument lowering.
9175   DAG.setRoot(NewRoot);
9176 
9177   // Set up the argument values.
9178   unsigned i = 0;
9179   if (!FuncInfo->CanLowerReturn) {
9180     // Create a virtual register for the sret pointer, and put in a copy
9181     // from the sret argument into it.
9182     SmallVector<EVT, 1> ValueVTs;
9183     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9184                     F.getReturnType()->getPointerTo(
9185                         DAG.getDataLayout().getAllocaAddrSpace()),
9186                     ValueVTs);
9187     MVT VT = ValueVTs[0].getSimpleVT();
9188     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9189     Optional<ISD::NodeType> AssertOp = None;
9190     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9191                                         nullptr, F.getCallingConv(), AssertOp);
9192 
9193     MachineFunction& MF = SDB->DAG.getMachineFunction();
9194     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9195     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9196     FuncInfo->DemoteRegister = SRetReg;
9197     NewRoot =
9198         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9199     DAG.setRoot(NewRoot);
9200 
9201     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9202     ++i;
9203   }
9204 
9205   SmallVector<SDValue, 4> Chains;
9206   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9207   for (const Argument &Arg : F.args()) {
9208     SmallVector<SDValue, 4> ArgValues;
9209     SmallVector<EVT, 4> ValueVTs;
9210     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9211     unsigned NumValues = ValueVTs.size();
9212     if (NumValues == 0)
9213       continue;
9214 
9215     bool ArgHasUses = !Arg.use_empty();
9216 
9217     // Elide the copying store if the target loaded this argument from a
9218     // suitable fixed stack object.
9219     if (Ins[i].Flags.isCopyElisionCandidate()) {
9220       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9221                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9222                              InVals[i], ArgHasUses);
9223     }
9224 
9225     // If this argument is unused then remember its value. It is used to generate
9226     // debugging information.
9227     bool isSwiftErrorArg =
9228         TLI->supportSwiftError() &&
9229         Arg.hasAttribute(Attribute::SwiftError);
9230     if (!ArgHasUses && !isSwiftErrorArg) {
9231       SDB->setUnusedArgValue(&Arg, InVals[i]);
9232 
9233       // Also remember any frame index for use in FastISel.
9234       if (FrameIndexSDNode *FI =
9235           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9236         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9237     }
9238 
9239     for (unsigned Val = 0; Val != NumValues; ++Val) {
9240       EVT VT = ValueVTs[Val];
9241       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9242                                                       F.getCallingConv(), VT);
9243       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9244           *CurDAG->getContext(), F.getCallingConv(), VT);
9245 
9246       // Even an apparant 'unused' swifterror argument needs to be returned. So
9247       // we do generate a copy for it that can be used on return from the
9248       // function.
9249       if (ArgHasUses || isSwiftErrorArg) {
9250         Optional<ISD::NodeType> AssertOp;
9251         if (Arg.hasAttribute(Attribute::SExt))
9252           AssertOp = ISD::AssertSext;
9253         else if (Arg.hasAttribute(Attribute::ZExt))
9254           AssertOp = ISD::AssertZext;
9255 
9256         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9257                                              PartVT, VT, nullptr,
9258                                              F.getCallingConv(), AssertOp));
9259       }
9260 
9261       i += NumParts;
9262     }
9263 
9264     // We don't need to do anything else for unused arguments.
9265     if (ArgValues.empty())
9266       continue;
9267 
9268     // Note down frame index.
9269     if (FrameIndexSDNode *FI =
9270         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9271       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9272 
9273     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9274                                      SDB->getCurSDLoc());
9275 
9276     SDB->setValue(&Arg, Res);
9277     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9278       // We want to associate the argument with the frame index, among
9279       // involved operands, that correspond to the lowest address. The
9280       // getCopyFromParts function, called earlier, is swapping the order of
9281       // the operands to BUILD_PAIR depending on endianness. The result of
9282       // that swapping is that the least significant bits of the argument will
9283       // be in the first operand of the BUILD_PAIR node, and the most
9284       // significant bits will be in the second operand.
9285       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9286       if (LoadSDNode *LNode =
9287           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9288         if (FrameIndexSDNode *FI =
9289             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9290           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9291     }
9292 
9293     // Update the SwiftErrorVRegDefMap.
9294     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9295       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9296       if (TargetRegisterInfo::isVirtualRegister(Reg))
9297         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9298                                            FuncInfo->SwiftErrorArg, Reg);
9299     }
9300 
9301     // If this argument is live outside of the entry block, insert a copy from
9302     // wherever we got it to the vreg that other BB's will reference it as.
9303     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9304       // If we can, though, try to skip creating an unnecessary vreg.
9305       // FIXME: This isn't very clean... it would be nice to make this more
9306       // general.  It's also subtly incompatible with the hacks FastISel
9307       // uses with vregs.
9308       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9309       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9310         FuncInfo->ValueMap[&Arg] = Reg;
9311         continue;
9312       }
9313     }
9314     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9315       FuncInfo->InitializeRegForValue(&Arg);
9316       SDB->CopyToExportRegsIfNeeded(&Arg);
9317     }
9318   }
9319 
9320   if (!Chains.empty()) {
9321     Chains.push_back(NewRoot);
9322     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9323   }
9324 
9325   DAG.setRoot(NewRoot);
9326 
9327   assert(i == InVals.size() && "Argument register count mismatch!");
9328 
9329   // If any argument copy elisions occurred and we have debug info, update the
9330   // stale frame indices used in the dbg.declare variable info table.
9331   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9332   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9333     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9334       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9335       if (I != ArgCopyElisionFrameIndexMap.end())
9336         VI.Slot = I->second;
9337     }
9338   }
9339 
9340   // Finally, if the target has anything special to do, allow it to do so.
9341   EmitFunctionEntryCode();
9342 }
9343 
9344 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9345 /// ensure constants are generated when needed.  Remember the virtual registers
9346 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9347 /// directly add them, because expansion might result in multiple MBB's for one
9348 /// BB.  As such, the start of the BB might correspond to a different MBB than
9349 /// the end.
9350 void
9351 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9352   const Instruction *TI = LLVMBB->getTerminator();
9353 
9354   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9355 
9356   // Check PHI nodes in successors that expect a value to be available from this
9357   // block.
9358   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9359     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9360     if (!isa<PHINode>(SuccBB->begin())) continue;
9361     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9362 
9363     // If this terminator has multiple identical successors (common for
9364     // switches), only handle each succ once.
9365     if (!SuccsHandled.insert(SuccMBB).second)
9366       continue;
9367 
9368     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9369 
9370     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9371     // nodes and Machine PHI nodes, but the incoming operands have not been
9372     // emitted yet.
9373     for (const PHINode &PN : SuccBB->phis()) {
9374       // Ignore dead phi's.
9375       if (PN.use_empty())
9376         continue;
9377 
9378       // Skip empty types
9379       if (PN.getType()->isEmptyTy())
9380         continue;
9381 
9382       unsigned Reg;
9383       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9384 
9385       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9386         unsigned &RegOut = ConstantsOut[C];
9387         if (RegOut == 0) {
9388           RegOut = FuncInfo.CreateRegs(C->getType());
9389           CopyValueToVirtualRegister(C, RegOut);
9390         }
9391         Reg = RegOut;
9392       } else {
9393         DenseMap<const Value *, unsigned>::iterator I =
9394           FuncInfo.ValueMap.find(PHIOp);
9395         if (I != FuncInfo.ValueMap.end())
9396           Reg = I->second;
9397         else {
9398           assert(isa<AllocaInst>(PHIOp) &&
9399                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9400                  "Didn't codegen value into a register!??");
9401           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9402           CopyValueToVirtualRegister(PHIOp, Reg);
9403         }
9404       }
9405 
9406       // Remember that this register needs to added to the machine PHI node as
9407       // the input for this MBB.
9408       SmallVector<EVT, 4> ValueVTs;
9409       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9410       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9411       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9412         EVT VT = ValueVTs[vti];
9413         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9414         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9415           FuncInfo.PHINodesToUpdate.push_back(
9416               std::make_pair(&*MBBI++, Reg + i));
9417         Reg += NumRegisters;
9418       }
9419     }
9420   }
9421 
9422   ConstantsOut.clear();
9423 }
9424 
9425 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9426 /// is 0.
9427 MachineBasicBlock *
9428 SelectionDAGBuilder::StackProtectorDescriptor::
9429 AddSuccessorMBB(const BasicBlock *BB,
9430                 MachineBasicBlock *ParentMBB,
9431                 bool IsLikely,
9432                 MachineBasicBlock *SuccMBB) {
9433   // If SuccBB has not been created yet, create it.
9434   if (!SuccMBB) {
9435     MachineFunction *MF = ParentMBB->getParent();
9436     MachineFunction::iterator BBI(ParentMBB);
9437     SuccMBB = MF->CreateMachineBasicBlock(BB);
9438     MF->insert(++BBI, SuccMBB);
9439   }
9440   // Add it as a successor of ParentMBB.
9441   ParentMBB->addSuccessor(
9442       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9443   return SuccMBB;
9444 }
9445 
9446 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9447   MachineFunction::iterator I(MBB);
9448   if (++I == FuncInfo.MF->end())
9449     return nullptr;
9450   return &*I;
9451 }
9452 
9453 /// During lowering new call nodes can be created (such as memset, etc.).
9454 /// Those will become new roots of the current DAG, but complications arise
9455 /// when they are tail calls. In such cases, the call lowering will update
9456 /// the root, but the builder still needs to know that a tail call has been
9457 /// lowered in order to avoid generating an additional return.
9458 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9459   // If the node is null, we do have a tail call.
9460   if (MaybeTC.getNode() != nullptr)
9461     DAG.setRoot(MaybeTC);
9462   else
9463     HasTailCall = true;
9464 }
9465 
9466 uint64_t
9467 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9468                                        unsigned First, unsigned Last) const {
9469   assert(Last >= First);
9470   const APInt &LowCase = Clusters[First].Low->getValue();
9471   const APInt &HighCase = Clusters[Last].High->getValue();
9472   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9473 
9474   // FIXME: A range of consecutive cases has 100% density, but only requires one
9475   // comparison to lower. We should discriminate against such consecutive ranges
9476   // in jump tables.
9477 
9478   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9479 }
9480 
9481 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9482     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9483     unsigned Last) const {
9484   assert(Last >= First);
9485   assert(TotalCases[Last] >= TotalCases[First]);
9486   uint64_t NumCases =
9487       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9488   return NumCases;
9489 }
9490 
9491 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9492                                          unsigned First, unsigned Last,
9493                                          const SwitchInst *SI,
9494                                          MachineBasicBlock *DefaultMBB,
9495                                          CaseCluster &JTCluster) {
9496   assert(First <= Last);
9497 
9498   auto Prob = BranchProbability::getZero();
9499   unsigned NumCmps = 0;
9500   std::vector<MachineBasicBlock*> Table;
9501   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9502 
9503   // Initialize probabilities in JTProbs.
9504   for (unsigned I = First; I <= Last; ++I)
9505     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9506 
9507   for (unsigned I = First; I <= Last; ++I) {
9508     assert(Clusters[I].Kind == CC_Range);
9509     Prob += Clusters[I].Prob;
9510     const APInt &Low = Clusters[I].Low->getValue();
9511     const APInt &High = Clusters[I].High->getValue();
9512     NumCmps += (Low == High) ? 1 : 2;
9513     if (I != First) {
9514       // Fill the gap between this and the previous cluster.
9515       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9516       assert(PreviousHigh.slt(Low));
9517       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9518       for (uint64_t J = 0; J < Gap; J++)
9519         Table.push_back(DefaultMBB);
9520     }
9521     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9522     for (uint64_t J = 0; J < ClusterSize; ++J)
9523       Table.push_back(Clusters[I].MBB);
9524     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9525   }
9526 
9527   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9528   unsigned NumDests = JTProbs.size();
9529   if (TLI.isSuitableForBitTests(
9530           NumDests, NumCmps, Clusters[First].Low->getValue(),
9531           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9532     // Clusters[First..Last] should be lowered as bit tests instead.
9533     return false;
9534   }
9535 
9536   // Create the MBB that will load from and jump through the table.
9537   // Note: We create it here, but it's not inserted into the function yet.
9538   MachineFunction *CurMF = FuncInfo.MF;
9539   MachineBasicBlock *JumpTableMBB =
9540       CurMF->CreateMachineBasicBlock(SI->getParent());
9541 
9542   // Add successors. Note: use table order for determinism.
9543   SmallPtrSet<MachineBasicBlock *, 8> Done;
9544   for (MachineBasicBlock *Succ : Table) {
9545     if (Done.count(Succ))
9546       continue;
9547     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9548     Done.insert(Succ);
9549   }
9550   JumpTableMBB->normalizeSuccProbs();
9551 
9552   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9553                      ->createJumpTableIndex(Table);
9554 
9555   // Set up the jump table info.
9556   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9557   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9558                       Clusters[Last].High->getValue(), SI->getCondition(),
9559                       nullptr, false);
9560   JTCases.emplace_back(std::move(JTH), std::move(JT));
9561 
9562   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9563                                      JTCases.size() - 1, Prob);
9564   return true;
9565 }
9566 
9567 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9568                                          const SwitchInst *SI,
9569                                          MachineBasicBlock *DefaultMBB) {
9570 #ifndef NDEBUG
9571   // Clusters must be non-empty, sorted, and only contain Range clusters.
9572   assert(!Clusters.empty());
9573   for (CaseCluster &C : Clusters)
9574     assert(C.Kind == CC_Range);
9575   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9576     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9577 #endif
9578 
9579   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9580   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9581     return;
9582 
9583   const int64_t N = Clusters.size();
9584   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9585   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9586 
9587   if (N < 2 || N < MinJumpTableEntries)
9588     return;
9589 
9590   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9591   SmallVector<unsigned, 8> TotalCases(N);
9592   for (unsigned i = 0; i < N; ++i) {
9593     const APInt &Hi = Clusters[i].High->getValue();
9594     const APInt &Lo = Clusters[i].Low->getValue();
9595     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9596     if (i != 0)
9597       TotalCases[i] += TotalCases[i - 1];
9598   }
9599 
9600   // Cheap case: the whole range may be suitable for jump table.
9601   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9602   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9603   assert(NumCases < UINT64_MAX / 100);
9604   assert(Range >= NumCases);
9605   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9606     CaseCluster JTCluster;
9607     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9608       Clusters[0] = JTCluster;
9609       Clusters.resize(1);
9610       return;
9611     }
9612   }
9613 
9614   // The algorithm below is not suitable for -O0.
9615   if (TM.getOptLevel() == CodeGenOpt::None)
9616     return;
9617 
9618   // Split Clusters into minimum number of dense partitions. The algorithm uses
9619   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9620   // for the Case Statement'" (1994), but builds the MinPartitions array in
9621   // reverse order to make it easier to reconstruct the partitions in ascending
9622   // order. In the choice between two optimal partitionings, it picks the one
9623   // which yields more jump tables.
9624 
9625   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9626   SmallVector<unsigned, 8> MinPartitions(N);
9627   // LastElement[i] is the last element of the partition starting at i.
9628   SmallVector<unsigned, 8> LastElement(N);
9629   // PartitionsScore[i] is used to break ties when choosing between two
9630   // partitionings resulting in the same number of partitions.
9631   SmallVector<unsigned, 8> PartitionsScore(N);
9632   // For PartitionsScore, a small number of comparisons is considered as good as
9633   // a jump table and a single comparison is considered better than a jump
9634   // table.
9635   enum PartitionScores : unsigned {
9636     NoTable = 0,
9637     Table = 1,
9638     FewCases = 1,
9639     SingleCase = 2
9640   };
9641 
9642   // Base case: There is only one way to partition Clusters[N-1].
9643   MinPartitions[N - 1] = 1;
9644   LastElement[N - 1] = N - 1;
9645   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9646 
9647   // Note: loop indexes are signed to avoid underflow.
9648   for (int64_t i = N - 2; i >= 0; i--) {
9649     // Find optimal partitioning of Clusters[i..N-1].
9650     // Baseline: Put Clusters[i] into a partition on its own.
9651     MinPartitions[i] = MinPartitions[i + 1] + 1;
9652     LastElement[i] = i;
9653     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9654 
9655     // Search for a solution that results in fewer partitions.
9656     for (int64_t j = N - 1; j > i; j--) {
9657       // Try building a partition from Clusters[i..j].
9658       uint64_t Range = getJumpTableRange(Clusters, i, j);
9659       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9660       assert(NumCases < UINT64_MAX / 100);
9661       assert(Range >= NumCases);
9662       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9663         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9664         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9665         int64_t NumEntries = j - i + 1;
9666 
9667         if (NumEntries == 1)
9668           Score += PartitionScores::SingleCase;
9669         else if (NumEntries <= SmallNumberOfEntries)
9670           Score += PartitionScores::FewCases;
9671         else if (NumEntries >= MinJumpTableEntries)
9672           Score += PartitionScores::Table;
9673 
9674         // If this leads to fewer partitions, or to the same number of
9675         // partitions with better score, it is a better partitioning.
9676         if (NumPartitions < MinPartitions[i] ||
9677             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9678           MinPartitions[i] = NumPartitions;
9679           LastElement[i] = j;
9680           PartitionsScore[i] = Score;
9681         }
9682       }
9683     }
9684   }
9685 
9686   // Iterate over the partitions, replacing some with jump tables in-place.
9687   unsigned DstIndex = 0;
9688   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9689     Last = LastElement[First];
9690     assert(Last >= First);
9691     assert(DstIndex <= First);
9692     unsigned NumClusters = Last - First + 1;
9693 
9694     CaseCluster JTCluster;
9695     if (NumClusters >= MinJumpTableEntries &&
9696         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9697       Clusters[DstIndex++] = JTCluster;
9698     } else {
9699       for (unsigned I = First; I <= Last; ++I)
9700         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9701     }
9702   }
9703   Clusters.resize(DstIndex);
9704 }
9705 
9706 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9707                                         unsigned First, unsigned Last,
9708                                         const SwitchInst *SI,
9709                                         CaseCluster &BTCluster) {
9710   assert(First <= Last);
9711   if (First == Last)
9712     return false;
9713 
9714   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9715   unsigned NumCmps = 0;
9716   for (int64_t I = First; I <= Last; ++I) {
9717     assert(Clusters[I].Kind == CC_Range);
9718     Dests.set(Clusters[I].MBB->getNumber());
9719     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9720   }
9721   unsigned NumDests = Dests.count();
9722 
9723   APInt Low = Clusters[First].Low->getValue();
9724   APInt High = Clusters[Last].High->getValue();
9725   assert(Low.slt(High));
9726 
9727   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9728   const DataLayout &DL = DAG.getDataLayout();
9729   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9730     return false;
9731 
9732   APInt LowBound;
9733   APInt CmpRange;
9734 
9735   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9736   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9737          "Case range must fit in bit mask!");
9738 
9739   // Check if the clusters cover a contiguous range such that no value in the
9740   // range will jump to the default statement.
9741   bool ContiguousRange = true;
9742   for (int64_t I = First + 1; I <= Last; ++I) {
9743     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9744       ContiguousRange = false;
9745       break;
9746     }
9747   }
9748 
9749   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9750     // Optimize the case where all the case values fit in a word without having
9751     // to subtract minValue. In this case, we can optimize away the subtraction.
9752     LowBound = APInt::getNullValue(Low.getBitWidth());
9753     CmpRange = High;
9754     ContiguousRange = false;
9755   } else {
9756     LowBound = Low;
9757     CmpRange = High - Low;
9758   }
9759 
9760   CaseBitsVector CBV;
9761   auto TotalProb = BranchProbability::getZero();
9762   for (unsigned i = First; i <= Last; ++i) {
9763     // Find the CaseBits for this destination.
9764     unsigned j;
9765     for (j = 0; j < CBV.size(); ++j)
9766       if (CBV[j].BB == Clusters[i].MBB)
9767         break;
9768     if (j == CBV.size())
9769       CBV.push_back(
9770           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9771     CaseBits *CB = &CBV[j];
9772 
9773     // Update Mask, Bits and ExtraProb.
9774     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9775     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9776     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9777     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9778     CB->Bits += Hi - Lo + 1;
9779     CB->ExtraProb += Clusters[i].Prob;
9780     TotalProb += Clusters[i].Prob;
9781   }
9782 
9783   BitTestInfo BTI;
9784   llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
9785     // Sort by probability first, number of bits second, bit mask third.
9786     if (a.ExtraProb != b.ExtraProb)
9787       return a.ExtraProb > b.ExtraProb;
9788     if (a.Bits != b.Bits)
9789       return a.Bits > b.Bits;
9790     return a.Mask < b.Mask;
9791   });
9792 
9793   for (auto &CB : CBV) {
9794     MachineBasicBlock *BitTestBB =
9795         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9796     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9797   }
9798   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9799                             SI->getCondition(), -1U, MVT::Other, false,
9800                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9801                             TotalProb);
9802 
9803   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9804                                     BitTestCases.size() - 1, TotalProb);
9805   return true;
9806 }
9807 
9808 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9809                                               const SwitchInst *SI) {
9810 // Partition Clusters into as few subsets as possible, where each subset has a
9811 // range that fits in a machine word and has <= 3 unique destinations.
9812 
9813 #ifndef NDEBUG
9814   // Clusters must be sorted and contain Range or JumpTable clusters.
9815   assert(!Clusters.empty());
9816   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9817   for (const CaseCluster &C : Clusters)
9818     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9819   for (unsigned i = 1; i < Clusters.size(); ++i)
9820     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9821 #endif
9822 
9823   // The algorithm below is not suitable for -O0.
9824   if (TM.getOptLevel() == CodeGenOpt::None)
9825     return;
9826 
9827   // If target does not have legal shift left, do not emit bit tests at all.
9828   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9829   const DataLayout &DL = DAG.getDataLayout();
9830 
9831   EVT PTy = TLI.getPointerTy(DL);
9832   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9833     return;
9834 
9835   int BitWidth = PTy.getSizeInBits();
9836   const int64_t N = Clusters.size();
9837 
9838   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9839   SmallVector<unsigned, 8> MinPartitions(N);
9840   // LastElement[i] is the last element of the partition starting at i.
9841   SmallVector<unsigned, 8> LastElement(N);
9842 
9843   // FIXME: This might not be the best algorithm for finding bit test clusters.
9844 
9845   // Base case: There is only one way to partition Clusters[N-1].
9846   MinPartitions[N - 1] = 1;
9847   LastElement[N - 1] = N - 1;
9848 
9849   // Note: loop indexes are signed to avoid underflow.
9850   for (int64_t i = N - 2; i >= 0; --i) {
9851     // Find optimal partitioning of Clusters[i..N-1].
9852     // Baseline: Put Clusters[i] into a partition on its own.
9853     MinPartitions[i] = MinPartitions[i + 1] + 1;
9854     LastElement[i] = i;
9855 
9856     // Search for a solution that results in fewer partitions.
9857     // Note: the search is limited by BitWidth, reducing time complexity.
9858     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9859       // Try building a partition from Clusters[i..j].
9860 
9861       // Check the range.
9862       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9863                                Clusters[j].High->getValue(), DL))
9864         continue;
9865 
9866       // Check nbr of destinations and cluster types.
9867       // FIXME: This works, but doesn't seem very efficient.
9868       bool RangesOnly = true;
9869       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9870       for (int64_t k = i; k <= j; k++) {
9871         if (Clusters[k].Kind != CC_Range) {
9872           RangesOnly = false;
9873           break;
9874         }
9875         Dests.set(Clusters[k].MBB->getNumber());
9876       }
9877       if (!RangesOnly || Dests.count() > 3)
9878         break;
9879 
9880       // Check if it's a better partition.
9881       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9882       if (NumPartitions < MinPartitions[i]) {
9883         // Found a better partition.
9884         MinPartitions[i] = NumPartitions;
9885         LastElement[i] = j;
9886       }
9887     }
9888   }
9889 
9890   // Iterate over the partitions, replacing with bit-test clusters in-place.
9891   unsigned DstIndex = 0;
9892   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9893     Last = LastElement[First];
9894     assert(First <= Last);
9895     assert(DstIndex <= First);
9896 
9897     CaseCluster BitTestCluster;
9898     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
9899       Clusters[DstIndex++] = BitTestCluster;
9900     } else {
9901       size_t NumClusters = Last - First + 1;
9902       std::memmove(&Clusters[DstIndex], &Clusters[First],
9903                    sizeof(Clusters[0]) * NumClusters);
9904       DstIndex += NumClusters;
9905     }
9906   }
9907   Clusters.resize(DstIndex);
9908 }
9909 
9910 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9911                                         MachineBasicBlock *SwitchMBB,
9912                                         MachineBasicBlock *DefaultMBB) {
9913   MachineFunction *CurMF = FuncInfo.MF;
9914   MachineBasicBlock *NextMBB = nullptr;
9915   MachineFunction::iterator BBI(W.MBB);
9916   if (++BBI != FuncInfo.MF->end())
9917     NextMBB = &*BBI;
9918 
9919   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9920 
9921   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9922 
9923   if (Size == 2 && W.MBB == SwitchMBB) {
9924     // If any two of the cases has the same destination, and if one value
9925     // is the same as the other, but has one bit unset that the other has set,
9926     // use bit manipulation to do two compares at once.  For example:
9927     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9928     // TODO: This could be extended to merge any 2 cases in switches with 3
9929     // cases.
9930     // TODO: Handle cases where W.CaseBB != SwitchBB.
9931     CaseCluster &Small = *W.FirstCluster;
9932     CaseCluster &Big = *W.LastCluster;
9933 
9934     if (Small.Low == Small.High && Big.Low == Big.High &&
9935         Small.MBB == Big.MBB) {
9936       const APInt &SmallValue = Small.Low->getValue();
9937       const APInt &BigValue = Big.Low->getValue();
9938 
9939       // Check that there is only one bit different.
9940       APInt CommonBit = BigValue ^ SmallValue;
9941       if (CommonBit.isPowerOf2()) {
9942         SDValue CondLHS = getValue(Cond);
9943         EVT VT = CondLHS.getValueType();
9944         SDLoc DL = getCurSDLoc();
9945 
9946         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9947                                  DAG.getConstant(CommonBit, DL, VT));
9948         SDValue Cond = DAG.getSetCC(
9949             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9950             ISD::SETEQ);
9951 
9952         // Update successor info.
9953         // Both Small and Big will jump to Small.BB, so we sum up the
9954         // probabilities.
9955         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9956         if (BPI)
9957           addSuccessorWithProb(
9958               SwitchMBB, DefaultMBB,
9959               // The default destination is the first successor in IR.
9960               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9961         else
9962           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9963 
9964         // Insert the true branch.
9965         SDValue BrCond =
9966             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9967                         DAG.getBasicBlock(Small.MBB));
9968         // Insert the false branch.
9969         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9970                              DAG.getBasicBlock(DefaultMBB));
9971 
9972         DAG.setRoot(BrCond);
9973         return;
9974       }
9975     }
9976   }
9977 
9978   if (TM.getOptLevel() != CodeGenOpt::None) {
9979     // Here, we order cases by probability so the most likely case will be
9980     // checked first. However, two clusters can have the same probability in
9981     // which case their relative ordering is non-deterministic. So we use Low
9982     // as a tie-breaker as clusters are guaranteed to never overlap.
9983     llvm::sort(W.FirstCluster, W.LastCluster + 1,
9984                [](const CaseCluster &a, const CaseCluster &b) {
9985       return a.Prob != b.Prob ?
9986              a.Prob > b.Prob :
9987              a.Low->getValue().slt(b.Low->getValue());
9988     });
9989 
9990     // Rearrange the case blocks so that the last one falls through if possible
9991     // without changing the order of probabilities.
9992     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9993       --I;
9994       if (I->Prob > W.LastCluster->Prob)
9995         break;
9996       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9997         std::swap(*I, *W.LastCluster);
9998         break;
9999       }
10000     }
10001   }
10002 
10003   // Compute total probability.
10004   BranchProbability DefaultProb = W.DefaultProb;
10005   BranchProbability UnhandledProbs = DefaultProb;
10006   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10007     UnhandledProbs += I->Prob;
10008 
10009   MachineBasicBlock *CurMBB = W.MBB;
10010   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10011     MachineBasicBlock *Fallthrough;
10012     if (I == W.LastCluster) {
10013       // For the last cluster, fall through to the default destination.
10014       Fallthrough = DefaultMBB;
10015     } else {
10016       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10017       CurMF->insert(BBI, Fallthrough);
10018       // Put Cond in a virtual register to make it available from the new blocks.
10019       ExportFromCurrentBlock(Cond);
10020     }
10021     UnhandledProbs -= I->Prob;
10022 
10023     switch (I->Kind) {
10024       case CC_JumpTable: {
10025         // FIXME: Optimize away range check based on pivot comparisons.
10026         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
10027         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
10028 
10029         // The jump block hasn't been inserted yet; insert it here.
10030         MachineBasicBlock *JumpMBB = JT->MBB;
10031         CurMF->insert(BBI, JumpMBB);
10032 
10033         auto JumpProb = I->Prob;
10034         auto FallthroughProb = UnhandledProbs;
10035 
10036         // If the default statement is a target of the jump table, we evenly
10037         // distribute the default probability to successors of CurMBB. Also
10038         // update the probability on the edge from JumpMBB to Fallthrough.
10039         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10040                                               SE = JumpMBB->succ_end();
10041              SI != SE; ++SI) {
10042           if (*SI == DefaultMBB) {
10043             JumpProb += DefaultProb / 2;
10044             FallthroughProb -= DefaultProb / 2;
10045             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10046             JumpMBB->normalizeSuccProbs();
10047             break;
10048           }
10049         }
10050 
10051         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10052         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10053         CurMBB->normalizeSuccProbs();
10054 
10055         // The jump table header will be inserted in our current block, do the
10056         // range check, and fall through to our fallthrough block.
10057         JTH->HeaderBB = CurMBB;
10058         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10059 
10060         // If we're in the right place, emit the jump table header right now.
10061         if (CurMBB == SwitchMBB) {
10062           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10063           JTH->Emitted = true;
10064         }
10065         break;
10066       }
10067       case CC_BitTests: {
10068         // FIXME: Optimize away range check based on pivot comparisons.
10069         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
10070 
10071         // The bit test blocks haven't been inserted yet; insert them here.
10072         for (BitTestCase &BTC : BTB->Cases)
10073           CurMF->insert(BBI, BTC.ThisBB);
10074 
10075         // Fill in fields of the BitTestBlock.
10076         BTB->Parent = CurMBB;
10077         BTB->Default = Fallthrough;
10078 
10079         BTB->DefaultProb = UnhandledProbs;
10080         // If the cases in bit test don't form a contiguous range, we evenly
10081         // distribute the probability on the edge to Fallthrough to two
10082         // successors of CurMBB.
10083         if (!BTB->ContiguousRange) {
10084           BTB->Prob += DefaultProb / 2;
10085           BTB->DefaultProb -= DefaultProb / 2;
10086         }
10087 
10088         // If we're in the right place, emit the bit test header right now.
10089         if (CurMBB == SwitchMBB) {
10090           visitBitTestHeader(*BTB, SwitchMBB);
10091           BTB->Emitted = true;
10092         }
10093         break;
10094       }
10095       case CC_Range: {
10096         const Value *RHS, *LHS, *MHS;
10097         ISD::CondCode CC;
10098         if (I->Low == I->High) {
10099           // Check Cond == I->Low.
10100           CC = ISD::SETEQ;
10101           LHS = Cond;
10102           RHS=I->Low;
10103           MHS = nullptr;
10104         } else {
10105           // Check I->Low <= Cond <= I->High.
10106           CC = ISD::SETLE;
10107           LHS = I->Low;
10108           MHS = Cond;
10109           RHS = I->High;
10110         }
10111 
10112         // The false probability is the sum of all unhandled cases.
10113         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10114                      getCurSDLoc(), I->Prob, UnhandledProbs);
10115 
10116         if (CurMBB == SwitchMBB)
10117           visitSwitchCase(CB, SwitchMBB);
10118         else
10119           SwitchCases.push_back(CB);
10120 
10121         break;
10122       }
10123     }
10124     CurMBB = Fallthrough;
10125   }
10126 }
10127 
10128 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10129                                               CaseClusterIt First,
10130                                               CaseClusterIt Last) {
10131   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10132     if (X.Prob != CC.Prob)
10133       return X.Prob > CC.Prob;
10134 
10135     // Ties are broken by comparing the case value.
10136     return X.Low->getValue().slt(CC.Low->getValue());
10137   });
10138 }
10139 
10140 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10141                                         const SwitchWorkListItem &W,
10142                                         Value *Cond,
10143                                         MachineBasicBlock *SwitchMBB) {
10144   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10145          "Clusters not sorted?");
10146 
10147   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10148 
10149   // Balance the tree based on branch probabilities to create a near-optimal (in
10150   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10151   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10152   CaseClusterIt LastLeft = W.FirstCluster;
10153   CaseClusterIt FirstRight = W.LastCluster;
10154   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10155   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10156 
10157   // Move LastLeft and FirstRight towards each other from opposite directions to
10158   // find a partitioning of the clusters which balances the probability on both
10159   // sides. If LeftProb and RightProb are equal, alternate which side is
10160   // taken to ensure 0-probability nodes are distributed evenly.
10161   unsigned I = 0;
10162   while (LastLeft + 1 < FirstRight) {
10163     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10164       LeftProb += (++LastLeft)->Prob;
10165     else
10166       RightProb += (--FirstRight)->Prob;
10167     I++;
10168   }
10169 
10170   while (true) {
10171     // Our binary search tree differs from a typical BST in that ours can have up
10172     // to three values in each leaf. The pivot selection above doesn't take that
10173     // into account, which means the tree might require more nodes and be less
10174     // efficient. We compensate for this here.
10175 
10176     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10177     unsigned NumRight = W.LastCluster - FirstRight + 1;
10178 
10179     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10180       // If one side has less than 3 clusters, and the other has more than 3,
10181       // consider taking a cluster from the other side.
10182 
10183       if (NumLeft < NumRight) {
10184         // Consider moving the first cluster on the right to the left side.
10185         CaseCluster &CC = *FirstRight;
10186         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10187         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10188         if (LeftSideRank <= RightSideRank) {
10189           // Moving the cluster to the left does not demote it.
10190           ++LastLeft;
10191           ++FirstRight;
10192           continue;
10193         }
10194       } else {
10195         assert(NumRight < NumLeft);
10196         // Consider moving the last element on the left to the right side.
10197         CaseCluster &CC = *LastLeft;
10198         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10199         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10200         if (RightSideRank <= LeftSideRank) {
10201           // Moving the cluster to the right does not demot it.
10202           --LastLeft;
10203           --FirstRight;
10204           continue;
10205         }
10206       }
10207     }
10208     break;
10209   }
10210 
10211   assert(LastLeft + 1 == FirstRight);
10212   assert(LastLeft >= W.FirstCluster);
10213   assert(FirstRight <= W.LastCluster);
10214 
10215   // Use the first element on the right as pivot since we will make less-than
10216   // comparisons against it.
10217   CaseClusterIt PivotCluster = FirstRight;
10218   assert(PivotCluster > W.FirstCluster);
10219   assert(PivotCluster <= W.LastCluster);
10220 
10221   CaseClusterIt FirstLeft = W.FirstCluster;
10222   CaseClusterIt LastRight = W.LastCluster;
10223 
10224   const ConstantInt *Pivot = PivotCluster->Low;
10225 
10226   // New blocks will be inserted immediately after the current one.
10227   MachineFunction::iterator BBI(W.MBB);
10228   ++BBI;
10229 
10230   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10231   // we can branch to its destination directly if it's squeezed exactly in
10232   // between the known lower bound and Pivot - 1.
10233   MachineBasicBlock *LeftMBB;
10234   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10235       FirstLeft->Low == W.GE &&
10236       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10237     LeftMBB = FirstLeft->MBB;
10238   } else {
10239     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10240     FuncInfo.MF->insert(BBI, LeftMBB);
10241     WorkList.push_back(
10242         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10243     // Put Cond in a virtual register to make it available from the new blocks.
10244     ExportFromCurrentBlock(Cond);
10245   }
10246 
10247   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10248   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10249   // directly if RHS.High equals the current upper bound.
10250   MachineBasicBlock *RightMBB;
10251   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10252       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10253     RightMBB = FirstRight->MBB;
10254   } else {
10255     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10256     FuncInfo.MF->insert(BBI, RightMBB);
10257     WorkList.push_back(
10258         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10259     // Put Cond in a virtual register to make it available from the new blocks.
10260     ExportFromCurrentBlock(Cond);
10261   }
10262 
10263   // Create the CaseBlock record that will be used to lower the branch.
10264   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10265                getCurSDLoc(), LeftProb, RightProb);
10266 
10267   if (W.MBB == SwitchMBB)
10268     visitSwitchCase(CB, SwitchMBB);
10269   else
10270     SwitchCases.push_back(CB);
10271 }
10272 
10273 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10274 // from the swith statement.
10275 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10276                                             BranchProbability PeeledCaseProb) {
10277   if (PeeledCaseProb == BranchProbability::getOne())
10278     return BranchProbability::getZero();
10279   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10280 
10281   uint32_t Numerator = CaseProb.getNumerator();
10282   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10283   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10284 }
10285 
10286 // Try to peel the top probability case if it exceeds the threshold.
10287 // Return current MachineBasicBlock for the switch statement if the peeling
10288 // does not occur.
10289 // If the peeling is performed, return the newly created MachineBasicBlock
10290 // for the peeled switch statement. Also update Clusters to remove the peeled
10291 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10292 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10293     const SwitchInst &SI, CaseClusterVector &Clusters,
10294     BranchProbability &PeeledCaseProb) {
10295   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10296   // Don't perform if there is only one cluster or optimizing for size.
10297   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10298       TM.getOptLevel() == CodeGenOpt::None ||
10299       SwitchMBB->getParent()->getFunction().optForMinSize())
10300     return SwitchMBB;
10301 
10302   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10303   unsigned PeeledCaseIndex = 0;
10304   bool SwitchPeeled = false;
10305   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10306     CaseCluster &CC = Clusters[Index];
10307     if (CC.Prob < TopCaseProb)
10308       continue;
10309     TopCaseProb = CC.Prob;
10310     PeeledCaseIndex = Index;
10311     SwitchPeeled = true;
10312   }
10313   if (!SwitchPeeled)
10314     return SwitchMBB;
10315 
10316   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10317                     << TopCaseProb << "\n");
10318 
10319   // Record the MBB for the peeled switch statement.
10320   MachineFunction::iterator BBI(SwitchMBB);
10321   ++BBI;
10322   MachineBasicBlock *PeeledSwitchMBB =
10323       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10324   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10325 
10326   ExportFromCurrentBlock(SI.getCondition());
10327   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10328   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10329                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10330   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10331 
10332   Clusters.erase(PeeledCaseIt);
10333   for (CaseCluster &CC : Clusters) {
10334     LLVM_DEBUG(
10335         dbgs() << "Scale the probablity for one cluster, before scaling: "
10336                << CC.Prob << "\n");
10337     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10338     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10339   }
10340   PeeledCaseProb = TopCaseProb;
10341   return PeeledSwitchMBB;
10342 }
10343 
10344 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10345   // Extract cases from the switch.
10346   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10347   CaseClusterVector Clusters;
10348   Clusters.reserve(SI.getNumCases());
10349   for (auto I : SI.cases()) {
10350     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10351     const ConstantInt *CaseVal = I.getCaseValue();
10352     BranchProbability Prob =
10353         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10354             : BranchProbability(1, SI.getNumCases() + 1);
10355     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10356   }
10357 
10358   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10359 
10360   // Cluster adjacent cases with the same destination. We do this at all
10361   // optimization levels because it's cheap to do and will make codegen faster
10362   // if there are many clusters.
10363   sortAndRangeify(Clusters);
10364 
10365   if (TM.getOptLevel() != CodeGenOpt::None) {
10366     // Replace an unreachable default with the most popular destination.
10367     // FIXME: Exploit unreachable default more aggressively.
10368     bool UnreachableDefault =
10369         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10370     if (UnreachableDefault && !Clusters.empty()) {
10371       DenseMap<const BasicBlock *, unsigned> Popularity;
10372       unsigned MaxPop = 0;
10373       const BasicBlock *MaxBB = nullptr;
10374       for (auto I : SI.cases()) {
10375         const BasicBlock *BB = I.getCaseSuccessor();
10376         if (++Popularity[BB] > MaxPop) {
10377           MaxPop = Popularity[BB];
10378           MaxBB = BB;
10379         }
10380       }
10381       // Set new default.
10382       assert(MaxPop > 0 && MaxBB);
10383       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10384 
10385       // Remove cases that were pointing to the destination that is now the
10386       // default.
10387       CaseClusterVector New;
10388       New.reserve(Clusters.size());
10389       for (CaseCluster &CC : Clusters) {
10390         if (CC.MBB != DefaultMBB)
10391           New.push_back(CC);
10392       }
10393       Clusters = std::move(New);
10394     }
10395   }
10396 
10397   // The branch probablity of the peeled case.
10398   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10399   MachineBasicBlock *PeeledSwitchMBB =
10400       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10401 
10402   // If there is only the default destination, jump there directly.
10403   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10404   if (Clusters.empty()) {
10405     assert(PeeledSwitchMBB == SwitchMBB);
10406     SwitchMBB->addSuccessor(DefaultMBB);
10407     if (DefaultMBB != NextBlock(SwitchMBB)) {
10408       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10409                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10410     }
10411     return;
10412   }
10413 
10414   findJumpTables(Clusters, &SI, DefaultMBB);
10415   findBitTestClusters(Clusters, &SI);
10416 
10417   LLVM_DEBUG({
10418     dbgs() << "Case clusters: ";
10419     for (const CaseCluster &C : Clusters) {
10420       if (C.Kind == CC_JumpTable)
10421         dbgs() << "JT:";
10422       if (C.Kind == CC_BitTests)
10423         dbgs() << "BT:";
10424 
10425       C.Low->getValue().print(dbgs(), true);
10426       if (C.Low != C.High) {
10427         dbgs() << '-';
10428         C.High->getValue().print(dbgs(), true);
10429       }
10430       dbgs() << ' ';
10431     }
10432     dbgs() << '\n';
10433   });
10434 
10435   assert(!Clusters.empty());
10436   SwitchWorkList WorkList;
10437   CaseClusterIt First = Clusters.begin();
10438   CaseClusterIt Last = Clusters.end() - 1;
10439   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10440   // Scale the branchprobability for DefaultMBB if the peel occurs and
10441   // DefaultMBB is not replaced.
10442   if (PeeledCaseProb != BranchProbability::getZero() &&
10443       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10444     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10445   WorkList.push_back(
10446       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10447 
10448   while (!WorkList.empty()) {
10449     SwitchWorkListItem W = WorkList.back();
10450     WorkList.pop_back();
10451     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10452 
10453     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10454         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10455       // For optimized builds, lower large range as a balanced binary tree.
10456       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10457       continue;
10458     }
10459 
10460     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10461   }
10462 }
10463