1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SelectionDAGBuilder.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/TargetLibraryInfo.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/Analysis/VectorUtils.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/FunctionLoweringInfo.h"
41 #include "llvm/CodeGen/GCMetadata.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineJumpTableInfo.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/RuntimeLibcalls.h"
54 #include "llvm/CodeGen/SelectionDAG.h"
55 #include "llvm/CodeGen/SelectionDAGNodes.h"
56 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
57 #include "llvm/CodeGen/StackMaps.h"
58 #include "llvm/CodeGen/TargetFrameLowering.h"
59 #include "llvm/CodeGen/TargetInstrInfo.h"
60 #include "llvm/CodeGen/TargetLowering.h"
61 #include "llvm/CodeGen/TargetOpcodes.h"
62 #include "llvm/CodeGen/TargetRegisterInfo.h"
63 #include "llvm/CodeGen/TargetSubtargetInfo.h"
64 #include "llvm/CodeGen/ValueTypes.h"
65 #include "llvm/CodeGen/WinEHFuncInfo.h"
66 #include "llvm/IR/Argument.h"
67 #include "llvm/IR/Attributes.h"
68 #include "llvm/IR/BasicBlock.h"
69 #include "llvm/IR/CFG.h"
70 #include "llvm/IR/CallSite.h"
71 #include "llvm/IR/CallingConv.h"
72 #include "llvm/IR/Constant.h"
73 #include "llvm/IR/ConstantRange.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DebugInfoMetadata.h"
77 #include "llvm/IR/DebugLoc.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/InlineAsm.h"
82 #include "llvm/IR/InstrTypes.h"
83 #include "llvm/IR/Instruction.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/Intrinsics.h"
87 #include "llvm/IR/LLVMContext.h"
88 #include "llvm/IR/Metadata.h"
89 #include "llvm/IR/Module.h"
90 #include "llvm/IR/Operator.h"
91 #include "llvm/IR/PatternMatch.h"
92 #include "llvm/IR/Statepoint.h"
93 #include "llvm/IR/Type.h"
94 #include "llvm/IR/User.h"
95 #include "llvm/IR/Value.h"
96 #include "llvm/MC/MCContext.h"
97 #include "llvm/MC/MCSymbol.h"
98 #include "llvm/Support/AtomicOrdering.h"
99 #include "llvm/Support/BranchProbability.h"
100 #include "llvm/Support/Casting.h"
101 #include "llvm/Support/CodeGen.h"
102 #include "llvm/Support/CommandLine.h"
103 #include "llvm/Support/Compiler.h"
104 #include "llvm/Support/Debug.h"
105 #include "llvm/Support/ErrorHandling.h"
106 #include "llvm/Support/MachineValueType.h"
107 #include "llvm/Support/MathExtras.h"
108 #include "llvm/Support/raw_ostream.h"
109 #include "llvm/Target/TargetIntrinsicInfo.h"
110 #include "llvm/Target/TargetMachine.h"
111 #include "llvm/Target/TargetOptions.h"
112 #include <algorithm>
113 #include <cassert>
114 #include <cstddef>
115 #include <cstdint>
116 #include <cstring>
117 #include <iterator>
118 #include <limits>
119 #include <numeric>
120 #include <tuple>
121 #include <utility>
122 #include <vector>
123 
124 using namespace llvm;
125 using namespace PatternMatch;
126 
127 #define DEBUG_TYPE "isel"
128 
129 /// LimitFloatPrecision - Generate low-precision inline sequences for
130 /// some float libcalls (6, 8 or 12 bits).
131 static unsigned LimitFloatPrecision;
132 
133 static cl::opt<unsigned, true>
134     LimitFPPrecision("limit-float-precision",
135                      cl::desc("Generate low-precision inline sequences "
136                               "for some float libcalls"),
137                      cl::location(LimitFloatPrecision), cl::Hidden,
138                      cl::init(0));
139 
140 static cl::opt<unsigned> SwitchPeelThreshold(
141     "switch-peel-threshold", cl::Hidden, cl::init(66),
142     cl::desc("Set the case probability threshold for peeling the case from a "
143              "switch statement. A value greater than 100 will void this "
144              "optimization"));
145 
146 // Limit the width of DAG chains. This is important in general to prevent
147 // DAG-based analysis from blowing up. For example, alias analysis and
148 // load clustering may not complete in reasonable time. It is difficult to
149 // recognize and avoid this situation within each individual analysis, and
150 // future analyses are likely to have the same behavior. Limiting DAG width is
151 // the safe approach and will be especially important with global DAGs.
152 //
153 // MaxParallelChains default is arbitrarily high to avoid affecting
154 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
155 // sequence over this should have been converted to llvm.memcpy by the
156 // frontend. It is easy to induce this behavior with .ll code such as:
157 // %buffer = alloca [4096 x i8]
158 // %data = load [4096 x i8]* %argPtr
159 // store [4096 x i8] %data, [4096 x i8]* %buffer
160 static const unsigned MaxParallelChains = 64;
161 
162 // Return the calling convention if the Value passed requires ABI mangling as it
163 // is a parameter to a function or a return value from a function which is not
164 // an intrinsic.
165 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
166   if (auto *R = dyn_cast<ReturnInst>(V))
167     return R->getParent()->getParent()->getCallingConv();
168 
169   if (auto *CI = dyn_cast<CallInst>(V)) {
170     const bool IsInlineAsm = CI->isInlineAsm();
171     const bool IsIndirectFunctionCall =
172         !IsInlineAsm && !CI->getCalledFunction();
173 
174     // It is possible that the call instruction is an inline asm statement or an
175     // indirect function call in which case the return value of
176     // getCalledFunction() would be nullptr.
177     const bool IsInstrinsicCall =
178         !IsInlineAsm && !IsIndirectFunctionCall &&
179         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
180 
181     if (!IsInlineAsm && !IsInstrinsicCall)
182       return CI->getCallingConv();
183   }
184 
185   return None;
186 }
187 
188 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
189                                       const SDValue *Parts, unsigned NumParts,
190                                       MVT PartVT, EVT ValueVT, const Value *V,
191                                       Optional<CallingConv::ID> CC);
192 
193 /// getCopyFromParts - Create a value that contains the specified legal parts
194 /// combined into the value they represent.  If the parts combine to a type
195 /// larger than ValueVT then AssertOp can be used to specify whether the extra
196 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
197 /// (ISD::AssertSext).
198 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
199                                 const SDValue *Parts, unsigned NumParts,
200                                 MVT PartVT, EVT ValueVT, const Value *V,
201                                 Optional<CallingConv::ID> CC = None,
202                                 Optional<ISD::NodeType> AssertOp = None) {
203   if (ValueVT.isVector())
204     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
205                                   CC);
206 
207   assert(NumParts > 0 && "No parts to assemble!");
208   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
209   SDValue Val = Parts[0];
210 
211   if (NumParts > 1) {
212     // Assemble the value from multiple parts.
213     if (ValueVT.isInteger()) {
214       unsigned PartBits = PartVT.getSizeInBits();
215       unsigned ValueBits = ValueVT.getSizeInBits();
216 
217       // Assemble the power of 2 part.
218       unsigned RoundParts = NumParts & (NumParts - 1) ?
219         1 << Log2_32(NumParts) : NumParts;
220       unsigned RoundBits = PartBits * RoundParts;
221       EVT RoundVT = RoundBits == ValueBits ?
222         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
223       SDValue Lo, Hi;
224 
225       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
226 
227       if (RoundParts > 2) {
228         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
229                               PartVT, HalfVT, V);
230         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
231                               RoundParts / 2, PartVT, HalfVT, V);
232       } else {
233         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
234         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
235       }
236 
237       if (DAG.getDataLayout().isBigEndian())
238         std::swap(Lo, Hi);
239 
240       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
241 
242       if (RoundParts < NumParts) {
243         // Assemble the trailing non-power-of-2 part.
244         unsigned OddParts = NumParts - RoundParts;
245         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
246         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
247                               OddVT, V, CC);
248 
249         // Combine the round and odd parts.
250         Lo = Val;
251         if (DAG.getDataLayout().isBigEndian())
252           std::swap(Lo, Hi);
253         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
254         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
255         Hi =
256             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
257                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
258                                         TLI.getPointerTy(DAG.getDataLayout())));
259         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
260         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
261       }
262     } else if (PartVT.isFloatingPoint()) {
263       // FP split into multiple FP parts (for ppcf128)
264       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
265              "Unexpected split");
266       SDValue Lo, Hi;
267       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
268       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
269       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
270         std::swap(Lo, Hi);
271       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
272     } else {
273       // FP split into integer parts (soft fp)
274       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
275              !PartVT.isVector() && "Unexpected split");
276       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
277       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
278     }
279   }
280 
281   // There is now one part, held in Val.  Correct it to match ValueVT.
282   // PartEVT is the type of the register class that holds the value.
283   // ValueVT is the type of the inline asm operation.
284   EVT PartEVT = Val.getValueType();
285 
286   if (PartEVT == ValueVT)
287     return Val;
288 
289   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
290       ValueVT.bitsLT(PartEVT)) {
291     // For an FP value in an integer part, we need to truncate to the right
292     // width first.
293     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
294     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
295   }
296 
297   // Handle types that have the same size.
298   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
299     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
300 
301   // Handle types with different sizes.
302   if (PartEVT.isInteger() && ValueVT.isInteger()) {
303     if (ValueVT.bitsLT(PartEVT)) {
304       // For a truncate, see if we have any information to
305       // indicate whether the truncated bits will always be
306       // zero or sign-extension.
307       if (AssertOp.hasValue())
308         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
309                           DAG.getValueType(ValueVT));
310       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
311     }
312     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
313   }
314 
315   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
316     // FP_ROUND's are always exact here.
317     if (ValueVT.bitsLT(Val.getValueType()))
318       return DAG.getNode(
319           ISD::FP_ROUND, DL, ValueVT, Val,
320           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
321 
322     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
323   }
324 
325   llvm_unreachable("Unknown mismatch!");
326 }
327 
328 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
329                                               const Twine &ErrMsg) {
330   const Instruction *I = dyn_cast_or_null<Instruction>(V);
331   if (!V)
332     return Ctx.emitError(ErrMsg);
333 
334   const char *AsmError = ", possible invalid constraint for vector type";
335   if (const CallInst *CI = dyn_cast<CallInst>(I))
336     if (isa<InlineAsm>(CI->getCalledValue()))
337       return Ctx.emitError(I, ErrMsg + AsmError);
338 
339   return Ctx.emitError(I, ErrMsg);
340 }
341 
342 /// getCopyFromPartsVector - Create a value that contains the specified legal
343 /// parts combined into the value they represent.  If the parts combine to a
344 /// type larger than ValueVT then AssertOp can be used to specify whether the
345 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
346 /// ValueVT (ISD::AssertSext).
347 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
348                                       const SDValue *Parts, unsigned NumParts,
349                                       MVT PartVT, EVT ValueVT, const Value *V,
350                                       Optional<CallingConv::ID> CallConv) {
351   assert(ValueVT.isVector() && "Not a vector value");
352   assert(NumParts > 0 && "No parts to assemble!");
353   const bool IsABIRegCopy = CallConv.hasValue();
354 
355   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
356   SDValue Val = Parts[0];
357 
358   // Handle a multi-element vector.
359   if (NumParts > 1) {
360     EVT IntermediateVT;
361     MVT RegisterVT;
362     unsigned NumIntermediates;
363     unsigned NumRegs;
364 
365     if (IsABIRegCopy) {
366       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
367           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
368           NumIntermediates, RegisterVT);
369     } else {
370       NumRegs =
371           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
372                                      NumIntermediates, RegisterVT);
373     }
374 
375     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
376     NumParts = NumRegs; // Silence a compiler warning.
377     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
378     assert(RegisterVT.getSizeInBits() ==
379            Parts[0].getSimpleValueType().getSizeInBits() &&
380            "Part type sizes don't match!");
381 
382     // Assemble the parts into intermediate operands.
383     SmallVector<SDValue, 8> Ops(NumIntermediates);
384     if (NumIntermediates == NumParts) {
385       // If the register was not expanded, truncate or copy the value,
386       // as appropriate.
387       for (unsigned i = 0; i != NumParts; ++i)
388         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
389                                   PartVT, IntermediateVT, V);
390     } else if (NumParts > 0) {
391       // If the intermediate type was expanded, build the intermediate
392       // operands from the parts.
393       assert(NumParts % NumIntermediates == 0 &&
394              "Must expand into a divisible number of parts!");
395       unsigned Factor = NumParts / NumIntermediates;
396       for (unsigned i = 0; i != NumIntermediates; ++i)
397         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
398                                   PartVT, IntermediateVT, V);
399     }
400 
401     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
402     // intermediate operands.
403     EVT BuiltVectorTy =
404         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
405                          (IntermediateVT.isVector()
406                               ? IntermediateVT.getVectorNumElements() * NumParts
407                               : NumIntermediates));
408     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
409                                                 : ISD::BUILD_VECTOR,
410                       DL, BuiltVectorTy, Ops);
411   }
412 
413   // There is now one part, held in Val.  Correct it to match ValueVT.
414   EVT PartEVT = Val.getValueType();
415 
416   if (PartEVT == ValueVT)
417     return Val;
418 
419   if (PartEVT.isVector()) {
420     // If the element type of the source/dest vectors are the same, but the
421     // parts vector has more elements than the value vector, then we have a
422     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
423     // elements we want.
424     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
425       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
426              "Cannot narrow, it would be a lossy transformation");
427       return DAG.getNode(
428           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
429           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
430     }
431 
432     // Vector/Vector bitcast.
433     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
434       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
435 
436     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
437       "Cannot handle this kind of promotion");
438     // Promoted vector extract
439     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
440 
441   }
442 
443   // Trivial bitcast if the types are the same size and the destination
444   // vector type is legal.
445   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
446       TLI.isTypeLegal(ValueVT))
447     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
448 
449   if (ValueVT.getVectorNumElements() != 1) {
450      // Certain ABIs require that vectors are passed as integers. For vectors
451      // are the same size, this is an obvious bitcast.
452      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
453        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
454      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
455        // Bitcast Val back the original type and extract the corresponding
456        // vector we want.
457        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
458        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
459                                            ValueVT.getVectorElementType(), Elts);
460        Val = DAG.getBitcast(WiderVecType, Val);
461        return DAG.getNode(
462            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
463            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
464      }
465 
466      diagnosePossiblyInvalidConstraint(
467          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
468      return DAG.getUNDEF(ValueVT);
469   }
470 
471   // Handle cases such as i8 -> <1 x i1>
472   EVT ValueSVT = ValueVT.getVectorElementType();
473   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
474     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
475                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
476 
477   return DAG.getBuildVector(ValueVT, DL, Val);
478 }
479 
480 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
481                                  SDValue Val, SDValue *Parts, unsigned NumParts,
482                                  MVT PartVT, const Value *V,
483                                  Optional<CallingConv::ID> CallConv);
484 
485 /// getCopyToParts - Create a series of nodes that contain the specified value
486 /// split into legal parts.  If the parts contain more bits than Val, then, for
487 /// integers, ExtendKind can be used to specify how to generate the extra bits.
488 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
489                            SDValue *Parts, unsigned NumParts, MVT PartVT,
490                            const Value *V,
491                            Optional<CallingConv::ID> CallConv = None,
492                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
493   EVT ValueVT = Val.getValueType();
494 
495   // Handle the vector case separately.
496   if (ValueVT.isVector())
497     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
498                                 CallConv);
499 
500   unsigned PartBits = PartVT.getSizeInBits();
501   unsigned OrigNumParts = NumParts;
502   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
503          "Copying to an illegal type!");
504 
505   if (NumParts == 0)
506     return;
507 
508   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
509   EVT PartEVT = PartVT;
510   if (PartEVT == ValueVT) {
511     assert(NumParts == 1 && "No-op copy with multiple parts!");
512     Parts[0] = Val;
513     return;
514   }
515 
516   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
517     // If the parts cover more bits than the value has, promote the value.
518     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
519       assert(NumParts == 1 && "Do not know what to promote to!");
520       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
521     } else {
522       if (ValueVT.isFloatingPoint()) {
523         // FP values need to be bitcast, then extended if they are being put
524         // into a larger container.
525         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
526         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
527       }
528       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
529              ValueVT.isInteger() &&
530              "Unknown mismatch!");
531       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
532       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
533       if (PartVT == MVT::x86mmx)
534         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
535     }
536   } else if (PartBits == ValueVT.getSizeInBits()) {
537     // Different types of the same size.
538     assert(NumParts == 1 && PartEVT != ValueVT);
539     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
540   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
541     // If the parts cover less bits than value has, truncate the value.
542     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
543            ValueVT.isInteger() &&
544            "Unknown mismatch!");
545     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
546     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
547     if (PartVT == MVT::x86mmx)
548       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
549   }
550 
551   // The value may have changed - recompute ValueVT.
552   ValueVT = Val.getValueType();
553   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
554          "Failed to tile the value with PartVT!");
555 
556   if (NumParts == 1) {
557     if (PartEVT != ValueVT) {
558       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
559                                         "scalar-to-vector conversion failed");
560       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
561     }
562 
563     Parts[0] = Val;
564     return;
565   }
566 
567   // Expand the value into multiple parts.
568   if (NumParts & (NumParts - 1)) {
569     // The number of parts is not a power of 2.  Split off and copy the tail.
570     assert(PartVT.isInteger() && ValueVT.isInteger() &&
571            "Do not know what to expand to!");
572     unsigned RoundParts = 1 << Log2_32(NumParts);
573     unsigned RoundBits = RoundParts * PartBits;
574     unsigned OddParts = NumParts - RoundParts;
575     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
576                                  DAG.getIntPtrConstant(RoundBits, DL));
577     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
578                    CallConv);
579 
580     if (DAG.getDataLayout().isBigEndian())
581       // The odd parts were reversed by getCopyToParts - unreverse them.
582       std::reverse(Parts + RoundParts, Parts + NumParts);
583 
584     NumParts = RoundParts;
585     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
586     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
587   }
588 
589   // The number of parts is a power of 2.  Repeatedly bisect the value using
590   // EXTRACT_ELEMENT.
591   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
592                          EVT::getIntegerVT(*DAG.getContext(),
593                                            ValueVT.getSizeInBits()),
594                          Val);
595 
596   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
597     for (unsigned i = 0; i < NumParts; i += StepSize) {
598       unsigned ThisBits = StepSize * PartBits / 2;
599       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
600       SDValue &Part0 = Parts[i];
601       SDValue &Part1 = Parts[i+StepSize/2];
602 
603       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
604                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
605       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
606                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
607 
608       if (ThisBits == PartBits && ThisVT != PartVT) {
609         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
610         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
611       }
612     }
613   }
614 
615   if (DAG.getDataLayout().isBigEndian())
616     std::reverse(Parts, Parts + OrigNumParts);
617 }
618 
619 static SDValue widenVectorToPartType(SelectionDAG &DAG,
620                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
621   if (!PartVT.isVector())
622     return SDValue();
623 
624   EVT ValueVT = Val.getValueType();
625   unsigned PartNumElts = PartVT.getVectorNumElements();
626   unsigned ValueNumElts = ValueVT.getVectorNumElements();
627   if (PartNumElts > ValueNumElts &&
628       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
629     EVT ElementVT = PartVT.getVectorElementType();
630     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
631     // undef elements.
632     SmallVector<SDValue, 16> Ops;
633     DAG.ExtractVectorElements(Val, Ops);
634     SDValue EltUndef = DAG.getUNDEF(ElementVT);
635     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
636       Ops.push_back(EltUndef);
637 
638     // FIXME: Use CONCAT for 2x -> 4x.
639     return DAG.getBuildVector(PartVT, DL, Ops);
640   }
641 
642   return SDValue();
643 }
644 
645 /// getCopyToPartsVector - Create a series of nodes that contain the specified
646 /// value split into legal parts.
647 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
648                                  SDValue Val, SDValue *Parts, unsigned NumParts,
649                                  MVT PartVT, const Value *V,
650                                  Optional<CallingConv::ID> CallConv) {
651   EVT ValueVT = Val.getValueType();
652   assert(ValueVT.isVector() && "Not a vector");
653   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
654   const bool IsABIRegCopy = CallConv.hasValue();
655 
656   if (NumParts == 1) {
657     EVT PartEVT = PartVT;
658     if (PartEVT == ValueVT) {
659       // Nothing to do.
660     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
661       // Bitconvert vector->vector case.
662       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
663     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
664       Val = Widened;
665     } else if (PartVT.isVector() &&
666                PartEVT.getVectorElementType().bitsGE(
667                  ValueVT.getVectorElementType()) &&
668                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
669 
670       // Promoted vector extract
671       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
672     } else {
673       if (ValueVT.getVectorNumElements() == 1) {
674         Val = DAG.getNode(
675             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
676             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
677       } else {
678         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
679                "lossy conversion of vector to scalar type");
680         EVT IntermediateType =
681             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
682         Val = DAG.getBitcast(IntermediateType, Val);
683         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
684       }
685     }
686 
687     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
688     Parts[0] = Val;
689     return;
690   }
691 
692   // Handle a multi-element vector.
693   EVT IntermediateVT;
694   MVT RegisterVT;
695   unsigned NumIntermediates;
696   unsigned NumRegs;
697   if (IsABIRegCopy) {
698     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
699         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
700         NumIntermediates, RegisterVT);
701   } else {
702     NumRegs =
703         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
704                                    NumIntermediates, RegisterVT);
705   }
706 
707   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
708   NumParts = NumRegs; // Silence a compiler warning.
709   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
710 
711   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
712     IntermediateVT.getVectorNumElements() : 1;
713 
714   // Convert the vector to the appropiate type if necessary.
715   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
716 
717   EVT BuiltVectorTy = EVT::getVectorVT(
718       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
719   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
720   if (ValueVT != BuiltVectorTy) {
721     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
722       Val = Widened;
723 
724     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
725   }
726 
727   // Split the vector into intermediate operands.
728   SmallVector<SDValue, 8> Ops(NumIntermediates);
729   for (unsigned i = 0; i != NumIntermediates; ++i) {
730     if (IntermediateVT.isVector()) {
731       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
732                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
733     } else {
734       Ops[i] = DAG.getNode(
735           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
736           DAG.getConstant(i, DL, IdxVT));
737     }
738   }
739 
740   // Split the intermediate operands into legal parts.
741   if (NumParts == NumIntermediates) {
742     // If the register was not expanded, promote or copy the value,
743     // as appropriate.
744     for (unsigned i = 0; i != NumParts; ++i)
745       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
746   } else if (NumParts > 0) {
747     // If the intermediate type was expanded, split each the value into
748     // legal parts.
749     assert(NumIntermediates != 0 && "division by zero");
750     assert(NumParts % NumIntermediates == 0 &&
751            "Must expand into a divisible number of parts!");
752     unsigned Factor = NumParts / NumIntermediates;
753     for (unsigned i = 0; i != NumIntermediates; ++i)
754       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
755                      CallConv);
756   }
757 }
758 
759 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
760                            EVT valuevt, Optional<CallingConv::ID> CC)
761     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
762       RegCount(1, regs.size()), CallConv(CC) {}
763 
764 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
765                            const DataLayout &DL, unsigned Reg, Type *Ty,
766                            Optional<CallingConv::ID> CC) {
767   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
768 
769   CallConv = CC;
770 
771   for (EVT ValueVT : ValueVTs) {
772     unsigned NumRegs =
773         isABIMangled()
774             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
775             : TLI.getNumRegisters(Context, ValueVT);
776     MVT RegisterVT =
777         isABIMangled()
778             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
779             : TLI.getRegisterType(Context, ValueVT);
780     for (unsigned i = 0; i != NumRegs; ++i)
781       Regs.push_back(Reg + i);
782     RegVTs.push_back(RegisterVT);
783     RegCount.push_back(NumRegs);
784     Reg += NumRegs;
785   }
786 }
787 
788 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
789                                       FunctionLoweringInfo &FuncInfo,
790                                       const SDLoc &dl, SDValue &Chain,
791                                       SDValue *Flag, const Value *V) const {
792   // A Value with type {} or [0 x %t] needs no registers.
793   if (ValueVTs.empty())
794     return SDValue();
795 
796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
797 
798   // Assemble the legal parts into the final values.
799   SmallVector<SDValue, 4> Values(ValueVTs.size());
800   SmallVector<SDValue, 8> Parts;
801   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
802     // Copy the legal parts from the registers.
803     EVT ValueVT = ValueVTs[Value];
804     unsigned NumRegs = RegCount[Value];
805     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
806                                           *DAG.getContext(),
807                                           CallConv.getValue(), RegVTs[Value])
808                                     : RegVTs[Value];
809 
810     Parts.resize(NumRegs);
811     for (unsigned i = 0; i != NumRegs; ++i) {
812       SDValue P;
813       if (!Flag) {
814         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
815       } else {
816         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
817         *Flag = P.getValue(2);
818       }
819 
820       Chain = P.getValue(1);
821       Parts[i] = P;
822 
823       // If the source register was virtual and if we know something about it,
824       // add an assert node.
825       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
826           !RegisterVT.isInteger() || RegisterVT.isVector())
827         continue;
828 
829       const FunctionLoweringInfo::LiveOutInfo *LOI =
830         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
831       if (!LOI)
832         continue;
833 
834       unsigned RegSize = RegisterVT.getSizeInBits();
835       unsigned NumSignBits = LOI->NumSignBits;
836       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
837 
838       if (NumZeroBits == RegSize) {
839         // The current value is a zero.
840         // Explicitly express that as it would be easier for
841         // optimizations to kick in.
842         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
843         continue;
844       }
845 
846       // FIXME: We capture more information than the dag can represent.  For
847       // now, just use the tightest assertzext/assertsext possible.
848       bool isSExt;
849       EVT FromVT(MVT::Other);
850       if (NumZeroBits) {
851         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
852         isSExt = false;
853       } else if (NumSignBits > 1) {
854         FromVT =
855             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
856         isSExt = true;
857       } else {
858         continue;
859       }
860       // Add an assertion node.
861       assert(FromVT != MVT::Other);
862       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
863                              RegisterVT, P, DAG.getValueType(FromVT));
864     }
865 
866     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
867                                      RegisterVT, ValueVT, V, CallConv);
868     Part += NumRegs;
869     Parts.clear();
870   }
871 
872   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
873 }
874 
875 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
876                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
877                                  const Value *V,
878                                  ISD::NodeType PreferredExtendType) const {
879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
880   ISD::NodeType ExtendKind = PreferredExtendType;
881 
882   // Get the list of the values's legal parts.
883   unsigned NumRegs = Regs.size();
884   SmallVector<SDValue, 8> Parts(NumRegs);
885   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
886     unsigned NumParts = RegCount[Value];
887 
888     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
889                                           *DAG.getContext(),
890                                           CallConv.getValue(), RegVTs[Value])
891                                     : RegVTs[Value];
892 
893     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
894       ExtendKind = ISD::ZERO_EXTEND;
895 
896     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
897                    NumParts, RegisterVT, V, CallConv, ExtendKind);
898     Part += NumParts;
899   }
900 
901   // Copy the parts into the registers.
902   SmallVector<SDValue, 8> Chains(NumRegs);
903   for (unsigned i = 0; i != NumRegs; ++i) {
904     SDValue Part;
905     if (!Flag) {
906       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
907     } else {
908       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
909       *Flag = Part.getValue(1);
910     }
911 
912     Chains[i] = Part.getValue(0);
913   }
914 
915   if (NumRegs == 1 || Flag)
916     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
917     // flagged to it. That is the CopyToReg nodes and the user are considered
918     // a single scheduling unit. If we create a TokenFactor and return it as
919     // chain, then the TokenFactor is both a predecessor (operand) of the
920     // user as well as a successor (the TF operands are flagged to the user).
921     // c1, f1 = CopyToReg
922     // c2, f2 = CopyToReg
923     // c3     = TokenFactor c1, c2
924     // ...
925     //        = op c3, ..., f2
926     Chain = Chains[NumRegs-1];
927   else
928     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
929 }
930 
931 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
932                                         unsigned MatchingIdx, const SDLoc &dl,
933                                         SelectionDAG &DAG,
934                                         std::vector<SDValue> &Ops) const {
935   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
936 
937   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
938   if (HasMatching)
939     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
940   else if (!Regs.empty() &&
941            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
942     // Put the register class of the virtual registers in the flag word.  That
943     // way, later passes can recompute register class constraints for inline
944     // assembly as well as normal instructions.
945     // Don't do this for tied operands that can use the regclass information
946     // from the def.
947     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
948     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
949     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
950   }
951 
952   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
953   Ops.push_back(Res);
954 
955   if (Code == InlineAsm::Kind_Clobber) {
956     // Clobbers should always have a 1:1 mapping with registers, and may
957     // reference registers that have illegal (e.g. vector) types. Hence, we
958     // shouldn't try to apply any sort of splitting logic to them.
959     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
960            "No 1:1 mapping from clobbers to regs?");
961     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
962     (void)SP;
963     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
964       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
965       assert(
966           (Regs[I] != SP ||
967            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
968           "If we clobbered the stack pointer, MFI should know about it.");
969     }
970     return;
971   }
972 
973   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
974     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
975     MVT RegisterVT = RegVTs[Value];
976     for (unsigned i = 0; i != NumRegs; ++i) {
977       assert(Reg < Regs.size() && "Mismatch in # registers expected");
978       unsigned TheReg = Regs[Reg++];
979       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
980     }
981   }
982 }
983 
984 SmallVector<std::pair<unsigned, unsigned>, 4>
985 RegsForValue::getRegsAndSizes() const {
986   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
987   unsigned I = 0;
988   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
989     unsigned RegCount = std::get<0>(CountAndVT);
990     MVT RegisterVT = std::get<1>(CountAndVT);
991     unsigned RegisterSize = RegisterVT.getSizeInBits();
992     for (unsigned E = I + RegCount; I != E; ++I)
993       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
994   }
995   return OutVec;
996 }
997 
998 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
999                                const TargetLibraryInfo *li) {
1000   AA = aa;
1001   GFI = gfi;
1002   LibInfo = li;
1003   DL = &DAG.getDataLayout();
1004   Context = DAG.getContext();
1005   LPadToCallSiteMap.clear();
1006 }
1007 
1008 void SelectionDAGBuilder::clear() {
1009   NodeMap.clear();
1010   UnusedArgNodeMap.clear();
1011   PendingLoads.clear();
1012   PendingExports.clear();
1013   CurInst = nullptr;
1014   HasTailCall = false;
1015   SDNodeOrder = LowestSDNodeOrder;
1016   StatepointLowering.clear();
1017 }
1018 
1019 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1020   DanglingDebugInfoMap.clear();
1021 }
1022 
1023 SDValue SelectionDAGBuilder::getRoot() {
1024   if (PendingLoads.empty())
1025     return DAG.getRoot();
1026 
1027   if (PendingLoads.size() == 1) {
1028     SDValue Root = PendingLoads[0];
1029     DAG.setRoot(Root);
1030     PendingLoads.clear();
1031     return Root;
1032   }
1033 
1034   // Otherwise, we have to make a token factor node.
1035   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1036                              PendingLoads);
1037   PendingLoads.clear();
1038   DAG.setRoot(Root);
1039   return Root;
1040 }
1041 
1042 SDValue SelectionDAGBuilder::getControlRoot() {
1043   SDValue Root = DAG.getRoot();
1044 
1045   if (PendingExports.empty())
1046     return Root;
1047 
1048   // Turn all of the CopyToReg chains into one factored node.
1049   if (Root.getOpcode() != ISD::EntryToken) {
1050     unsigned i = 0, e = PendingExports.size();
1051     for (; i != e; ++i) {
1052       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1053       if (PendingExports[i].getNode()->getOperand(0) == Root)
1054         break;  // Don't add the root if we already indirectly depend on it.
1055     }
1056 
1057     if (i == e)
1058       PendingExports.push_back(Root);
1059   }
1060 
1061   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1062                      PendingExports);
1063   PendingExports.clear();
1064   DAG.setRoot(Root);
1065   return Root;
1066 }
1067 
1068 void SelectionDAGBuilder::visit(const Instruction &I) {
1069   // Set up outgoing PHI node register values before emitting the terminator.
1070   if (I.isTerminator()) {
1071     HandlePHINodesInSuccessorBlocks(I.getParent());
1072   }
1073 
1074   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1075   if (!isa<DbgInfoIntrinsic>(I))
1076     ++SDNodeOrder;
1077 
1078   CurInst = &I;
1079 
1080   visit(I.getOpcode(), I);
1081 
1082   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1083     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1084     // maps to this instruction.
1085     // TODO: We could handle all flags (nsw, etc) here.
1086     // TODO: If an IR instruction maps to >1 node, only the final node will have
1087     //       flags set.
1088     if (SDNode *Node = getNodeForIRValue(&I)) {
1089       SDNodeFlags IncomingFlags;
1090       IncomingFlags.copyFMF(*FPMO);
1091       if (!Node->getFlags().isDefined())
1092         Node->setFlags(IncomingFlags);
1093       else
1094         Node->intersectFlagsWith(IncomingFlags);
1095     }
1096   }
1097 
1098   if (!I.isTerminator() && !HasTailCall &&
1099       !isStatepoint(&I)) // statepoints handle their exports internally
1100     CopyToExportRegsIfNeeded(&I);
1101 
1102   CurInst = nullptr;
1103 }
1104 
1105 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1106   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1107 }
1108 
1109 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1110   // Note: this doesn't use InstVisitor, because it has to work with
1111   // ConstantExpr's in addition to instructions.
1112   switch (Opcode) {
1113   default: llvm_unreachable("Unknown instruction type encountered!");
1114     // Build the switch statement using the Instruction.def file.
1115 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1116     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1117 #include "llvm/IR/Instruction.def"
1118   }
1119 }
1120 
1121 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1122                                                 const DIExpression *Expr) {
1123   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1124     const DbgValueInst *DI = DDI.getDI();
1125     DIVariable *DanglingVariable = DI->getVariable();
1126     DIExpression *DanglingExpr = DI->getExpression();
1127     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1128       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1129       return true;
1130     }
1131     return false;
1132   };
1133 
1134   for (auto &DDIMI : DanglingDebugInfoMap) {
1135     DanglingDebugInfoVector &DDIV = DDIMI.second;
1136     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1137   }
1138 }
1139 
1140 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1141 // generate the debug data structures now that we've seen its definition.
1142 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1143                                                    SDValue Val) {
1144   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1145   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1146     return;
1147 
1148   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1149   for (auto &DDI : DDIV) {
1150     const DbgValueInst *DI = DDI.getDI();
1151     assert(DI && "Ill-formed DanglingDebugInfo");
1152     DebugLoc dl = DDI.getdl();
1153     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1154     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1155     DILocalVariable *Variable = DI->getVariable();
1156     DIExpression *Expr = DI->getExpression();
1157     assert(Variable->isValidLocationForIntrinsic(dl) &&
1158            "Expected inlined-at fields to agree");
1159     SDDbgValue *SDV;
1160     if (Val.getNode()) {
1161       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1162         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1163                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1164         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1165         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1166         // inserted after the definition of Val when emitting the instructions
1167         // after ISel. An alternative could be to teach
1168         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1169         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1170                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1171                    << ValSDNodeOrder << "\n");
1172         SDV = getDbgValue(Val, Variable, Expr, dl,
1173                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1174         DAG.AddDbgValue(SDV, Val.getNode(), false);
1175       } else
1176         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1177                           << "in EmitFuncArgumentDbgValue\n");
1178     } else
1179       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1180   }
1181   DDIV.clear();
1182 }
1183 
1184 /// getCopyFromRegs - If there was virtual register allocated for the value V
1185 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1186 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1187   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1188   SDValue Result;
1189 
1190   if (It != FuncInfo.ValueMap.end()) {
1191     unsigned InReg = It->second;
1192 
1193     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1194                      DAG.getDataLayout(), InReg, Ty,
1195                      None); // This is not an ABI copy.
1196     SDValue Chain = DAG.getEntryNode();
1197     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1198                                  V);
1199     resolveDanglingDebugInfo(V, Result);
1200   }
1201 
1202   return Result;
1203 }
1204 
1205 /// getValue - Return an SDValue for the given Value.
1206 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1207   // If we already have an SDValue for this value, use it. It's important
1208   // to do this first, so that we don't create a CopyFromReg if we already
1209   // have a regular SDValue.
1210   SDValue &N = NodeMap[V];
1211   if (N.getNode()) return N;
1212 
1213   // If there's a virtual register allocated and initialized for this
1214   // value, use it.
1215   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1216     return copyFromReg;
1217 
1218   // Otherwise create a new SDValue and remember it.
1219   SDValue Val = getValueImpl(V);
1220   NodeMap[V] = Val;
1221   resolveDanglingDebugInfo(V, Val);
1222   return Val;
1223 }
1224 
1225 // Return true if SDValue exists for the given Value
1226 bool SelectionDAGBuilder::findValue(const Value *V) const {
1227   return (NodeMap.find(V) != NodeMap.end()) ||
1228     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1229 }
1230 
1231 /// getNonRegisterValue - Return an SDValue for the given Value, but
1232 /// don't look in FuncInfo.ValueMap for a virtual register.
1233 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1234   // If we already have an SDValue for this value, use it.
1235   SDValue &N = NodeMap[V];
1236   if (N.getNode()) {
1237     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1238       // Remove the debug location from the node as the node is about to be used
1239       // in a location which may differ from the original debug location.  This
1240       // is relevant to Constant and ConstantFP nodes because they can appear
1241       // as constant expressions inside PHI nodes.
1242       N->setDebugLoc(DebugLoc());
1243     }
1244     return N;
1245   }
1246 
1247   // Otherwise create a new SDValue and remember it.
1248   SDValue Val = getValueImpl(V);
1249   NodeMap[V] = Val;
1250   resolveDanglingDebugInfo(V, Val);
1251   return Val;
1252 }
1253 
1254 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1255 /// Create an SDValue for the given value.
1256 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1257   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1258 
1259   if (const Constant *C = dyn_cast<Constant>(V)) {
1260     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1261 
1262     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1263       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1264 
1265     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1266       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1267 
1268     if (isa<ConstantPointerNull>(C)) {
1269       unsigned AS = V->getType()->getPointerAddressSpace();
1270       return DAG.getConstant(0, getCurSDLoc(),
1271                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1272     }
1273 
1274     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1275       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1276 
1277     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1278       return DAG.getUNDEF(VT);
1279 
1280     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1281       visit(CE->getOpcode(), *CE);
1282       SDValue N1 = NodeMap[V];
1283       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1284       return N1;
1285     }
1286 
1287     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1288       SmallVector<SDValue, 4> Constants;
1289       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1290            OI != OE; ++OI) {
1291         SDNode *Val = getValue(*OI).getNode();
1292         // If the operand is an empty aggregate, there are no values.
1293         if (!Val) continue;
1294         // Add each leaf value from the operand to the Constants list
1295         // to form a flattened list of all the values.
1296         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1297           Constants.push_back(SDValue(Val, i));
1298       }
1299 
1300       return DAG.getMergeValues(Constants, getCurSDLoc());
1301     }
1302 
1303     if (const ConstantDataSequential *CDS =
1304           dyn_cast<ConstantDataSequential>(C)) {
1305       SmallVector<SDValue, 4> Ops;
1306       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1307         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1308         // Add each leaf value from the operand to the Constants list
1309         // to form a flattened list of all the values.
1310         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1311           Ops.push_back(SDValue(Val, i));
1312       }
1313 
1314       if (isa<ArrayType>(CDS->getType()))
1315         return DAG.getMergeValues(Ops, getCurSDLoc());
1316       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1317     }
1318 
1319     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1320       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1321              "Unknown struct or array constant!");
1322 
1323       SmallVector<EVT, 4> ValueVTs;
1324       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1325       unsigned NumElts = ValueVTs.size();
1326       if (NumElts == 0)
1327         return SDValue(); // empty struct
1328       SmallVector<SDValue, 4> Constants(NumElts);
1329       for (unsigned i = 0; i != NumElts; ++i) {
1330         EVT EltVT = ValueVTs[i];
1331         if (isa<UndefValue>(C))
1332           Constants[i] = DAG.getUNDEF(EltVT);
1333         else if (EltVT.isFloatingPoint())
1334           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1335         else
1336           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1337       }
1338 
1339       return DAG.getMergeValues(Constants, getCurSDLoc());
1340     }
1341 
1342     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1343       return DAG.getBlockAddress(BA, VT);
1344 
1345     VectorType *VecTy = cast<VectorType>(V->getType());
1346     unsigned NumElements = VecTy->getNumElements();
1347 
1348     // Now that we know the number and type of the elements, get that number of
1349     // elements into the Ops array based on what kind of constant it is.
1350     SmallVector<SDValue, 16> Ops;
1351     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1352       for (unsigned i = 0; i != NumElements; ++i)
1353         Ops.push_back(getValue(CV->getOperand(i)));
1354     } else {
1355       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1356       EVT EltVT =
1357           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1358 
1359       SDValue Op;
1360       if (EltVT.isFloatingPoint())
1361         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1362       else
1363         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1364       Ops.assign(NumElements, Op);
1365     }
1366 
1367     // Create a BUILD_VECTOR node.
1368     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1369   }
1370 
1371   // If this is a static alloca, generate it as the frameindex instead of
1372   // computation.
1373   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1374     DenseMap<const AllocaInst*, int>::iterator SI =
1375       FuncInfo.StaticAllocaMap.find(AI);
1376     if (SI != FuncInfo.StaticAllocaMap.end())
1377       return DAG.getFrameIndex(SI->second,
1378                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1379   }
1380 
1381   // If this is an instruction which fast-isel has deferred, select it now.
1382   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1383     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1384 
1385     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1386                      Inst->getType(), getABIRegCopyCC(V));
1387     SDValue Chain = DAG.getEntryNode();
1388     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1389   }
1390 
1391   llvm_unreachable("Can't get register for value!");
1392 }
1393 
1394 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1395   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1396   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1397   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1398   bool IsSEH = isAsynchronousEHPersonality(Pers);
1399   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1400   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1401   if (!IsSEH)
1402     CatchPadMBB->setIsEHScopeEntry();
1403   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1404   if (IsMSVCCXX || IsCoreCLR)
1405     CatchPadMBB->setIsEHFuncletEntry();
1406   // Wasm does not need catchpads anymore
1407   if (!IsWasmCXX)
1408     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1409                             getControlRoot()));
1410 }
1411 
1412 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1413   // Update machine-CFG edge.
1414   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1415   FuncInfo.MBB->addSuccessor(TargetMBB);
1416 
1417   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1418   bool IsSEH = isAsynchronousEHPersonality(Pers);
1419   if (IsSEH) {
1420     // If this is not a fall-through branch or optimizations are switched off,
1421     // emit the branch.
1422     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1423         TM.getOptLevel() == CodeGenOpt::None)
1424       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1425                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1426     return;
1427   }
1428 
1429   // Figure out the funclet membership for the catchret's successor.
1430   // This will be used by the FuncletLayout pass to determine how to order the
1431   // BB's.
1432   // A 'catchret' returns to the outer scope's color.
1433   Value *ParentPad = I.getCatchSwitchParentPad();
1434   const BasicBlock *SuccessorColor;
1435   if (isa<ConstantTokenNone>(ParentPad))
1436     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1437   else
1438     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1439   assert(SuccessorColor && "No parent funclet for catchret!");
1440   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1441   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1442 
1443   // Create the terminator node.
1444   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1445                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1446                             DAG.getBasicBlock(SuccessorColorMBB));
1447   DAG.setRoot(Ret);
1448 }
1449 
1450 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1451   // Don't emit any special code for the cleanuppad instruction. It just marks
1452   // the start of an EH scope/funclet.
1453   FuncInfo.MBB->setIsEHScopeEntry();
1454   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1455   if (Pers != EHPersonality::Wasm_CXX) {
1456     FuncInfo.MBB->setIsEHFuncletEntry();
1457     FuncInfo.MBB->setIsCleanupFuncletEntry();
1458   }
1459 }
1460 
1461 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1462 /// many places it could ultimately go. In the IR, we have a single unwind
1463 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1464 /// This function skips over imaginary basic blocks that hold catchswitch
1465 /// instructions, and finds all the "real" machine
1466 /// basic block destinations. As those destinations may not be successors of
1467 /// EHPadBB, here we also calculate the edge probability to those destinations.
1468 /// The passed-in Prob is the edge probability to EHPadBB.
1469 static void findUnwindDestinations(
1470     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1471     BranchProbability Prob,
1472     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1473         &UnwindDests) {
1474   EHPersonality Personality =
1475     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1476   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1477   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1478   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1479   bool IsSEH = isAsynchronousEHPersonality(Personality);
1480 
1481   while (EHPadBB) {
1482     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1483     BasicBlock *NewEHPadBB = nullptr;
1484     if (isa<LandingPadInst>(Pad)) {
1485       // Stop on landingpads. They are not funclets.
1486       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1487       break;
1488     } else if (isa<CleanupPadInst>(Pad)) {
1489       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1490       // personalities.
1491       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1492       UnwindDests.back().first->setIsEHScopeEntry();
1493       if (!IsWasmCXX)
1494         UnwindDests.back().first->setIsEHFuncletEntry();
1495       break;
1496     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1497       // Add the catchpad handlers to the possible destinations.
1498       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1499         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1500         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1501         if (IsMSVCCXX || IsCoreCLR)
1502           UnwindDests.back().first->setIsEHFuncletEntry();
1503         if (!IsSEH)
1504           UnwindDests.back().first->setIsEHScopeEntry();
1505       }
1506       NewEHPadBB = CatchSwitch->getUnwindDest();
1507     } else {
1508       continue;
1509     }
1510 
1511     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1512     if (BPI && NewEHPadBB)
1513       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1514     EHPadBB = NewEHPadBB;
1515   }
1516 }
1517 
1518 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1519   // Update successor info.
1520   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1521   auto UnwindDest = I.getUnwindDest();
1522   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1523   BranchProbability UnwindDestProb =
1524       (BPI && UnwindDest)
1525           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1526           : BranchProbability::getZero();
1527   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1528   for (auto &UnwindDest : UnwindDests) {
1529     UnwindDest.first->setIsEHPad();
1530     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1531   }
1532   FuncInfo.MBB->normalizeSuccProbs();
1533 
1534   // Create the terminator node.
1535   SDValue Ret =
1536       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1537   DAG.setRoot(Ret);
1538 }
1539 
1540 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1541   report_fatal_error("visitCatchSwitch not yet implemented!");
1542 }
1543 
1544 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1545   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1546   auto &DL = DAG.getDataLayout();
1547   SDValue Chain = getControlRoot();
1548   SmallVector<ISD::OutputArg, 8> Outs;
1549   SmallVector<SDValue, 8> OutVals;
1550 
1551   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1552   // lower
1553   //
1554   //   %val = call <ty> @llvm.experimental.deoptimize()
1555   //   ret <ty> %val
1556   //
1557   // differently.
1558   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1559     LowerDeoptimizingReturn();
1560     return;
1561   }
1562 
1563   if (!FuncInfo.CanLowerReturn) {
1564     unsigned DemoteReg = FuncInfo.DemoteRegister;
1565     const Function *F = I.getParent()->getParent();
1566 
1567     // Emit a store of the return value through the virtual register.
1568     // Leave Outs empty so that LowerReturn won't try to load return
1569     // registers the usual way.
1570     SmallVector<EVT, 1> PtrValueVTs;
1571     ComputeValueVTs(TLI, DL,
1572                     F->getReturnType()->getPointerTo(
1573                         DAG.getDataLayout().getAllocaAddrSpace()),
1574                     PtrValueVTs);
1575 
1576     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1577                                         DemoteReg, PtrValueVTs[0]);
1578     SDValue RetOp = getValue(I.getOperand(0));
1579 
1580     SmallVector<EVT, 4> ValueVTs;
1581     SmallVector<uint64_t, 4> Offsets;
1582     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1583     unsigned NumValues = ValueVTs.size();
1584 
1585     SmallVector<SDValue, 4> Chains(NumValues);
1586     for (unsigned i = 0; i != NumValues; ++i) {
1587       // An aggregate return value cannot wrap around the address space, so
1588       // offsets to its parts don't wrap either.
1589       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1590       Chains[i] = DAG.getStore(
1591           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1592           // FIXME: better loc info would be nice.
1593           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1594     }
1595 
1596     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1597                         MVT::Other, Chains);
1598   } else if (I.getNumOperands() != 0) {
1599     SmallVector<EVT, 4> ValueVTs;
1600     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1601     unsigned NumValues = ValueVTs.size();
1602     if (NumValues) {
1603       SDValue RetOp = getValue(I.getOperand(0));
1604 
1605       const Function *F = I.getParent()->getParent();
1606 
1607       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1608       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1609                                           Attribute::SExt))
1610         ExtendKind = ISD::SIGN_EXTEND;
1611       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1612                                                Attribute::ZExt))
1613         ExtendKind = ISD::ZERO_EXTEND;
1614 
1615       LLVMContext &Context = F->getContext();
1616       bool RetInReg = F->getAttributes().hasAttribute(
1617           AttributeList::ReturnIndex, Attribute::InReg);
1618 
1619       for (unsigned j = 0; j != NumValues; ++j) {
1620         EVT VT = ValueVTs[j];
1621 
1622         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1623           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1624 
1625         CallingConv::ID CC = F->getCallingConv();
1626 
1627         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1628         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1629         SmallVector<SDValue, 4> Parts(NumParts);
1630         getCopyToParts(DAG, getCurSDLoc(),
1631                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1632                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1633 
1634         // 'inreg' on function refers to return value
1635         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1636         if (RetInReg)
1637           Flags.setInReg();
1638 
1639         // Propagate extension type if any
1640         if (ExtendKind == ISD::SIGN_EXTEND)
1641           Flags.setSExt();
1642         else if (ExtendKind == ISD::ZERO_EXTEND)
1643           Flags.setZExt();
1644 
1645         for (unsigned i = 0; i < NumParts; ++i) {
1646           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1647                                         VT, /*isfixed=*/true, 0, 0));
1648           OutVals.push_back(Parts[i]);
1649         }
1650       }
1651     }
1652   }
1653 
1654   // Push in swifterror virtual register as the last element of Outs. This makes
1655   // sure swifterror virtual register will be returned in the swifterror
1656   // physical register.
1657   const Function *F = I.getParent()->getParent();
1658   if (TLI.supportSwiftError() &&
1659       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1660     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1661     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1662     Flags.setSwiftError();
1663     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1664                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1665                                   true /*isfixed*/, 1 /*origidx*/,
1666                                   0 /*partOffs*/));
1667     // Create SDNode for the swifterror virtual register.
1668     OutVals.push_back(
1669         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1670                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1671                         EVT(TLI.getPointerTy(DL))));
1672   }
1673 
1674   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1675   CallingConv::ID CallConv =
1676     DAG.getMachineFunction().getFunction().getCallingConv();
1677   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1678       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1679 
1680   // Verify that the target's LowerReturn behaved as expected.
1681   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1682          "LowerReturn didn't return a valid chain!");
1683 
1684   // Update the DAG with the new chain value resulting from return lowering.
1685   DAG.setRoot(Chain);
1686 }
1687 
1688 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1689 /// created for it, emit nodes to copy the value into the virtual
1690 /// registers.
1691 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1692   // Skip empty types
1693   if (V->getType()->isEmptyTy())
1694     return;
1695 
1696   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1697   if (VMI != FuncInfo.ValueMap.end()) {
1698     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1699     CopyValueToVirtualRegister(V, VMI->second);
1700   }
1701 }
1702 
1703 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1704 /// the current basic block, add it to ValueMap now so that we'll get a
1705 /// CopyTo/FromReg.
1706 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1707   // No need to export constants.
1708   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1709 
1710   // Already exported?
1711   if (FuncInfo.isExportedInst(V)) return;
1712 
1713   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1714   CopyValueToVirtualRegister(V, Reg);
1715 }
1716 
1717 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1718                                                      const BasicBlock *FromBB) {
1719   // The operands of the setcc have to be in this block.  We don't know
1720   // how to export them from some other block.
1721   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1722     // Can export from current BB.
1723     if (VI->getParent() == FromBB)
1724       return true;
1725 
1726     // Is already exported, noop.
1727     return FuncInfo.isExportedInst(V);
1728   }
1729 
1730   // If this is an argument, we can export it if the BB is the entry block or
1731   // if it is already exported.
1732   if (isa<Argument>(V)) {
1733     if (FromBB == &FromBB->getParent()->getEntryBlock())
1734       return true;
1735 
1736     // Otherwise, can only export this if it is already exported.
1737     return FuncInfo.isExportedInst(V);
1738   }
1739 
1740   // Otherwise, constants can always be exported.
1741   return true;
1742 }
1743 
1744 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1745 BranchProbability
1746 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1747                                         const MachineBasicBlock *Dst) const {
1748   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1749   const BasicBlock *SrcBB = Src->getBasicBlock();
1750   const BasicBlock *DstBB = Dst->getBasicBlock();
1751   if (!BPI) {
1752     // If BPI is not available, set the default probability as 1 / N, where N is
1753     // the number of successors.
1754     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1755     return BranchProbability(1, SuccSize);
1756   }
1757   return BPI->getEdgeProbability(SrcBB, DstBB);
1758 }
1759 
1760 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1761                                                MachineBasicBlock *Dst,
1762                                                BranchProbability Prob) {
1763   if (!FuncInfo.BPI)
1764     Src->addSuccessorWithoutProb(Dst);
1765   else {
1766     if (Prob.isUnknown())
1767       Prob = getEdgeProbability(Src, Dst);
1768     Src->addSuccessor(Dst, Prob);
1769   }
1770 }
1771 
1772 static bool InBlock(const Value *V, const BasicBlock *BB) {
1773   if (const Instruction *I = dyn_cast<Instruction>(V))
1774     return I->getParent() == BB;
1775   return true;
1776 }
1777 
1778 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1779 /// This function emits a branch and is used at the leaves of an OR or an
1780 /// AND operator tree.
1781 void
1782 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1783                                                   MachineBasicBlock *TBB,
1784                                                   MachineBasicBlock *FBB,
1785                                                   MachineBasicBlock *CurBB,
1786                                                   MachineBasicBlock *SwitchBB,
1787                                                   BranchProbability TProb,
1788                                                   BranchProbability FProb,
1789                                                   bool InvertCond) {
1790   const BasicBlock *BB = CurBB->getBasicBlock();
1791 
1792   // If the leaf of the tree is a comparison, merge the condition into
1793   // the caseblock.
1794   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1795     // The operands of the cmp have to be in this block.  We don't know
1796     // how to export them from some other block.  If this is the first block
1797     // of the sequence, no exporting is needed.
1798     if (CurBB == SwitchBB ||
1799         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1800          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1801       ISD::CondCode Condition;
1802       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1803         ICmpInst::Predicate Pred =
1804             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1805         Condition = getICmpCondCode(Pred);
1806       } else {
1807         const FCmpInst *FC = cast<FCmpInst>(Cond);
1808         FCmpInst::Predicate Pred =
1809             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1810         Condition = getFCmpCondCode(Pred);
1811         if (TM.Options.NoNaNsFPMath)
1812           Condition = getFCmpCodeWithoutNaN(Condition);
1813       }
1814 
1815       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1816                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1817       SwitchCases.push_back(CB);
1818       return;
1819     }
1820   }
1821 
1822   // Create a CaseBlock record representing this branch.
1823   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1824   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1825                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1826   SwitchCases.push_back(CB);
1827 }
1828 
1829 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1830                                                MachineBasicBlock *TBB,
1831                                                MachineBasicBlock *FBB,
1832                                                MachineBasicBlock *CurBB,
1833                                                MachineBasicBlock *SwitchBB,
1834                                                Instruction::BinaryOps Opc,
1835                                                BranchProbability TProb,
1836                                                BranchProbability FProb,
1837                                                bool InvertCond) {
1838   // Skip over not part of the tree and remember to invert op and operands at
1839   // next level.
1840   Value *NotCond;
1841   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
1842       InBlock(NotCond, CurBB->getBasicBlock())) {
1843     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1844                          !InvertCond);
1845     return;
1846   }
1847 
1848   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1849   // Compute the effective opcode for Cond, taking into account whether it needs
1850   // to be inverted, e.g.
1851   //   and (not (or A, B)), C
1852   // gets lowered as
1853   //   and (and (not A, not B), C)
1854   unsigned BOpc = 0;
1855   if (BOp) {
1856     BOpc = BOp->getOpcode();
1857     if (InvertCond) {
1858       if (BOpc == Instruction::And)
1859         BOpc = Instruction::Or;
1860       else if (BOpc == Instruction::Or)
1861         BOpc = Instruction::And;
1862     }
1863   }
1864 
1865   // If this node is not part of the or/and tree, emit it as a branch.
1866   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1867       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
1868       BOp->getParent() != CurBB->getBasicBlock() ||
1869       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1870       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1871     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1872                                  TProb, FProb, InvertCond);
1873     return;
1874   }
1875 
1876   //  Create TmpBB after CurBB.
1877   MachineFunction::iterator BBI(CurBB);
1878   MachineFunction &MF = DAG.getMachineFunction();
1879   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1880   CurBB->getParent()->insert(++BBI, TmpBB);
1881 
1882   if (Opc == Instruction::Or) {
1883     // Codegen X | Y as:
1884     // BB1:
1885     //   jmp_if_X TBB
1886     //   jmp TmpBB
1887     // TmpBB:
1888     //   jmp_if_Y TBB
1889     //   jmp FBB
1890     //
1891 
1892     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1893     // The requirement is that
1894     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1895     //     = TrueProb for original BB.
1896     // Assuming the original probabilities are A and B, one choice is to set
1897     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1898     // A/(1+B) and 2B/(1+B). This choice assumes that
1899     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1900     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1901     // TmpBB, but the math is more complicated.
1902 
1903     auto NewTrueProb = TProb / 2;
1904     auto NewFalseProb = TProb / 2 + FProb;
1905     // Emit the LHS condition.
1906     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1907                          NewTrueProb, NewFalseProb, InvertCond);
1908 
1909     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1910     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1911     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1912     // Emit the RHS condition into TmpBB.
1913     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1914                          Probs[0], Probs[1], InvertCond);
1915   } else {
1916     assert(Opc == Instruction::And && "Unknown merge op!");
1917     // Codegen X & Y as:
1918     // BB1:
1919     //   jmp_if_X TmpBB
1920     //   jmp FBB
1921     // TmpBB:
1922     //   jmp_if_Y TBB
1923     //   jmp FBB
1924     //
1925     //  This requires creation of TmpBB after CurBB.
1926 
1927     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1928     // The requirement is that
1929     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1930     //     = FalseProb for original BB.
1931     // Assuming the original probabilities are A and B, one choice is to set
1932     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1933     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1934     // TrueProb for BB1 * FalseProb for TmpBB.
1935 
1936     auto NewTrueProb = TProb + FProb / 2;
1937     auto NewFalseProb = FProb / 2;
1938     // Emit the LHS condition.
1939     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1940                          NewTrueProb, NewFalseProb, InvertCond);
1941 
1942     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1943     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1944     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1945     // Emit the RHS condition into TmpBB.
1946     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1947                          Probs[0], Probs[1], InvertCond);
1948   }
1949 }
1950 
1951 /// If the set of cases should be emitted as a series of branches, return true.
1952 /// If we should emit this as a bunch of and/or'd together conditions, return
1953 /// false.
1954 bool
1955 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1956   if (Cases.size() != 2) return true;
1957 
1958   // If this is two comparisons of the same values or'd or and'd together, they
1959   // will get folded into a single comparison, so don't emit two blocks.
1960   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1961        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1962       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1963        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1964     return false;
1965   }
1966 
1967   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1968   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1969   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1970       Cases[0].CC == Cases[1].CC &&
1971       isa<Constant>(Cases[0].CmpRHS) &&
1972       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1973     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1974       return false;
1975     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1976       return false;
1977   }
1978 
1979   return true;
1980 }
1981 
1982 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1983   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1984 
1985   // Update machine-CFG edges.
1986   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1987 
1988   if (I.isUnconditional()) {
1989     // Update machine-CFG edges.
1990     BrMBB->addSuccessor(Succ0MBB);
1991 
1992     // If this is not a fall-through branch or optimizations are switched off,
1993     // emit the branch.
1994     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1995       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1996                               MVT::Other, getControlRoot(),
1997                               DAG.getBasicBlock(Succ0MBB)));
1998 
1999     return;
2000   }
2001 
2002   // If this condition is one of the special cases we handle, do special stuff
2003   // now.
2004   const Value *CondVal = I.getCondition();
2005   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2006 
2007   // If this is a series of conditions that are or'd or and'd together, emit
2008   // this as a sequence of branches instead of setcc's with and/or operations.
2009   // As long as jumps are not expensive, this should improve performance.
2010   // For example, instead of something like:
2011   //     cmp A, B
2012   //     C = seteq
2013   //     cmp D, E
2014   //     F = setle
2015   //     or C, F
2016   //     jnz foo
2017   // Emit:
2018   //     cmp A, B
2019   //     je foo
2020   //     cmp D, E
2021   //     jle foo
2022   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2023     Instruction::BinaryOps Opcode = BOp->getOpcode();
2024     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2025         !I.getMetadata(LLVMContext::MD_unpredictable) &&
2026         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2027       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2028                            Opcode,
2029                            getEdgeProbability(BrMBB, Succ0MBB),
2030                            getEdgeProbability(BrMBB, Succ1MBB),
2031                            /*InvertCond=*/false);
2032       // If the compares in later blocks need to use values not currently
2033       // exported from this block, export them now.  This block should always
2034       // be the first entry.
2035       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2036 
2037       // Allow some cases to be rejected.
2038       if (ShouldEmitAsBranches(SwitchCases)) {
2039         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
2040           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
2041           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
2042         }
2043 
2044         // Emit the branch for this block.
2045         visitSwitchCase(SwitchCases[0], BrMBB);
2046         SwitchCases.erase(SwitchCases.begin());
2047         return;
2048       }
2049 
2050       // Okay, we decided not to do this, remove any inserted MBB's and clear
2051       // SwitchCases.
2052       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2053         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2054 
2055       SwitchCases.clear();
2056     }
2057   }
2058 
2059   // Create a CaseBlock record representing this branch.
2060   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2061                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2062 
2063   // Use visitSwitchCase to actually insert the fast branch sequence for this
2064   // cond branch.
2065   visitSwitchCase(CB, BrMBB);
2066 }
2067 
2068 /// visitSwitchCase - Emits the necessary code to represent a single node in
2069 /// the binary search tree resulting from lowering a switch instruction.
2070 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2071                                           MachineBasicBlock *SwitchBB) {
2072   SDValue Cond;
2073   SDValue CondLHS = getValue(CB.CmpLHS);
2074   SDLoc dl = CB.DL;
2075 
2076   // Build the setcc now.
2077   if (!CB.CmpMHS) {
2078     // Fold "(X == true)" to X and "(X == false)" to !X to
2079     // handle common cases produced by branch lowering.
2080     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2081         CB.CC == ISD::SETEQ)
2082       Cond = CondLHS;
2083     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2084              CB.CC == ISD::SETEQ) {
2085       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2086       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2087     } else
2088       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2089   } else {
2090     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2091 
2092     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2093     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2094 
2095     SDValue CmpOp = getValue(CB.CmpMHS);
2096     EVT VT = CmpOp.getValueType();
2097 
2098     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2099       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2100                           ISD::SETLE);
2101     } else {
2102       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2103                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2104       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2105                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2106     }
2107   }
2108 
2109   // Update successor info
2110   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2111   // TrueBB and FalseBB are always different unless the incoming IR is
2112   // degenerate. This only happens when running llc on weird IR.
2113   if (CB.TrueBB != CB.FalseBB)
2114     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2115   SwitchBB->normalizeSuccProbs();
2116 
2117   // If the lhs block is the next block, invert the condition so that we can
2118   // fall through to the lhs instead of the rhs block.
2119   if (CB.TrueBB == NextBlock(SwitchBB)) {
2120     std::swap(CB.TrueBB, CB.FalseBB);
2121     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2122     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2123   }
2124 
2125   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2126                                MVT::Other, getControlRoot(), Cond,
2127                                DAG.getBasicBlock(CB.TrueBB));
2128 
2129   // Insert the false branch. Do this even if it's a fall through branch,
2130   // this makes it easier to do DAG optimizations which require inverting
2131   // the branch condition.
2132   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2133                        DAG.getBasicBlock(CB.FalseBB));
2134 
2135   DAG.setRoot(BrCond);
2136 }
2137 
2138 /// visitJumpTable - Emit JumpTable node in the current MBB
2139 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2140   // Emit the code for the jump table
2141   assert(JT.Reg != -1U && "Should lower JT Header first!");
2142   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2143   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2144                                      JT.Reg, PTy);
2145   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2146   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2147                                     MVT::Other, Index.getValue(1),
2148                                     Table, Index);
2149   DAG.setRoot(BrJumpTable);
2150 }
2151 
2152 /// visitJumpTableHeader - This function emits necessary code to produce index
2153 /// in the JumpTable from switch case.
2154 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2155                                                JumpTableHeader &JTH,
2156                                                MachineBasicBlock *SwitchBB) {
2157   SDLoc dl = getCurSDLoc();
2158 
2159   // Subtract the lowest switch case value from the value being switched on and
2160   // conditional branch to default mbb if the result is greater than the
2161   // difference between smallest and largest cases.
2162   SDValue SwitchOp = getValue(JTH.SValue);
2163   EVT VT = SwitchOp.getValueType();
2164   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2165                             DAG.getConstant(JTH.First, dl, VT));
2166 
2167   // The SDNode we just created, which holds the value being switched on minus
2168   // the smallest case value, needs to be copied to a virtual register so it
2169   // can be used as an index into the jump table in a subsequent basic block.
2170   // This value may be smaller or larger than the target's pointer type, and
2171   // therefore require extension or truncating.
2172   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2173   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2174 
2175   unsigned JumpTableReg =
2176       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2177   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2178                                     JumpTableReg, SwitchOp);
2179   JT.Reg = JumpTableReg;
2180 
2181   // Emit the range check for the jump table, and branch to the default block
2182   // for the switch statement if the value being switched on exceeds the largest
2183   // case in the switch.
2184   SDValue CMP = DAG.getSetCC(
2185       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2186                                  Sub.getValueType()),
2187       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2188 
2189   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2190                                MVT::Other, CopyTo, CMP,
2191                                DAG.getBasicBlock(JT.Default));
2192 
2193   // Avoid emitting unnecessary branches to the next block.
2194   if (JT.MBB != NextBlock(SwitchBB))
2195     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2196                          DAG.getBasicBlock(JT.MBB));
2197 
2198   DAG.setRoot(BrCond);
2199 }
2200 
2201 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2202 /// variable if there exists one.
2203 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2204                                  SDValue &Chain) {
2205   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2206   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2207   MachineFunction &MF = DAG.getMachineFunction();
2208   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2209   MachineSDNode *Node =
2210       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2211   if (Global) {
2212     MachinePointerInfo MPInfo(Global);
2213     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2214                  MachineMemOperand::MODereferenceable;
2215     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2216         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2217     DAG.setNodeMemRefs(Node, {MemRef});
2218   }
2219   return SDValue(Node, 0);
2220 }
2221 
2222 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2223 /// tail spliced into a stack protector check success bb.
2224 ///
2225 /// For a high level explanation of how this fits into the stack protector
2226 /// generation see the comment on the declaration of class
2227 /// StackProtectorDescriptor.
2228 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2229                                                   MachineBasicBlock *ParentBB) {
2230 
2231   // First create the loads to the guard/stack slot for the comparison.
2232   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2233   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2234 
2235   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2236   int FI = MFI.getStackProtectorIndex();
2237 
2238   SDValue Guard;
2239   SDLoc dl = getCurSDLoc();
2240   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2241   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2242   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2243 
2244   // Generate code to load the content of the guard slot.
2245   SDValue GuardVal = DAG.getLoad(
2246       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2247       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2248       MachineMemOperand::MOVolatile);
2249 
2250   if (TLI.useStackGuardXorFP())
2251     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2252 
2253   // Retrieve guard check function, nullptr if instrumentation is inlined.
2254   if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
2255     // The target provides a guard check function to validate the guard value.
2256     // Generate a call to that function with the content of the guard slot as
2257     // argument.
2258     auto *Fn = cast<Function>(GuardCheck);
2259     FunctionType *FnTy = Fn->getFunctionType();
2260     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2261 
2262     TargetLowering::ArgListTy Args;
2263     TargetLowering::ArgListEntry Entry;
2264     Entry.Node = GuardVal;
2265     Entry.Ty = FnTy->getParamType(0);
2266     if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
2267       Entry.IsInReg = true;
2268     Args.push_back(Entry);
2269 
2270     TargetLowering::CallLoweringInfo CLI(DAG);
2271     CLI.setDebugLoc(getCurSDLoc())
2272       .setChain(DAG.getEntryNode())
2273       .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
2274                  getValue(GuardCheck), std::move(Args));
2275 
2276     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2277     DAG.setRoot(Result.second);
2278     return;
2279   }
2280 
2281   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2282   // Otherwise, emit a volatile load to retrieve the stack guard value.
2283   SDValue Chain = DAG.getEntryNode();
2284   if (TLI.useLoadStackGuardNode()) {
2285     Guard = getLoadStackGuard(DAG, dl, Chain);
2286   } else {
2287     const Value *IRGuard = TLI.getSDagStackGuard(M);
2288     SDValue GuardPtr = getValue(IRGuard);
2289 
2290     Guard =
2291         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2292                     Align, MachineMemOperand::MOVolatile);
2293   }
2294 
2295   // Perform the comparison via a subtract/getsetcc.
2296   EVT VT = Guard.getValueType();
2297   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2298 
2299   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2300                                                         *DAG.getContext(),
2301                                                         Sub.getValueType()),
2302                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2303 
2304   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2305   // branch to failure MBB.
2306   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2307                                MVT::Other, GuardVal.getOperand(0),
2308                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2309   // Otherwise branch to success MBB.
2310   SDValue Br = DAG.getNode(ISD::BR, dl,
2311                            MVT::Other, BrCond,
2312                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2313 
2314   DAG.setRoot(Br);
2315 }
2316 
2317 /// Codegen the failure basic block for a stack protector check.
2318 ///
2319 /// A failure stack protector machine basic block consists simply of a call to
2320 /// __stack_chk_fail().
2321 ///
2322 /// For a high level explanation of how this fits into the stack protector
2323 /// generation see the comment on the declaration of class
2324 /// StackProtectorDescriptor.
2325 void
2326 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2327   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2328   SDValue Chain =
2329       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2330                       None, false, getCurSDLoc(), false, false).second;
2331   DAG.setRoot(Chain);
2332 }
2333 
2334 /// visitBitTestHeader - This function emits necessary code to produce value
2335 /// suitable for "bit tests"
2336 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2337                                              MachineBasicBlock *SwitchBB) {
2338   SDLoc dl = getCurSDLoc();
2339 
2340   // Subtract the minimum value
2341   SDValue SwitchOp = getValue(B.SValue);
2342   EVT VT = SwitchOp.getValueType();
2343   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2344                             DAG.getConstant(B.First, dl, VT));
2345 
2346   // Check range
2347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2348   SDValue RangeCmp = DAG.getSetCC(
2349       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2350                                  Sub.getValueType()),
2351       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2352 
2353   // Determine the type of the test operands.
2354   bool UsePtrType = false;
2355   if (!TLI.isTypeLegal(VT))
2356     UsePtrType = true;
2357   else {
2358     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2359       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2360         // Switch table case range are encoded into series of masks.
2361         // Just use pointer type, it's guaranteed to fit.
2362         UsePtrType = true;
2363         break;
2364       }
2365   }
2366   if (UsePtrType) {
2367     VT = TLI.getPointerTy(DAG.getDataLayout());
2368     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2369   }
2370 
2371   B.RegVT = VT.getSimpleVT();
2372   B.Reg = FuncInfo.CreateReg(B.RegVT);
2373   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2374 
2375   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2376 
2377   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2378   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2379   SwitchBB->normalizeSuccProbs();
2380 
2381   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2382                                 MVT::Other, CopyTo, RangeCmp,
2383                                 DAG.getBasicBlock(B.Default));
2384 
2385   // Avoid emitting unnecessary branches to the next block.
2386   if (MBB != NextBlock(SwitchBB))
2387     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2388                           DAG.getBasicBlock(MBB));
2389 
2390   DAG.setRoot(BrRange);
2391 }
2392 
2393 /// visitBitTestCase - this function produces one "bit test"
2394 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2395                                            MachineBasicBlock* NextMBB,
2396                                            BranchProbability BranchProbToNext,
2397                                            unsigned Reg,
2398                                            BitTestCase &B,
2399                                            MachineBasicBlock *SwitchBB) {
2400   SDLoc dl = getCurSDLoc();
2401   MVT VT = BB.RegVT;
2402   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2403   SDValue Cmp;
2404   unsigned PopCount = countPopulation(B.Mask);
2405   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2406   if (PopCount == 1) {
2407     // Testing for a single bit; just compare the shift count with what it
2408     // would need to be to shift a 1 bit in that position.
2409     Cmp = DAG.getSetCC(
2410         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2411         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2412         ISD::SETEQ);
2413   } else if (PopCount == BB.Range) {
2414     // There is only one zero bit in the range, test for it directly.
2415     Cmp = DAG.getSetCC(
2416         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2417         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2418         ISD::SETNE);
2419   } else {
2420     // Make desired shift
2421     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2422                                     DAG.getConstant(1, dl, VT), ShiftOp);
2423 
2424     // Emit bit tests and jumps
2425     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2426                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2427     Cmp = DAG.getSetCC(
2428         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2429         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2430   }
2431 
2432   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2433   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2434   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2435   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2436   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2437   // one as they are relative probabilities (and thus work more like weights),
2438   // and hence we need to normalize them to let the sum of them become one.
2439   SwitchBB->normalizeSuccProbs();
2440 
2441   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2442                               MVT::Other, getControlRoot(),
2443                               Cmp, DAG.getBasicBlock(B.TargetBB));
2444 
2445   // Avoid emitting unnecessary branches to the next block.
2446   if (NextMBB != NextBlock(SwitchBB))
2447     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2448                         DAG.getBasicBlock(NextMBB));
2449 
2450   DAG.setRoot(BrAnd);
2451 }
2452 
2453 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2454   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2455 
2456   // Retrieve successors. Look through artificial IR level blocks like
2457   // catchswitch for successors.
2458   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2459   const BasicBlock *EHPadBB = I.getSuccessor(1);
2460 
2461   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2462   // have to do anything here to lower funclet bundles.
2463   assert(!I.hasOperandBundlesOtherThan(
2464              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2465          "Cannot lower invokes with arbitrary operand bundles yet!");
2466 
2467   const Value *Callee(I.getCalledValue());
2468   const Function *Fn = dyn_cast<Function>(Callee);
2469   if (isa<InlineAsm>(Callee))
2470     visitInlineAsm(&I);
2471   else if (Fn && Fn->isIntrinsic()) {
2472     switch (Fn->getIntrinsicID()) {
2473     default:
2474       llvm_unreachable("Cannot invoke this intrinsic");
2475     case Intrinsic::donothing:
2476       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2477       break;
2478     case Intrinsic::experimental_patchpoint_void:
2479     case Intrinsic::experimental_patchpoint_i64:
2480       visitPatchpoint(&I, EHPadBB);
2481       break;
2482     case Intrinsic::experimental_gc_statepoint:
2483       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2484       break;
2485     }
2486   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2487     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2488     // Eventually we will support lowering the @llvm.experimental.deoptimize
2489     // intrinsic, and right now there are no plans to support other intrinsics
2490     // with deopt state.
2491     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2492   } else {
2493     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2494   }
2495 
2496   // If the value of the invoke is used outside of its defining block, make it
2497   // available as a virtual register.
2498   // We already took care of the exported value for the statepoint instruction
2499   // during call to the LowerStatepoint.
2500   if (!isStatepoint(I)) {
2501     CopyToExportRegsIfNeeded(&I);
2502   }
2503 
2504   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2505   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2506   BranchProbability EHPadBBProb =
2507       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2508           : BranchProbability::getZero();
2509   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2510 
2511   // Update successor info.
2512   addSuccessorWithProb(InvokeMBB, Return);
2513   for (auto &UnwindDest : UnwindDests) {
2514     UnwindDest.first->setIsEHPad();
2515     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2516   }
2517   InvokeMBB->normalizeSuccProbs();
2518 
2519   // Drop into normal successor.
2520   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2521                           MVT::Other, getControlRoot(),
2522                           DAG.getBasicBlock(Return)));
2523 }
2524 
2525 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2526   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2527 }
2528 
2529 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2530   assert(FuncInfo.MBB->isEHPad() &&
2531          "Call to landingpad not in landing pad!");
2532 
2533   // If there aren't registers to copy the values into (e.g., during SjLj
2534   // exceptions), then don't bother to create these DAG nodes.
2535   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2536   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2537   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2538       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2539     return;
2540 
2541   // If landingpad's return type is token type, we don't create DAG nodes
2542   // for its exception pointer and selector value. The extraction of exception
2543   // pointer or selector value from token type landingpads is not currently
2544   // supported.
2545   if (LP.getType()->isTokenTy())
2546     return;
2547 
2548   SmallVector<EVT, 2> ValueVTs;
2549   SDLoc dl = getCurSDLoc();
2550   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2551   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2552 
2553   // Get the two live-in registers as SDValues. The physregs have already been
2554   // copied into virtual registers.
2555   SDValue Ops[2];
2556   if (FuncInfo.ExceptionPointerVirtReg) {
2557     Ops[0] = DAG.getZExtOrTrunc(
2558         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2559                            FuncInfo.ExceptionPointerVirtReg,
2560                            TLI.getPointerTy(DAG.getDataLayout())),
2561         dl, ValueVTs[0]);
2562   } else {
2563     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2564   }
2565   Ops[1] = DAG.getZExtOrTrunc(
2566       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2567                          FuncInfo.ExceptionSelectorVirtReg,
2568                          TLI.getPointerTy(DAG.getDataLayout())),
2569       dl, ValueVTs[1]);
2570 
2571   // Merge into one.
2572   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2573                             DAG.getVTList(ValueVTs), Ops);
2574   setValue(&LP, Res);
2575 }
2576 
2577 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2578 #ifndef NDEBUG
2579   for (const CaseCluster &CC : Clusters)
2580     assert(CC.Low == CC.High && "Input clusters must be single-case");
2581 #endif
2582 
2583   llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
2584     return a.Low->getValue().slt(b.Low->getValue());
2585   });
2586 
2587   // Merge adjacent clusters with the same destination.
2588   const unsigned N = Clusters.size();
2589   unsigned DstIndex = 0;
2590   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2591     CaseCluster &CC = Clusters[SrcIndex];
2592     const ConstantInt *CaseVal = CC.Low;
2593     MachineBasicBlock *Succ = CC.MBB;
2594 
2595     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2596         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2597       // If this case has the same successor and is a neighbour, merge it into
2598       // the previous cluster.
2599       Clusters[DstIndex - 1].High = CaseVal;
2600       Clusters[DstIndex - 1].Prob += CC.Prob;
2601     } else {
2602       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2603                    sizeof(Clusters[SrcIndex]));
2604     }
2605   }
2606   Clusters.resize(DstIndex);
2607 }
2608 
2609 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2610                                            MachineBasicBlock *Last) {
2611   // Update JTCases.
2612   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2613     if (JTCases[i].first.HeaderBB == First)
2614       JTCases[i].first.HeaderBB = Last;
2615 
2616   // Update BitTestCases.
2617   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2618     if (BitTestCases[i].Parent == First)
2619       BitTestCases[i].Parent = Last;
2620 }
2621 
2622 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2623   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2624 
2625   // Update machine-CFG edges with unique successors.
2626   SmallSet<BasicBlock*, 32> Done;
2627   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2628     BasicBlock *BB = I.getSuccessor(i);
2629     bool Inserted = Done.insert(BB).second;
2630     if (!Inserted)
2631         continue;
2632 
2633     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2634     addSuccessorWithProb(IndirectBrMBB, Succ);
2635   }
2636   IndirectBrMBB->normalizeSuccProbs();
2637 
2638   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2639                           MVT::Other, getControlRoot(),
2640                           getValue(I.getAddress())));
2641 }
2642 
2643 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2644   if (!DAG.getTarget().Options.TrapUnreachable)
2645     return;
2646 
2647   // We may be able to ignore unreachable behind a noreturn call.
2648   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2649     const BasicBlock &BB = *I.getParent();
2650     if (&I != &BB.front()) {
2651       BasicBlock::const_iterator PredI =
2652         std::prev(BasicBlock::const_iterator(&I));
2653       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2654         if (Call->doesNotReturn())
2655           return;
2656       }
2657     }
2658   }
2659 
2660   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2661 }
2662 
2663 void SelectionDAGBuilder::visitFSub(const User &I) {
2664   // -0.0 - X --> fneg
2665   Type *Ty = I.getType();
2666   if (isa<Constant>(I.getOperand(0)) &&
2667       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2668     SDValue Op2 = getValue(I.getOperand(1));
2669     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2670                              Op2.getValueType(), Op2));
2671     return;
2672   }
2673 
2674   visitBinary(I, ISD::FSUB);
2675 }
2676 
2677 /// Checks if the given instruction performs a vector reduction, in which case
2678 /// we have the freedom to alter the elements in the result as long as the
2679 /// reduction of them stays unchanged.
2680 static bool isVectorReductionOp(const User *I) {
2681   const Instruction *Inst = dyn_cast<Instruction>(I);
2682   if (!Inst || !Inst->getType()->isVectorTy())
2683     return false;
2684 
2685   auto OpCode = Inst->getOpcode();
2686   switch (OpCode) {
2687   case Instruction::Add:
2688   case Instruction::Mul:
2689   case Instruction::And:
2690   case Instruction::Or:
2691   case Instruction::Xor:
2692     break;
2693   case Instruction::FAdd:
2694   case Instruction::FMul:
2695     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2696       if (FPOp->getFastMathFlags().isFast())
2697         break;
2698     LLVM_FALLTHROUGH;
2699   default:
2700     return false;
2701   }
2702 
2703   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2704   // Ensure the reduction size is a power of 2.
2705   if (!isPowerOf2_32(ElemNum))
2706     return false;
2707 
2708   unsigned ElemNumToReduce = ElemNum;
2709 
2710   // Do DFS search on the def-use chain from the given instruction. We only
2711   // allow four kinds of operations during the search until we reach the
2712   // instruction that extracts the first element from the vector:
2713   //
2714   //   1. The reduction operation of the same opcode as the given instruction.
2715   //
2716   //   2. PHI node.
2717   //
2718   //   3. ShuffleVector instruction together with a reduction operation that
2719   //      does a partial reduction.
2720   //
2721   //   4. ExtractElement that extracts the first element from the vector, and we
2722   //      stop searching the def-use chain here.
2723   //
2724   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2725   // from 1-3 to the stack to continue the DFS. The given instruction is not
2726   // a reduction operation if we meet any other instructions other than those
2727   // listed above.
2728 
2729   SmallVector<const User *, 16> UsersToVisit{Inst};
2730   SmallPtrSet<const User *, 16> Visited;
2731   bool ReduxExtracted = false;
2732 
2733   while (!UsersToVisit.empty()) {
2734     auto User = UsersToVisit.back();
2735     UsersToVisit.pop_back();
2736     if (!Visited.insert(User).second)
2737       continue;
2738 
2739     for (const auto &U : User->users()) {
2740       auto Inst = dyn_cast<Instruction>(U);
2741       if (!Inst)
2742         return false;
2743 
2744       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2745         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2746           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2747             return false;
2748         UsersToVisit.push_back(U);
2749       } else if (const ShuffleVectorInst *ShufInst =
2750                      dyn_cast<ShuffleVectorInst>(U)) {
2751         // Detect the following pattern: A ShuffleVector instruction together
2752         // with a reduction that do partial reduction on the first and second
2753         // ElemNumToReduce / 2 elements, and store the result in
2754         // ElemNumToReduce / 2 elements in another vector.
2755 
2756         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2757         if (ResultElements < ElemNum)
2758           return false;
2759 
2760         if (ElemNumToReduce == 1)
2761           return false;
2762         if (!isa<UndefValue>(U->getOperand(1)))
2763           return false;
2764         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2765           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2766             return false;
2767         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2768           if (ShufInst->getMaskValue(i) != -1)
2769             return false;
2770 
2771         // There is only one user of this ShuffleVector instruction, which
2772         // must be a reduction operation.
2773         if (!U->hasOneUse())
2774           return false;
2775 
2776         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2777         if (!U2 || U2->getOpcode() != OpCode)
2778           return false;
2779 
2780         // Check operands of the reduction operation.
2781         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2782             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2783           UsersToVisit.push_back(U2);
2784           ElemNumToReduce /= 2;
2785         } else
2786           return false;
2787       } else if (isa<ExtractElementInst>(U)) {
2788         // At this moment we should have reduced all elements in the vector.
2789         if (ElemNumToReduce != 1)
2790           return false;
2791 
2792         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2793         if (!Val || !Val->isZero())
2794           return false;
2795 
2796         ReduxExtracted = true;
2797       } else
2798         return false;
2799     }
2800   }
2801   return ReduxExtracted;
2802 }
2803 
2804 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
2805   SDNodeFlags Flags;
2806   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
2807     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
2808     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
2809   }
2810   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
2811     Flags.setExact(ExactOp->isExact());
2812   }
2813   if (isVectorReductionOp(&I)) {
2814     Flags.setVectorReduction(true);
2815     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2816   }
2817 
2818   SDValue Op1 = getValue(I.getOperand(0));
2819   SDValue Op2 = getValue(I.getOperand(1));
2820   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
2821                                      Op1, Op2, Flags);
2822   setValue(&I, BinNodeValue);
2823 }
2824 
2825 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2826   SDValue Op1 = getValue(I.getOperand(0));
2827   SDValue Op2 = getValue(I.getOperand(1));
2828 
2829   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2830       Op1.getValueType(), DAG.getDataLayout());
2831 
2832   // Coerce the shift amount to the right type if we can.
2833   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2834     unsigned ShiftSize = ShiftTy.getSizeInBits();
2835     unsigned Op2Size = Op2.getValueSizeInBits();
2836     SDLoc DL = getCurSDLoc();
2837 
2838     // If the operand is smaller than the shift count type, promote it.
2839     if (ShiftSize > Op2Size)
2840       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2841 
2842     // If the operand is larger than the shift count type but the shift
2843     // count type has enough bits to represent any shift value, truncate
2844     // it now. This is a common case and it exposes the truncate to
2845     // optimization early.
2846     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2847       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2848     // Otherwise we'll need to temporarily settle for some other convenient
2849     // type.  Type legalization will make adjustments once the shiftee is split.
2850     else
2851       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2852   }
2853 
2854   bool nuw = false;
2855   bool nsw = false;
2856   bool exact = false;
2857 
2858   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2859 
2860     if (const OverflowingBinaryOperator *OFBinOp =
2861             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2862       nuw = OFBinOp->hasNoUnsignedWrap();
2863       nsw = OFBinOp->hasNoSignedWrap();
2864     }
2865     if (const PossiblyExactOperator *ExactOp =
2866             dyn_cast<const PossiblyExactOperator>(&I))
2867       exact = ExactOp->isExact();
2868   }
2869   SDNodeFlags Flags;
2870   Flags.setExact(exact);
2871   Flags.setNoSignedWrap(nsw);
2872   Flags.setNoUnsignedWrap(nuw);
2873   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2874                             Flags);
2875   setValue(&I, Res);
2876 }
2877 
2878 void SelectionDAGBuilder::visitSDiv(const User &I) {
2879   SDValue Op1 = getValue(I.getOperand(0));
2880   SDValue Op2 = getValue(I.getOperand(1));
2881 
2882   SDNodeFlags Flags;
2883   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2884                  cast<PossiblyExactOperator>(&I)->isExact());
2885   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2886                            Op2, Flags));
2887 }
2888 
2889 void SelectionDAGBuilder::visitICmp(const User &I) {
2890   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2891   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2892     predicate = IC->getPredicate();
2893   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2894     predicate = ICmpInst::Predicate(IC->getPredicate());
2895   SDValue Op1 = getValue(I.getOperand(0));
2896   SDValue Op2 = getValue(I.getOperand(1));
2897   ISD::CondCode Opcode = getICmpCondCode(predicate);
2898 
2899   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2900                                                         I.getType());
2901   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2902 }
2903 
2904 void SelectionDAGBuilder::visitFCmp(const User &I) {
2905   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2906   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2907     predicate = FC->getPredicate();
2908   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2909     predicate = FCmpInst::Predicate(FC->getPredicate());
2910   SDValue Op1 = getValue(I.getOperand(0));
2911   SDValue Op2 = getValue(I.getOperand(1));
2912 
2913   ISD::CondCode Condition = getFCmpCondCode(predicate);
2914   auto *FPMO = dyn_cast<FPMathOperator>(&I);
2915   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
2916     Condition = getFCmpCodeWithoutNaN(Condition);
2917 
2918   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2919                                                         I.getType());
2920   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2921 }
2922 
2923 // Check if the condition of the select has one use or two users that are both
2924 // selects with the same condition.
2925 static bool hasOnlySelectUsers(const Value *Cond) {
2926   return llvm::all_of(Cond->users(), [](const Value *V) {
2927     return isa<SelectInst>(V);
2928   });
2929 }
2930 
2931 void SelectionDAGBuilder::visitSelect(const User &I) {
2932   SmallVector<EVT, 4> ValueVTs;
2933   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2934                   ValueVTs);
2935   unsigned NumValues = ValueVTs.size();
2936   if (NumValues == 0) return;
2937 
2938   SmallVector<SDValue, 4> Values(NumValues);
2939   SDValue Cond     = getValue(I.getOperand(0));
2940   SDValue LHSVal   = getValue(I.getOperand(1));
2941   SDValue RHSVal   = getValue(I.getOperand(2));
2942   auto BaseOps = {Cond};
2943   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2944     ISD::VSELECT : ISD::SELECT;
2945 
2946   // Min/max matching is only viable if all output VTs are the same.
2947   if (is_splat(ValueVTs)) {
2948     EVT VT = ValueVTs[0];
2949     LLVMContext &Ctx = *DAG.getContext();
2950     auto &TLI = DAG.getTargetLoweringInfo();
2951 
2952     // We care about the legality of the operation after it has been type
2953     // legalized.
2954     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2955            VT != TLI.getTypeToTransformTo(Ctx, VT))
2956       VT = TLI.getTypeToTransformTo(Ctx, VT);
2957 
2958     // If the vselect is legal, assume we want to leave this as a vector setcc +
2959     // vselect. Otherwise, if this is going to be scalarized, we want to see if
2960     // min/max is legal on the scalar type.
2961     bool UseScalarMinMax = VT.isVector() &&
2962       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2963 
2964     Value *LHS, *RHS;
2965     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2966     ISD::NodeType Opc = ISD::DELETED_NODE;
2967     switch (SPR.Flavor) {
2968     case SPF_UMAX:    Opc = ISD::UMAX; break;
2969     case SPF_UMIN:    Opc = ISD::UMIN; break;
2970     case SPF_SMAX:    Opc = ISD::SMAX; break;
2971     case SPF_SMIN:    Opc = ISD::SMIN; break;
2972     case SPF_FMINNUM:
2973       switch (SPR.NaNBehavior) {
2974       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2975       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
2976       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2977       case SPNB_RETURNS_ANY: {
2978         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2979           Opc = ISD::FMINNUM;
2980         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
2981           Opc = ISD::FMINIMUM;
2982         else if (UseScalarMinMax)
2983           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2984             ISD::FMINNUM : ISD::FMINIMUM;
2985         break;
2986       }
2987       }
2988       break;
2989     case SPF_FMAXNUM:
2990       switch (SPR.NaNBehavior) {
2991       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2992       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
2993       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
2994       case SPNB_RETURNS_ANY:
2995 
2996         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
2997           Opc = ISD::FMAXNUM;
2998         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
2999           Opc = ISD::FMAXIMUM;
3000         else if (UseScalarMinMax)
3001           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3002             ISD::FMAXNUM : ISD::FMAXIMUM;
3003         break;
3004       }
3005       break;
3006     default: break;
3007     }
3008 
3009     if (Opc != ISD::DELETED_NODE &&
3010         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3011          (UseScalarMinMax &&
3012           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3013         // If the underlying comparison instruction is used by any other
3014         // instruction, the consumed instructions won't be destroyed, so it is
3015         // not profitable to convert to a min/max.
3016         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3017       OpCode = Opc;
3018       LHSVal = getValue(LHS);
3019       RHSVal = getValue(RHS);
3020       BaseOps = {};
3021     }
3022   }
3023 
3024   for (unsigned i = 0; i != NumValues; ++i) {
3025     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3026     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3027     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3028     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
3029                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
3030                             Ops);
3031   }
3032 
3033   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3034                            DAG.getVTList(ValueVTs), Values));
3035 }
3036 
3037 void SelectionDAGBuilder::visitTrunc(const User &I) {
3038   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3039   SDValue N = getValue(I.getOperand(0));
3040   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3041                                                         I.getType());
3042   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3043 }
3044 
3045 void SelectionDAGBuilder::visitZExt(const User &I) {
3046   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3047   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3048   SDValue N = getValue(I.getOperand(0));
3049   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3050                                                         I.getType());
3051   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3052 }
3053 
3054 void SelectionDAGBuilder::visitSExt(const User &I) {
3055   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3056   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3057   SDValue N = getValue(I.getOperand(0));
3058   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3059                                                         I.getType());
3060   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3061 }
3062 
3063 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3064   // FPTrunc is never a no-op cast, no need to check
3065   SDValue N = getValue(I.getOperand(0));
3066   SDLoc dl = getCurSDLoc();
3067   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3068   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3069   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3070                            DAG.getTargetConstant(
3071                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3072 }
3073 
3074 void SelectionDAGBuilder::visitFPExt(const User &I) {
3075   // FPExt is never a no-op cast, no need to check
3076   SDValue N = getValue(I.getOperand(0));
3077   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3078                                                         I.getType());
3079   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3080 }
3081 
3082 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3083   // FPToUI is never a no-op cast, no need to check
3084   SDValue N = getValue(I.getOperand(0));
3085   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3086                                                         I.getType());
3087   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3088 }
3089 
3090 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3091   // FPToSI is never a no-op cast, no need to check
3092   SDValue N = getValue(I.getOperand(0));
3093   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3094                                                         I.getType());
3095   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3096 }
3097 
3098 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3099   // UIToFP is never a no-op cast, no need to check
3100   SDValue N = getValue(I.getOperand(0));
3101   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3102                                                         I.getType());
3103   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3104 }
3105 
3106 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3107   // SIToFP is never a no-op cast, no need to check
3108   SDValue N = getValue(I.getOperand(0));
3109   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3110                                                         I.getType());
3111   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3112 }
3113 
3114 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3115   // What to do depends on the size of the integer and the size of the pointer.
3116   // We can either truncate, zero extend, or no-op, accordingly.
3117   SDValue N = getValue(I.getOperand(0));
3118   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3119                                                         I.getType());
3120   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3121 }
3122 
3123 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3124   // What to do depends on the size of the integer and the size of the pointer.
3125   // We can either truncate, zero extend, or no-op, accordingly.
3126   SDValue N = getValue(I.getOperand(0));
3127   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3128                                                         I.getType());
3129   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3130 }
3131 
3132 void SelectionDAGBuilder::visitBitCast(const User &I) {
3133   SDValue N = getValue(I.getOperand(0));
3134   SDLoc dl = getCurSDLoc();
3135   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3136                                                         I.getType());
3137 
3138   // BitCast assures us that source and destination are the same size so this is
3139   // either a BITCAST or a no-op.
3140   if (DestVT != N.getValueType())
3141     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3142                              DestVT, N)); // convert types.
3143   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3144   // might fold any kind of constant expression to an integer constant and that
3145   // is not what we are looking for. Only recognize a bitcast of a genuine
3146   // constant integer as an opaque constant.
3147   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3148     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3149                                  /*isOpaque*/true));
3150   else
3151     setValue(&I, N);            // noop cast.
3152 }
3153 
3154 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3155   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3156   const Value *SV = I.getOperand(0);
3157   SDValue N = getValue(SV);
3158   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3159 
3160   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3161   unsigned DestAS = I.getType()->getPointerAddressSpace();
3162 
3163   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3164     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3165 
3166   setValue(&I, N);
3167 }
3168 
3169 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3171   SDValue InVec = getValue(I.getOperand(0));
3172   SDValue InVal = getValue(I.getOperand(1));
3173   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3174                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3175   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3176                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3177                            InVec, InVal, InIdx));
3178 }
3179 
3180 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3181   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3182   SDValue InVec = getValue(I.getOperand(0));
3183   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3184                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3185   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3186                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3187                            InVec, InIdx));
3188 }
3189 
3190 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3191   SDValue Src1 = getValue(I.getOperand(0));
3192   SDValue Src2 = getValue(I.getOperand(1));
3193   SDLoc DL = getCurSDLoc();
3194 
3195   SmallVector<int, 8> Mask;
3196   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3197   unsigned MaskNumElts = Mask.size();
3198 
3199   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3200   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3201   EVT SrcVT = Src1.getValueType();
3202   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3203 
3204   if (SrcNumElts == MaskNumElts) {
3205     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3206     return;
3207   }
3208 
3209   // Normalize the shuffle vector since mask and vector length don't match.
3210   if (SrcNumElts < MaskNumElts) {
3211     // Mask is longer than the source vectors. We can use concatenate vector to
3212     // make the mask and vectors lengths match.
3213 
3214     if (MaskNumElts % SrcNumElts == 0) {
3215       // Mask length is a multiple of the source vector length.
3216       // Check if the shuffle is some kind of concatenation of the input
3217       // vectors.
3218       unsigned NumConcat = MaskNumElts / SrcNumElts;
3219       bool IsConcat = true;
3220       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3221       for (unsigned i = 0; i != MaskNumElts; ++i) {
3222         int Idx = Mask[i];
3223         if (Idx < 0)
3224           continue;
3225         // Ensure the indices in each SrcVT sized piece are sequential and that
3226         // the same source is used for the whole piece.
3227         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3228             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3229              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3230           IsConcat = false;
3231           break;
3232         }
3233         // Remember which source this index came from.
3234         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3235       }
3236 
3237       // The shuffle is concatenating multiple vectors together. Just emit
3238       // a CONCAT_VECTORS operation.
3239       if (IsConcat) {
3240         SmallVector<SDValue, 8> ConcatOps;
3241         for (auto Src : ConcatSrcs) {
3242           if (Src < 0)
3243             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3244           else if (Src == 0)
3245             ConcatOps.push_back(Src1);
3246           else
3247             ConcatOps.push_back(Src2);
3248         }
3249         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3250         return;
3251       }
3252     }
3253 
3254     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3255     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3256     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3257                                     PaddedMaskNumElts);
3258 
3259     // Pad both vectors with undefs to make them the same length as the mask.
3260     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3261 
3262     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3263     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3264     MOps1[0] = Src1;
3265     MOps2[0] = Src2;
3266 
3267     Src1 = Src1.isUndef()
3268                ? DAG.getUNDEF(PaddedVT)
3269                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3270     Src2 = Src2.isUndef()
3271                ? DAG.getUNDEF(PaddedVT)
3272                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3273 
3274     // Readjust mask for new input vector length.
3275     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3276     for (unsigned i = 0; i != MaskNumElts; ++i) {
3277       int Idx = Mask[i];
3278       if (Idx >= (int)SrcNumElts)
3279         Idx -= SrcNumElts - PaddedMaskNumElts;
3280       MappedOps[i] = Idx;
3281     }
3282 
3283     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3284 
3285     // If the concatenated vector was padded, extract a subvector with the
3286     // correct number of elements.
3287     if (MaskNumElts != PaddedMaskNumElts)
3288       Result = DAG.getNode(
3289           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3290           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3291 
3292     setValue(&I, Result);
3293     return;
3294   }
3295 
3296   if (SrcNumElts > MaskNumElts) {
3297     // Analyze the access pattern of the vector to see if we can extract
3298     // two subvectors and do the shuffle.
3299     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3300     bool CanExtract = true;
3301     for (int Idx : Mask) {
3302       unsigned Input = 0;
3303       if (Idx < 0)
3304         continue;
3305 
3306       if (Idx >= (int)SrcNumElts) {
3307         Input = 1;
3308         Idx -= SrcNumElts;
3309       }
3310 
3311       // If all the indices come from the same MaskNumElts sized portion of
3312       // the sources we can use extract. Also make sure the extract wouldn't
3313       // extract past the end of the source.
3314       int NewStartIdx = alignDown(Idx, MaskNumElts);
3315       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3316           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3317         CanExtract = false;
3318       // Make sure we always update StartIdx as we use it to track if all
3319       // elements are undef.
3320       StartIdx[Input] = NewStartIdx;
3321     }
3322 
3323     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3324       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3325       return;
3326     }
3327     if (CanExtract) {
3328       // Extract appropriate subvector and generate a vector shuffle
3329       for (unsigned Input = 0; Input < 2; ++Input) {
3330         SDValue &Src = Input == 0 ? Src1 : Src2;
3331         if (StartIdx[Input] < 0)
3332           Src = DAG.getUNDEF(VT);
3333         else {
3334           Src = DAG.getNode(
3335               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3336               DAG.getConstant(StartIdx[Input], DL,
3337                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3338         }
3339       }
3340 
3341       // Calculate new mask.
3342       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3343       for (int &Idx : MappedOps) {
3344         if (Idx >= (int)SrcNumElts)
3345           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3346         else if (Idx >= 0)
3347           Idx -= StartIdx[0];
3348       }
3349 
3350       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3351       return;
3352     }
3353   }
3354 
3355   // We can't use either concat vectors or extract subvectors so fall back to
3356   // replacing the shuffle with extract and build vector.
3357   // to insert and build vector.
3358   EVT EltVT = VT.getVectorElementType();
3359   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3360   SmallVector<SDValue,8> Ops;
3361   for (int Idx : Mask) {
3362     SDValue Res;
3363 
3364     if (Idx < 0) {
3365       Res = DAG.getUNDEF(EltVT);
3366     } else {
3367       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3368       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3369 
3370       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3371                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3372     }
3373 
3374     Ops.push_back(Res);
3375   }
3376 
3377   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3378 }
3379 
3380 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3381   ArrayRef<unsigned> Indices;
3382   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3383     Indices = IV->getIndices();
3384   else
3385     Indices = cast<ConstantExpr>(&I)->getIndices();
3386 
3387   const Value *Op0 = I.getOperand(0);
3388   const Value *Op1 = I.getOperand(1);
3389   Type *AggTy = I.getType();
3390   Type *ValTy = Op1->getType();
3391   bool IntoUndef = isa<UndefValue>(Op0);
3392   bool FromUndef = isa<UndefValue>(Op1);
3393 
3394   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3395 
3396   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3397   SmallVector<EVT, 4> AggValueVTs;
3398   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3399   SmallVector<EVT, 4> ValValueVTs;
3400   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3401 
3402   unsigned NumAggValues = AggValueVTs.size();
3403   unsigned NumValValues = ValValueVTs.size();
3404   SmallVector<SDValue, 4> Values(NumAggValues);
3405 
3406   // Ignore an insertvalue that produces an empty object
3407   if (!NumAggValues) {
3408     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3409     return;
3410   }
3411 
3412   SDValue Agg = getValue(Op0);
3413   unsigned i = 0;
3414   // Copy the beginning value(s) from the original aggregate.
3415   for (; i != LinearIndex; ++i)
3416     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3417                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3418   // Copy values from the inserted value(s).
3419   if (NumValValues) {
3420     SDValue Val = getValue(Op1);
3421     for (; i != LinearIndex + NumValValues; ++i)
3422       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3423                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3424   }
3425   // Copy remaining value(s) from the original aggregate.
3426   for (; i != NumAggValues; ++i)
3427     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3428                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3429 
3430   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3431                            DAG.getVTList(AggValueVTs), Values));
3432 }
3433 
3434 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3435   ArrayRef<unsigned> Indices;
3436   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3437     Indices = EV->getIndices();
3438   else
3439     Indices = cast<ConstantExpr>(&I)->getIndices();
3440 
3441   const Value *Op0 = I.getOperand(0);
3442   Type *AggTy = Op0->getType();
3443   Type *ValTy = I.getType();
3444   bool OutOfUndef = isa<UndefValue>(Op0);
3445 
3446   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3447 
3448   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3449   SmallVector<EVT, 4> ValValueVTs;
3450   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3451 
3452   unsigned NumValValues = ValValueVTs.size();
3453 
3454   // Ignore a extractvalue that produces an empty object
3455   if (!NumValValues) {
3456     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3457     return;
3458   }
3459 
3460   SmallVector<SDValue, 4> Values(NumValValues);
3461 
3462   SDValue Agg = getValue(Op0);
3463   // Copy out the selected value(s).
3464   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3465     Values[i - LinearIndex] =
3466       OutOfUndef ?
3467         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3468         SDValue(Agg.getNode(), Agg.getResNo() + i);
3469 
3470   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3471                            DAG.getVTList(ValValueVTs), Values));
3472 }
3473 
3474 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3475   Value *Op0 = I.getOperand(0);
3476   // Note that the pointer operand may be a vector of pointers. Take the scalar
3477   // element which holds a pointer.
3478   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3479   SDValue N = getValue(Op0);
3480   SDLoc dl = getCurSDLoc();
3481 
3482   // Normalize Vector GEP - all scalar operands should be converted to the
3483   // splat vector.
3484   unsigned VectorWidth = I.getType()->isVectorTy() ?
3485     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3486 
3487   if (VectorWidth && !N.getValueType().isVector()) {
3488     LLVMContext &Context = *DAG.getContext();
3489     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3490     N = DAG.getSplatBuildVector(VT, dl, N);
3491   }
3492 
3493   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3494        GTI != E; ++GTI) {
3495     const Value *Idx = GTI.getOperand();
3496     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3497       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3498       if (Field) {
3499         // N = N + Offset
3500         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3501 
3502         // In an inbounds GEP with an offset that is nonnegative even when
3503         // interpreted as signed, assume there is no unsigned overflow.
3504         SDNodeFlags Flags;
3505         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3506           Flags.setNoUnsignedWrap(true);
3507 
3508         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3509                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3510       }
3511     } else {
3512       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3513       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3514       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3515 
3516       // If this is a scalar constant or a splat vector of constants,
3517       // handle it quickly.
3518       const auto *CI = dyn_cast<ConstantInt>(Idx);
3519       if (!CI && isa<ConstantDataVector>(Idx) &&
3520           cast<ConstantDataVector>(Idx)->getSplatValue())
3521         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3522 
3523       if (CI) {
3524         if (CI->isZero())
3525           continue;
3526         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3527         LLVMContext &Context = *DAG.getContext();
3528         SDValue OffsVal = VectorWidth ?
3529           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3530           DAG.getConstant(Offs, dl, IdxTy);
3531 
3532         // In an inbouds GEP with an offset that is nonnegative even when
3533         // interpreted as signed, assume there is no unsigned overflow.
3534         SDNodeFlags Flags;
3535         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3536           Flags.setNoUnsignedWrap(true);
3537 
3538         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3539         continue;
3540       }
3541 
3542       // N = N + Idx * ElementSize;
3543       SDValue IdxN = getValue(Idx);
3544 
3545       if (!IdxN.getValueType().isVector() && VectorWidth) {
3546         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3547         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3548       }
3549 
3550       // If the index is smaller or larger than intptr_t, truncate or extend
3551       // it.
3552       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3553 
3554       // If this is a multiply by a power of two, turn it into a shl
3555       // immediately.  This is a very common case.
3556       if (ElementSize != 1) {
3557         if (ElementSize.isPowerOf2()) {
3558           unsigned Amt = ElementSize.logBase2();
3559           IdxN = DAG.getNode(ISD::SHL, dl,
3560                              N.getValueType(), IdxN,
3561                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3562         } else {
3563           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3564           IdxN = DAG.getNode(ISD::MUL, dl,
3565                              N.getValueType(), IdxN, Scale);
3566         }
3567       }
3568 
3569       N = DAG.getNode(ISD::ADD, dl,
3570                       N.getValueType(), N, IdxN);
3571     }
3572   }
3573 
3574   setValue(&I, N);
3575 }
3576 
3577 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3578   // If this is a fixed sized alloca in the entry block of the function,
3579   // allocate it statically on the stack.
3580   if (FuncInfo.StaticAllocaMap.count(&I))
3581     return;   // getValue will auto-populate this.
3582 
3583   SDLoc dl = getCurSDLoc();
3584   Type *Ty = I.getAllocatedType();
3585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3586   auto &DL = DAG.getDataLayout();
3587   uint64_t TySize = DL.getTypeAllocSize(Ty);
3588   unsigned Align =
3589       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3590 
3591   SDValue AllocSize = getValue(I.getArraySize());
3592 
3593   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3594   if (AllocSize.getValueType() != IntPtr)
3595     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3596 
3597   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3598                           AllocSize,
3599                           DAG.getConstant(TySize, dl, IntPtr));
3600 
3601   // Handle alignment.  If the requested alignment is less than or equal to
3602   // the stack alignment, ignore it.  If the size is greater than or equal to
3603   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3604   unsigned StackAlign =
3605       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3606   if (Align <= StackAlign)
3607     Align = 0;
3608 
3609   // Round the size of the allocation up to the stack alignment size
3610   // by add SA-1 to the size. This doesn't overflow because we're computing
3611   // an address inside an alloca.
3612   SDNodeFlags Flags;
3613   Flags.setNoUnsignedWrap(true);
3614   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3615                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3616 
3617   // Mask out the low bits for alignment purposes.
3618   AllocSize =
3619       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3620                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3621 
3622   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3623   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3624   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3625   setValue(&I, DSA);
3626   DAG.setRoot(DSA.getValue(1));
3627 
3628   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3629 }
3630 
3631 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3632   if (I.isAtomic())
3633     return visitAtomicLoad(I);
3634 
3635   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3636   const Value *SV = I.getOperand(0);
3637   if (TLI.supportSwiftError()) {
3638     // Swifterror values can come from either a function parameter with
3639     // swifterror attribute or an alloca with swifterror attribute.
3640     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3641       if (Arg->hasSwiftErrorAttr())
3642         return visitLoadFromSwiftError(I);
3643     }
3644 
3645     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3646       if (Alloca->isSwiftError())
3647         return visitLoadFromSwiftError(I);
3648     }
3649   }
3650 
3651   SDValue Ptr = getValue(SV);
3652 
3653   Type *Ty = I.getType();
3654 
3655   bool isVolatile = I.isVolatile();
3656   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3657   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3658   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3659   unsigned Alignment = I.getAlignment();
3660 
3661   AAMDNodes AAInfo;
3662   I.getAAMetadata(AAInfo);
3663   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3664 
3665   SmallVector<EVT, 4> ValueVTs;
3666   SmallVector<uint64_t, 4> Offsets;
3667   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3668   unsigned NumValues = ValueVTs.size();
3669   if (NumValues == 0)
3670     return;
3671 
3672   SDValue Root;
3673   bool ConstantMemory = false;
3674   if (isVolatile || NumValues > MaxParallelChains)
3675     // Serialize volatile loads with other side effects.
3676     Root = getRoot();
3677   else if (AA && AA->pointsToConstantMemory(MemoryLocation(
3678                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3679     // Do not serialize (non-volatile) loads of constant memory with anything.
3680     Root = DAG.getEntryNode();
3681     ConstantMemory = true;
3682   } else {
3683     // Do not serialize non-volatile loads against each other.
3684     Root = DAG.getRoot();
3685   }
3686 
3687   SDLoc dl = getCurSDLoc();
3688 
3689   if (isVolatile)
3690     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3691 
3692   // An aggregate load cannot wrap around the address space, so offsets to its
3693   // parts don't wrap either.
3694   SDNodeFlags Flags;
3695   Flags.setNoUnsignedWrap(true);
3696 
3697   SmallVector<SDValue, 4> Values(NumValues);
3698   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3699   EVT PtrVT = Ptr.getValueType();
3700   unsigned ChainI = 0;
3701   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3702     // Serializing loads here may result in excessive register pressure, and
3703     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3704     // could recover a bit by hoisting nodes upward in the chain by recognizing
3705     // they are side-effect free or do not alias. The optimizer should really
3706     // avoid this case by converting large object/array copies to llvm.memcpy
3707     // (MaxParallelChains should always remain as failsafe).
3708     if (ChainI == MaxParallelChains) {
3709       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3710       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3711                                   makeArrayRef(Chains.data(), ChainI));
3712       Root = Chain;
3713       ChainI = 0;
3714     }
3715     SDValue A = DAG.getNode(ISD::ADD, dl,
3716                             PtrVT, Ptr,
3717                             DAG.getConstant(Offsets[i], dl, PtrVT),
3718                             Flags);
3719     auto MMOFlags = MachineMemOperand::MONone;
3720     if (isVolatile)
3721       MMOFlags |= MachineMemOperand::MOVolatile;
3722     if (isNonTemporal)
3723       MMOFlags |= MachineMemOperand::MONonTemporal;
3724     if (isInvariant)
3725       MMOFlags |= MachineMemOperand::MOInvariant;
3726     if (isDereferenceable)
3727       MMOFlags |= MachineMemOperand::MODereferenceable;
3728     MMOFlags |= TLI.getMMOFlags(I);
3729 
3730     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3731                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3732                             MMOFlags, AAInfo, Ranges);
3733 
3734     Values[i] = L;
3735     Chains[ChainI] = L.getValue(1);
3736   }
3737 
3738   if (!ConstantMemory) {
3739     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3740                                 makeArrayRef(Chains.data(), ChainI));
3741     if (isVolatile)
3742       DAG.setRoot(Chain);
3743     else
3744       PendingLoads.push_back(Chain);
3745   }
3746 
3747   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3748                            DAG.getVTList(ValueVTs), Values));
3749 }
3750 
3751 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3752   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3753          "call visitStoreToSwiftError when backend supports swifterror");
3754 
3755   SmallVector<EVT, 4> ValueVTs;
3756   SmallVector<uint64_t, 4> Offsets;
3757   const Value *SrcV = I.getOperand(0);
3758   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3759                   SrcV->getType(), ValueVTs, &Offsets);
3760   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3761          "expect a single EVT for swifterror");
3762 
3763   SDValue Src = getValue(SrcV);
3764   // Create a virtual register, then update the virtual register.
3765   unsigned VReg; bool CreatedVReg;
3766   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3767   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3768   // Chain can be getRoot or getControlRoot.
3769   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3770                                       SDValue(Src.getNode(), Src.getResNo()));
3771   DAG.setRoot(CopyNode);
3772   if (CreatedVReg)
3773     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3774 }
3775 
3776 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3777   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3778          "call visitLoadFromSwiftError when backend supports swifterror");
3779 
3780   assert(!I.isVolatile() &&
3781          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3782          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3783          "Support volatile, non temporal, invariant for load_from_swift_error");
3784 
3785   const Value *SV = I.getOperand(0);
3786   Type *Ty = I.getType();
3787   AAMDNodes AAInfo;
3788   I.getAAMetadata(AAInfo);
3789   assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
3790              SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
3791          "load_from_swift_error should not be constant memory");
3792 
3793   SmallVector<EVT, 4> ValueVTs;
3794   SmallVector<uint64_t, 4> Offsets;
3795   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3796                   ValueVTs, &Offsets);
3797   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3798          "expect a single EVT for swifterror");
3799 
3800   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3801   SDValue L = DAG.getCopyFromReg(
3802       getRoot(), getCurSDLoc(),
3803       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3804       ValueVTs[0]);
3805 
3806   setValue(&I, L);
3807 }
3808 
3809 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3810   if (I.isAtomic())
3811     return visitAtomicStore(I);
3812 
3813   const Value *SrcV = I.getOperand(0);
3814   const Value *PtrV = I.getOperand(1);
3815 
3816   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3817   if (TLI.supportSwiftError()) {
3818     // Swifterror values can come from either a function parameter with
3819     // swifterror attribute or an alloca with swifterror attribute.
3820     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3821       if (Arg->hasSwiftErrorAttr())
3822         return visitStoreToSwiftError(I);
3823     }
3824 
3825     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3826       if (Alloca->isSwiftError())
3827         return visitStoreToSwiftError(I);
3828     }
3829   }
3830 
3831   SmallVector<EVT, 4> ValueVTs;
3832   SmallVector<uint64_t, 4> Offsets;
3833   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3834                   SrcV->getType(), ValueVTs, &Offsets);
3835   unsigned NumValues = ValueVTs.size();
3836   if (NumValues == 0)
3837     return;
3838 
3839   // Get the lowered operands. Note that we do this after
3840   // checking if NumResults is zero, because with zero results
3841   // the operands won't have values in the map.
3842   SDValue Src = getValue(SrcV);
3843   SDValue Ptr = getValue(PtrV);
3844 
3845   SDValue Root = getRoot();
3846   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3847   SDLoc dl = getCurSDLoc();
3848   EVT PtrVT = Ptr.getValueType();
3849   unsigned Alignment = I.getAlignment();
3850   AAMDNodes AAInfo;
3851   I.getAAMetadata(AAInfo);
3852 
3853   auto MMOFlags = MachineMemOperand::MONone;
3854   if (I.isVolatile())
3855     MMOFlags |= MachineMemOperand::MOVolatile;
3856   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3857     MMOFlags |= MachineMemOperand::MONonTemporal;
3858   MMOFlags |= TLI.getMMOFlags(I);
3859 
3860   // An aggregate load cannot wrap around the address space, so offsets to its
3861   // parts don't wrap either.
3862   SDNodeFlags Flags;
3863   Flags.setNoUnsignedWrap(true);
3864 
3865   unsigned ChainI = 0;
3866   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3867     // See visitLoad comments.
3868     if (ChainI == MaxParallelChains) {
3869       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3870                                   makeArrayRef(Chains.data(), ChainI));
3871       Root = Chain;
3872       ChainI = 0;
3873     }
3874     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3875                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
3876     SDValue St = DAG.getStore(
3877         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3878         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3879     Chains[ChainI] = St;
3880   }
3881 
3882   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3883                                   makeArrayRef(Chains.data(), ChainI));
3884   DAG.setRoot(StoreNode);
3885 }
3886 
3887 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3888                                            bool IsCompressing) {
3889   SDLoc sdl = getCurSDLoc();
3890 
3891   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3892                            unsigned& Alignment) {
3893     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3894     Src0 = I.getArgOperand(0);
3895     Ptr = I.getArgOperand(1);
3896     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3897     Mask = I.getArgOperand(3);
3898   };
3899   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3900                            unsigned& Alignment) {
3901     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3902     Src0 = I.getArgOperand(0);
3903     Ptr = I.getArgOperand(1);
3904     Mask = I.getArgOperand(2);
3905     Alignment = 0;
3906   };
3907 
3908   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3909   unsigned Alignment;
3910   if (IsCompressing)
3911     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3912   else
3913     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3914 
3915   SDValue Ptr = getValue(PtrOperand);
3916   SDValue Src0 = getValue(Src0Operand);
3917   SDValue Mask = getValue(MaskOperand);
3918 
3919   EVT VT = Src0.getValueType();
3920   if (!Alignment)
3921     Alignment = DAG.getEVTAlignment(VT);
3922 
3923   AAMDNodes AAInfo;
3924   I.getAAMetadata(AAInfo);
3925 
3926   MachineMemOperand *MMO =
3927     DAG.getMachineFunction().
3928     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3929                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3930                           Alignment, AAInfo);
3931   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3932                                          MMO, false /* Truncating */,
3933                                          IsCompressing);
3934   DAG.setRoot(StoreNode);
3935   setValue(&I, StoreNode);
3936 }
3937 
3938 // Get a uniform base for the Gather/Scatter intrinsic.
3939 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3940 // We try to represent it as a base pointer + vector of indices.
3941 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3942 // The first operand of the GEP may be a single pointer or a vector of pointers
3943 // Example:
3944 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3945 //  or
3946 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
3947 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3948 //
3949 // When the first GEP operand is a single pointer - it is the uniform base we
3950 // are looking for. If first operand of the GEP is a splat vector - we
3951 // extract the splat value and use it as a uniform base.
3952 // In all other cases the function returns 'false'.
3953 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
3954                            SDValue &Scale, SelectionDAGBuilder* SDB) {
3955   SelectionDAG& DAG = SDB->DAG;
3956   LLVMContext &Context = *DAG.getContext();
3957 
3958   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3959   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3960   if (!GEP)
3961     return false;
3962 
3963   const Value *GEPPtr = GEP->getPointerOperand();
3964   if (!GEPPtr->getType()->isVectorTy())
3965     Ptr = GEPPtr;
3966   else if (!(Ptr = getSplatValue(GEPPtr)))
3967     return false;
3968 
3969   unsigned FinalIndex = GEP->getNumOperands() - 1;
3970   Value *IndexVal = GEP->getOperand(FinalIndex);
3971 
3972   // Ensure all the other indices are 0.
3973   for (unsigned i = 1; i < FinalIndex; ++i) {
3974     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
3975     if (!C || !C->isZero())
3976       return false;
3977   }
3978 
3979   // The operands of the GEP may be defined in another basic block.
3980   // In this case we'll not find nodes for the operands.
3981   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3982     return false;
3983 
3984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3985   const DataLayout &DL = DAG.getDataLayout();
3986   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
3987                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
3988   Base = SDB->getValue(Ptr);
3989   Index = SDB->getValue(IndexVal);
3990 
3991   if (!Index.getValueType().isVector()) {
3992     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
3993     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
3994     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
3995   }
3996   return true;
3997 }
3998 
3999 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4000   SDLoc sdl = getCurSDLoc();
4001 
4002   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4003   const Value *Ptr = I.getArgOperand(1);
4004   SDValue Src0 = getValue(I.getArgOperand(0));
4005   SDValue Mask = getValue(I.getArgOperand(3));
4006   EVT VT = Src0.getValueType();
4007   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4008   if (!Alignment)
4009     Alignment = DAG.getEVTAlignment(VT);
4010   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4011 
4012   AAMDNodes AAInfo;
4013   I.getAAMetadata(AAInfo);
4014 
4015   SDValue Base;
4016   SDValue Index;
4017   SDValue Scale;
4018   const Value *BasePtr = Ptr;
4019   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4020 
4021   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4022   MachineMemOperand *MMO = DAG.getMachineFunction().
4023     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4024                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4025                          Alignment, AAInfo);
4026   if (!UniformBase) {
4027     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4028     Index = getValue(Ptr);
4029     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4030   }
4031   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4032   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4033                                          Ops, MMO);
4034   DAG.setRoot(Scatter);
4035   setValue(&I, Scatter);
4036 }
4037 
4038 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4039   SDLoc sdl = getCurSDLoc();
4040 
4041   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4042                            unsigned& Alignment) {
4043     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4044     Ptr = I.getArgOperand(0);
4045     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4046     Mask = I.getArgOperand(2);
4047     Src0 = I.getArgOperand(3);
4048   };
4049   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4050                            unsigned& Alignment) {
4051     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4052     Ptr = I.getArgOperand(0);
4053     Alignment = 0;
4054     Mask = I.getArgOperand(1);
4055     Src0 = I.getArgOperand(2);
4056   };
4057 
4058   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4059   unsigned Alignment;
4060   if (IsExpanding)
4061     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4062   else
4063     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4064 
4065   SDValue Ptr = getValue(PtrOperand);
4066   SDValue Src0 = getValue(Src0Operand);
4067   SDValue Mask = getValue(MaskOperand);
4068 
4069   EVT VT = Src0.getValueType();
4070   if (!Alignment)
4071     Alignment = DAG.getEVTAlignment(VT);
4072 
4073   AAMDNodes AAInfo;
4074   I.getAAMetadata(AAInfo);
4075   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4076 
4077   // Do not serialize masked loads of constant memory with anything.
4078   bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
4079       PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
4080   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4081 
4082   MachineMemOperand *MMO =
4083     DAG.getMachineFunction().
4084     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4085                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4086                           Alignment, AAInfo, Ranges);
4087 
4088   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4089                                    ISD::NON_EXTLOAD, IsExpanding);
4090   if (AddToChain)
4091     PendingLoads.push_back(Load.getValue(1));
4092   setValue(&I, Load);
4093 }
4094 
4095 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4096   SDLoc sdl = getCurSDLoc();
4097 
4098   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4099   const Value *Ptr = I.getArgOperand(0);
4100   SDValue Src0 = getValue(I.getArgOperand(3));
4101   SDValue Mask = getValue(I.getArgOperand(2));
4102 
4103   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4104   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4105   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4106   if (!Alignment)
4107     Alignment = DAG.getEVTAlignment(VT);
4108 
4109   AAMDNodes AAInfo;
4110   I.getAAMetadata(AAInfo);
4111   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4112 
4113   SDValue Root = DAG.getRoot();
4114   SDValue Base;
4115   SDValue Index;
4116   SDValue Scale;
4117   const Value *BasePtr = Ptr;
4118   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4119   bool ConstantMemory = false;
4120   if (UniformBase &&
4121       AA && AA->pointsToConstantMemory(MemoryLocation(
4122           BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
4123           AAInfo))) {
4124     // Do not serialize (non-volatile) loads of constant memory with anything.
4125     Root = DAG.getEntryNode();
4126     ConstantMemory = true;
4127   }
4128 
4129   MachineMemOperand *MMO =
4130     DAG.getMachineFunction().
4131     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4132                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4133                          Alignment, AAInfo, Ranges);
4134 
4135   if (!UniformBase) {
4136     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4137     Index = getValue(Ptr);
4138     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4139   }
4140   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4141   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4142                                        Ops, MMO);
4143 
4144   SDValue OutChain = Gather.getValue(1);
4145   if (!ConstantMemory)
4146     PendingLoads.push_back(OutChain);
4147   setValue(&I, Gather);
4148 }
4149 
4150 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4151   SDLoc dl = getCurSDLoc();
4152   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4153   AtomicOrdering FailureOrder = I.getFailureOrdering();
4154   SyncScope::ID SSID = I.getSyncScopeID();
4155 
4156   SDValue InChain = getRoot();
4157 
4158   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4159   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4160   SDValue L = DAG.getAtomicCmpSwap(
4161       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4162       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4163       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4164       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4165 
4166   SDValue OutChain = L.getValue(2);
4167 
4168   setValue(&I, L);
4169   DAG.setRoot(OutChain);
4170 }
4171 
4172 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4173   SDLoc dl = getCurSDLoc();
4174   ISD::NodeType NT;
4175   switch (I.getOperation()) {
4176   default: llvm_unreachable("Unknown atomicrmw operation");
4177   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4178   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4179   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4180   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4181   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4182   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4183   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4184   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4185   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4186   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4187   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4188   }
4189   AtomicOrdering Order = I.getOrdering();
4190   SyncScope::ID SSID = I.getSyncScopeID();
4191 
4192   SDValue InChain = getRoot();
4193 
4194   SDValue L =
4195     DAG.getAtomic(NT, dl,
4196                   getValue(I.getValOperand()).getSimpleValueType(),
4197                   InChain,
4198                   getValue(I.getPointerOperand()),
4199                   getValue(I.getValOperand()),
4200                   I.getPointerOperand(),
4201                   /* Alignment=*/ 0, Order, SSID);
4202 
4203   SDValue OutChain = L.getValue(1);
4204 
4205   setValue(&I, L);
4206   DAG.setRoot(OutChain);
4207 }
4208 
4209 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4210   SDLoc dl = getCurSDLoc();
4211   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4212   SDValue Ops[3];
4213   Ops[0] = getRoot();
4214   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4215                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4216   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4217                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4218   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4219 }
4220 
4221 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4222   SDLoc dl = getCurSDLoc();
4223   AtomicOrdering Order = I.getOrdering();
4224   SyncScope::ID SSID = I.getSyncScopeID();
4225 
4226   SDValue InChain = getRoot();
4227 
4228   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4229   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4230 
4231   if (!TLI.supportsUnalignedAtomics() &&
4232       I.getAlignment() < VT.getStoreSize())
4233     report_fatal_error("Cannot generate unaligned atomic load");
4234 
4235   MachineMemOperand *MMO =
4236       DAG.getMachineFunction().
4237       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4238                            MachineMemOperand::MOVolatile |
4239                            MachineMemOperand::MOLoad,
4240                            VT.getStoreSize(),
4241                            I.getAlignment() ? I.getAlignment() :
4242                                               DAG.getEVTAlignment(VT),
4243                            AAMDNodes(), nullptr, SSID, Order);
4244 
4245   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4246   SDValue L =
4247       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4248                     getValue(I.getPointerOperand()), MMO);
4249 
4250   SDValue OutChain = L.getValue(1);
4251 
4252   setValue(&I, L);
4253   DAG.setRoot(OutChain);
4254 }
4255 
4256 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4257   SDLoc dl = getCurSDLoc();
4258 
4259   AtomicOrdering Order = I.getOrdering();
4260   SyncScope::ID SSID = I.getSyncScopeID();
4261 
4262   SDValue InChain = getRoot();
4263 
4264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4265   EVT VT =
4266       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4267 
4268   if (I.getAlignment() < VT.getStoreSize())
4269     report_fatal_error("Cannot generate unaligned atomic store");
4270 
4271   SDValue OutChain =
4272     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4273                   InChain,
4274                   getValue(I.getPointerOperand()),
4275                   getValue(I.getValueOperand()),
4276                   I.getPointerOperand(), I.getAlignment(),
4277                   Order, SSID);
4278 
4279   DAG.setRoot(OutChain);
4280 }
4281 
4282 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4283 /// node.
4284 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4285                                                unsigned Intrinsic) {
4286   // Ignore the callsite's attributes. A specific call site may be marked with
4287   // readnone, but the lowering code will expect the chain based on the
4288   // definition.
4289   const Function *F = I.getCalledFunction();
4290   bool HasChain = !F->doesNotAccessMemory();
4291   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4292 
4293   // Build the operand list.
4294   SmallVector<SDValue, 8> Ops;
4295   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4296     if (OnlyLoad) {
4297       // We don't need to serialize loads against other loads.
4298       Ops.push_back(DAG.getRoot());
4299     } else {
4300       Ops.push_back(getRoot());
4301     }
4302   }
4303 
4304   // Info is set by getTgtMemInstrinsic
4305   TargetLowering::IntrinsicInfo Info;
4306   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4307   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4308                                                DAG.getMachineFunction(),
4309                                                Intrinsic);
4310 
4311   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4312   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4313       Info.opc == ISD::INTRINSIC_W_CHAIN)
4314     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4315                                         TLI.getPointerTy(DAG.getDataLayout())));
4316 
4317   // Add all operands of the call to the operand list.
4318   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4319     SDValue Op = getValue(I.getArgOperand(i));
4320     Ops.push_back(Op);
4321   }
4322 
4323   SmallVector<EVT, 4> ValueVTs;
4324   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4325 
4326   if (HasChain)
4327     ValueVTs.push_back(MVT::Other);
4328 
4329   SDVTList VTs = DAG.getVTList(ValueVTs);
4330 
4331   // Create the node.
4332   SDValue Result;
4333   if (IsTgtIntrinsic) {
4334     // This is target intrinsic that touches memory
4335     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4336       Ops, Info.memVT,
4337       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4338       Info.flags, Info.size);
4339   } else if (!HasChain) {
4340     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4341   } else if (!I.getType()->isVoidTy()) {
4342     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4343   } else {
4344     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4345   }
4346 
4347   if (HasChain) {
4348     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4349     if (OnlyLoad)
4350       PendingLoads.push_back(Chain);
4351     else
4352       DAG.setRoot(Chain);
4353   }
4354 
4355   if (!I.getType()->isVoidTy()) {
4356     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4357       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4358       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4359     } else
4360       Result = lowerRangeToAssertZExt(DAG, I, Result);
4361 
4362     setValue(&I, Result);
4363   }
4364 }
4365 
4366 /// GetSignificand - Get the significand and build it into a floating-point
4367 /// number with exponent of 1:
4368 ///
4369 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4370 ///
4371 /// where Op is the hexadecimal representation of floating point value.
4372 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4373   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4374                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4375   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4376                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4377   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4378 }
4379 
4380 /// GetExponent - Get the exponent:
4381 ///
4382 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4383 ///
4384 /// where Op is the hexadecimal representation of floating point value.
4385 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4386                            const TargetLowering &TLI, const SDLoc &dl) {
4387   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4388                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4389   SDValue t1 = DAG.getNode(
4390       ISD::SRL, dl, MVT::i32, t0,
4391       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4392   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4393                            DAG.getConstant(127, dl, MVT::i32));
4394   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4395 }
4396 
4397 /// getF32Constant - Get 32-bit floating point constant.
4398 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4399                               const SDLoc &dl) {
4400   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4401                            MVT::f32);
4402 }
4403 
4404 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4405                                        SelectionDAG &DAG) {
4406   // TODO: What fast-math-flags should be set on the floating-point nodes?
4407 
4408   //   IntegerPartOfX = ((int32_t)(t0);
4409   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4410 
4411   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4412   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4413   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4414 
4415   //   IntegerPartOfX <<= 23;
4416   IntegerPartOfX = DAG.getNode(
4417       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4418       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4419                                   DAG.getDataLayout())));
4420 
4421   SDValue TwoToFractionalPartOfX;
4422   if (LimitFloatPrecision <= 6) {
4423     // For floating-point precision of 6:
4424     //
4425     //   TwoToFractionalPartOfX =
4426     //     0.997535578f +
4427     //       (0.735607626f + 0.252464424f * x) * x;
4428     //
4429     // error 0.0144103317, which is 6 bits
4430     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4431                              getF32Constant(DAG, 0x3e814304, dl));
4432     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4433                              getF32Constant(DAG, 0x3f3c50c8, dl));
4434     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4435     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4436                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4437   } else if (LimitFloatPrecision <= 12) {
4438     // For floating-point precision of 12:
4439     //
4440     //   TwoToFractionalPartOfX =
4441     //     0.999892986f +
4442     //       (0.696457318f +
4443     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4444     //
4445     // error 0.000107046256, which is 13 to 14 bits
4446     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4447                              getF32Constant(DAG, 0x3da235e3, dl));
4448     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4449                              getF32Constant(DAG, 0x3e65b8f3, dl));
4450     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4451     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4452                              getF32Constant(DAG, 0x3f324b07, dl));
4453     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4454     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4455                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4456   } else { // LimitFloatPrecision <= 18
4457     // For floating-point precision of 18:
4458     //
4459     //   TwoToFractionalPartOfX =
4460     //     0.999999982f +
4461     //       (0.693148872f +
4462     //         (0.240227044f +
4463     //           (0.554906021e-1f +
4464     //             (0.961591928e-2f +
4465     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4466     // error 2.47208000*10^(-7), which is better than 18 bits
4467     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4468                              getF32Constant(DAG, 0x3924b03e, dl));
4469     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4470                              getF32Constant(DAG, 0x3ab24b87, dl));
4471     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4472     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4473                              getF32Constant(DAG, 0x3c1d8c17, dl));
4474     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4475     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4476                              getF32Constant(DAG, 0x3d634a1d, dl));
4477     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4478     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4479                              getF32Constant(DAG, 0x3e75fe14, dl));
4480     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4481     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4482                               getF32Constant(DAG, 0x3f317234, dl));
4483     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4484     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4485                                          getF32Constant(DAG, 0x3f800000, dl));
4486   }
4487 
4488   // Add the exponent into the result in integer domain.
4489   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4490   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4491                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4492 }
4493 
4494 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4495 /// limited-precision mode.
4496 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4497                          const TargetLowering &TLI) {
4498   if (Op.getValueType() == MVT::f32 &&
4499       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4500 
4501     // Put the exponent in the right bit position for later addition to the
4502     // final result:
4503     //
4504     //   #define LOG2OFe 1.4426950f
4505     //   t0 = Op * LOG2OFe
4506 
4507     // TODO: What fast-math-flags should be set here?
4508     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4509                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4510     return getLimitedPrecisionExp2(t0, dl, DAG);
4511   }
4512 
4513   // No special expansion.
4514   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4515 }
4516 
4517 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4518 /// limited-precision mode.
4519 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4520                          const TargetLowering &TLI) {
4521   // TODO: What fast-math-flags should be set on the floating-point nodes?
4522 
4523   if (Op.getValueType() == MVT::f32 &&
4524       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4525     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4526 
4527     // Scale the exponent by log(2) [0.69314718f].
4528     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4529     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4530                                         getF32Constant(DAG, 0x3f317218, dl));
4531 
4532     // Get the significand and build it into a floating-point number with
4533     // exponent of 1.
4534     SDValue X = GetSignificand(DAG, Op1, dl);
4535 
4536     SDValue LogOfMantissa;
4537     if (LimitFloatPrecision <= 6) {
4538       // For floating-point precision of 6:
4539       //
4540       //   LogofMantissa =
4541       //     -1.1609546f +
4542       //       (1.4034025f - 0.23903021f * x) * x;
4543       //
4544       // error 0.0034276066, which is better than 8 bits
4545       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4546                                getF32Constant(DAG, 0xbe74c456, dl));
4547       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4548                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4549       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4550       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4551                                   getF32Constant(DAG, 0x3f949a29, dl));
4552     } else if (LimitFloatPrecision <= 12) {
4553       // For floating-point precision of 12:
4554       //
4555       //   LogOfMantissa =
4556       //     -1.7417939f +
4557       //       (2.8212026f +
4558       //         (-1.4699568f +
4559       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4560       //
4561       // error 0.000061011436, which is 14 bits
4562       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4563                                getF32Constant(DAG, 0xbd67b6d6, dl));
4564       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4565                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4566       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4567       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4568                                getF32Constant(DAG, 0x3fbc278b, dl));
4569       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4570       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4571                                getF32Constant(DAG, 0x40348e95, dl));
4572       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4573       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4574                                   getF32Constant(DAG, 0x3fdef31a, dl));
4575     } else { // LimitFloatPrecision <= 18
4576       // For floating-point precision of 18:
4577       //
4578       //   LogOfMantissa =
4579       //     -2.1072184f +
4580       //       (4.2372794f +
4581       //         (-3.7029485f +
4582       //           (2.2781945f +
4583       //             (-0.87823314f +
4584       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4585       //
4586       // error 0.0000023660568, which is better than 18 bits
4587       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4588                                getF32Constant(DAG, 0xbc91e5ac, dl));
4589       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4590                                getF32Constant(DAG, 0x3e4350aa, dl));
4591       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4592       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4593                                getF32Constant(DAG, 0x3f60d3e3, dl));
4594       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4595       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4596                                getF32Constant(DAG, 0x4011cdf0, dl));
4597       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4598       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4599                                getF32Constant(DAG, 0x406cfd1c, dl));
4600       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4601       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4602                                getF32Constant(DAG, 0x408797cb, dl));
4603       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4604       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4605                                   getF32Constant(DAG, 0x4006dcab, dl));
4606     }
4607 
4608     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4609   }
4610 
4611   // No special expansion.
4612   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4613 }
4614 
4615 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4616 /// limited-precision mode.
4617 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4618                           const TargetLowering &TLI) {
4619   // TODO: What fast-math-flags should be set on the floating-point nodes?
4620 
4621   if (Op.getValueType() == MVT::f32 &&
4622       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4623     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4624 
4625     // Get the exponent.
4626     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4627 
4628     // Get the significand and build it into a floating-point number with
4629     // exponent of 1.
4630     SDValue X = GetSignificand(DAG, Op1, dl);
4631 
4632     // Different possible minimax approximations of significand in
4633     // floating-point for various degrees of accuracy over [1,2].
4634     SDValue Log2ofMantissa;
4635     if (LimitFloatPrecision <= 6) {
4636       // For floating-point precision of 6:
4637       //
4638       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4639       //
4640       // error 0.0049451742, which is more than 7 bits
4641       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4642                                getF32Constant(DAG, 0xbeb08fe0, dl));
4643       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4644                                getF32Constant(DAG, 0x40019463, dl));
4645       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4646       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4647                                    getF32Constant(DAG, 0x3fd6633d, dl));
4648     } else if (LimitFloatPrecision <= 12) {
4649       // For floating-point precision of 12:
4650       //
4651       //   Log2ofMantissa =
4652       //     -2.51285454f +
4653       //       (4.07009056f +
4654       //         (-2.12067489f +
4655       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4656       //
4657       // error 0.0000876136000, which is better than 13 bits
4658       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4659                                getF32Constant(DAG, 0xbda7262e, dl));
4660       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4661                                getF32Constant(DAG, 0x3f25280b, dl));
4662       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4663       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4664                                getF32Constant(DAG, 0x4007b923, dl));
4665       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4666       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4667                                getF32Constant(DAG, 0x40823e2f, dl));
4668       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4669       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4670                                    getF32Constant(DAG, 0x4020d29c, dl));
4671     } else { // LimitFloatPrecision <= 18
4672       // For floating-point precision of 18:
4673       //
4674       //   Log2ofMantissa =
4675       //     -3.0400495f +
4676       //       (6.1129976f +
4677       //         (-5.3420409f +
4678       //           (3.2865683f +
4679       //             (-1.2669343f +
4680       //               (0.27515199f -
4681       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4682       //
4683       // error 0.0000018516, which is better than 18 bits
4684       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4685                                getF32Constant(DAG, 0xbcd2769e, dl));
4686       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4687                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4688       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4689       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4690                                getF32Constant(DAG, 0x3fa22ae7, dl));
4691       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4692       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4693                                getF32Constant(DAG, 0x40525723, dl));
4694       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4695       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4696                                getF32Constant(DAG, 0x40aaf200, dl));
4697       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4698       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4699                                getF32Constant(DAG, 0x40c39dad, dl));
4700       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4701       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4702                                    getF32Constant(DAG, 0x4042902c, dl));
4703     }
4704 
4705     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4706   }
4707 
4708   // No special expansion.
4709   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4710 }
4711 
4712 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4713 /// limited-precision mode.
4714 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4715                            const TargetLowering &TLI) {
4716   // TODO: What fast-math-flags should be set on the floating-point nodes?
4717 
4718   if (Op.getValueType() == MVT::f32 &&
4719       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4720     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4721 
4722     // Scale the exponent by log10(2) [0.30102999f].
4723     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4724     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4725                                         getF32Constant(DAG, 0x3e9a209a, dl));
4726 
4727     // Get the significand and build it into a floating-point number with
4728     // exponent of 1.
4729     SDValue X = GetSignificand(DAG, Op1, dl);
4730 
4731     SDValue Log10ofMantissa;
4732     if (LimitFloatPrecision <= 6) {
4733       // For floating-point precision of 6:
4734       //
4735       //   Log10ofMantissa =
4736       //     -0.50419619f +
4737       //       (0.60948995f - 0.10380950f * x) * x;
4738       //
4739       // error 0.0014886165, which is 6 bits
4740       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4741                                getF32Constant(DAG, 0xbdd49a13, dl));
4742       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4743                                getF32Constant(DAG, 0x3f1c0789, dl));
4744       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4745       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4746                                     getF32Constant(DAG, 0x3f011300, dl));
4747     } else if (LimitFloatPrecision <= 12) {
4748       // For floating-point precision of 12:
4749       //
4750       //   Log10ofMantissa =
4751       //     -0.64831180f +
4752       //       (0.91751397f +
4753       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4754       //
4755       // error 0.00019228036, which is better than 12 bits
4756       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4757                                getF32Constant(DAG, 0x3d431f31, dl));
4758       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4759                                getF32Constant(DAG, 0x3ea21fb2, dl));
4760       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4761       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4762                                getF32Constant(DAG, 0x3f6ae232, dl));
4763       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4764       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4765                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4766     } else { // LimitFloatPrecision <= 18
4767       // For floating-point precision of 18:
4768       //
4769       //   Log10ofMantissa =
4770       //     -0.84299375f +
4771       //       (1.5327582f +
4772       //         (-1.0688956f +
4773       //           (0.49102474f +
4774       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4775       //
4776       // error 0.0000037995730, which is better than 18 bits
4777       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4778                                getF32Constant(DAG, 0x3c5d51ce, dl));
4779       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4780                                getF32Constant(DAG, 0x3e00685a, dl));
4781       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4782       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4783                                getF32Constant(DAG, 0x3efb6798, dl));
4784       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4785       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4786                                getF32Constant(DAG, 0x3f88d192, dl));
4787       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4788       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4789                                getF32Constant(DAG, 0x3fc4316c, dl));
4790       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4791       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4792                                     getF32Constant(DAG, 0x3f57ce70, dl));
4793     }
4794 
4795     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4796   }
4797 
4798   // No special expansion.
4799   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4800 }
4801 
4802 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4803 /// limited-precision mode.
4804 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4805                           const TargetLowering &TLI) {
4806   if (Op.getValueType() == MVT::f32 &&
4807       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4808     return getLimitedPrecisionExp2(Op, dl, DAG);
4809 
4810   // No special expansion.
4811   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4812 }
4813 
4814 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4815 /// limited-precision mode with x == 10.0f.
4816 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4817                          SelectionDAG &DAG, const TargetLowering &TLI) {
4818   bool IsExp10 = false;
4819   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4820       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4821     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4822       APFloat Ten(10.0f);
4823       IsExp10 = LHSC->isExactlyValue(Ten);
4824     }
4825   }
4826 
4827   // TODO: What fast-math-flags should be set on the FMUL node?
4828   if (IsExp10) {
4829     // Put the exponent in the right bit position for later addition to the
4830     // final result:
4831     //
4832     //   #define LOG2OF10 3.3219281f
4833     //   t0 = Op * LOG2OF10;
4834     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4835                              getF32Constant(DAG, 0x40549a78, dl));
4836     return getLimitedPrecisionExp2(t0, dl, DAG);
4837   }
4838 
4839   // No special expansion.
4840   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4841 }
4842 
4843 /// ExpandPowI - Expand a llvm.powi intrinsic.
4844 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4845                           SelectionDAG &DAG) {
4846   // If RHS is a constant, we can expand this out to a multiplication tree,
4847   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4848   // optimizing for size, we only want to do this if the expansion would produce
4849   // a small number of multiplies, otherwise we do the full expansion.
4850   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4851     // Get the exponent as a positive value.
4852     unsigned Val = RHSC->getSExtValue();
4853     if ((int)Val < 0) Val = -Val;
4854 
4855     // powi(x, 0) -> 1.0
4856     if (Val == 0)
4857       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4858 
4859     const Function &F = DAG.getMachineFunction().getFunction();
4860     if (!F.optForSize() ||
4861         // If optimizing for size, don't insert too many multiplies.
4862         // This inserts up to 5 multiplies.
4863         countPopulation(Val) + Log2_32(Val) < 7) {
4864       // We use the simple binary decomposition method to generate the multiply
4865       // sequence.  There are more optimal ways to do this (for example,
4866       // powi(x,15) generates one more multiply than it should), but this has
4867       // the benefit of being both really simple and much better than a libcall.
4868       SDValue Res;  // Logically starts equal to 1.0
4869       SDValue CurSquare = LHS;
4870       // TODO: Intrinsics should have fast-math-flags that propagate to these
4871       // nodes.
4872       while (Val) {
4873         if (Val & 1) {
4874           if (Res.getNode())
4875             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4876           else
4877             Res = CurSquare;  // 1.0*CurSquare.
4878         }
4879 
4880         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4881                                 CurSquare, CurSquare);
4882         Val >>= 1;
4883       }
4884 
4885       // If the original was negative, invert the result, producing 1/(x*x*x).
4886       if (RHSC->getSExtValue() < 0)
4887         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4888                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4889       return Res;
4890     }
4891   }
4892 
4893   // Otherwise, expand to a libcall.
4894   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4895 }
4896 
4897 // getUnderlyingArgReg - Find underlying register used for a truncated or
4898 // bitcasted argument.
4899 static unsigned getUnderlyingArgReg(const SDValue &N) {
4900   switch (N.getOpcode()) {
4901   case ISD::CopyFromReg:
4902     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4903   case ISD::BITCAST:
4904   case ISD::AssertZext:
4905   case ISD::AssertSext:
4906   case ISD::TRUNCATE:
4907     return getUnderlyingArgReg(N.getOperand(0));
4908   default:
4909     return 0;
4910   }
4911 }
4912 
4913 /// If the DbgValueInst is a dbg_value of a function argument, create the
4914 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
4915 /// instruction selection, they will be inserted to the entry BB.
4916 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4917     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4918     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
4919   const Argument *Arg = dyn_cast<Argument>(V);
4920   if (!Arg)
4921     return false;
4922 
4923   MachineFunction &MF = DAG.getMachineFunction();
4924   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4925 
4926   bool IsIndirect = false;
4927   Optional<MachineOperand> Op;
4928   // Some arguments' frame index is recorded during argument lowering.
4929   int FI = FuncInfo.getArgumentFrameIndex(Arg);
4930   if (FI != std::numeric_limits<int>::max())
4931     Op = MachineOperand::CreateFI(FI);
4932 
4933   if (!Op && N.getNode()) {
4934     unsigned Reg = getUnderlyingArgReg(N);
4935     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4936       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4937       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4938       if (PR)
4939         Reg = PR;
4940     }
4941     if (Reg) {
4942       Op = MachineOperand::CreateReg(Reg, false);
4943       IsIndirect = IsDbgDeclare;
4944     }
4945   }
4946 
4947   if (!Op && N.getNode())
4948     // Check if frame index is available.
4949     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4950       if (FrameIndexSDNode *FINode =
4951           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4952         Op = MachineOperand::CreateFI(FINode->getIndex());
4953 
4954   if (!Op) {
4955     // Check if ValueMap has reg number.
4956     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4957     if (VMI != FuncInfo.ValueMap.end()) {
4958       const auto &TLI = DAG.getTargetLoweringInfo();
4959       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
4960                        V->getType(), getABIRegCopyCC(V));
4961       if (RFV.occupiesMultipleRegs()) {
4962         unsigned Offset = 0;
4963         for (auto RegAndSize : RFV.getRegsAndSizes()) {
4964           Op = MachineOperand::CreateReg(RegAndSize.first, false);
4965           auto FragmentExpr = DIExpression::createFragmentExpression(
4966               Expr, Offset, RegAndSize.second);
4967           if (!FragmentExpr)
4968             continue;
4969           FuncInfo.ArgDbgValues.push_back(
4970               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
4971                       Op->getReg(), Variable, *FragmentExpr));
4972           Offset += RegAndSize.second;
4973         }
4974         return true;
4975       }
4976       Op = MachineOperand::CreateReg(VMI->second, false);
4977       IsIndirect = IsDbgDeclare;
4978     }
4979   }
4980 
4981   if (!Op)
4982     return false;
4983 
4984   assert(Variable->isValidLocationForIntrinsic(DL) &&
4985          "Expected inlined-at fields to agree");
4986   IsIndirect = (Op->isReg()) ? IsIndirect : true;
4987   FuncInfo.ArgDbgValues.push_back(
4988       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4989               *Op, Variable, Expr));
4990 
4991   return true;
4992 }
4993 
4994 /// Return the appropriate SDDbgValue based on N.
4995 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
4996                                              DILocalVariable *Variable,
4997                                              DIExpression *Expr,
4998                                              const DebugLoc &dl,
4999                                              unsigned DbgSDNodeOrder) {
5000   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5001     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5002     // stack slot locations.
5003     //
5004     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5005     // debug values here after optimization:
5006     //
5007     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5008     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5009     //
5010     // Both describe the direct values of their associated variables.
5011     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5012                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5013   }
5014   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5015                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5016 }
5017 
5018 // VisualStudio defines setjmp as _setjmp
5019 #if defined(_MSC_VER) && defined(setjmp) && \
5020                          !defined(setjmp_undefined_for_msvc)
5021 #  pragma push_macro("setjmp")
5022 #  undef setjmp
5023 #  define setjmp_undefined_for_msvc
5024 #endif
5025 
5026 /// Lower the call to the specified intrinsic function. If we want to emit this
5027 /// as a call to a named external function, return the name. Otherwise, lower it
5028 /// and return null.
5029 const char *
5030 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
5031   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5032   SDLoc sdl = getCurSDLoc();
5033   DebugLoc dl = getCurDebugLoc();
5034   SDValue Res;
5035 
5036   switch (Intrinsic) {
5037   default:
5038     // By default, turn this into a target intrinsic node.
5039     visitTargetIntrinsic(I, Intrinsic);
5040     return nullptr;
5041   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5042   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5043   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5044   case Intrinsic::returnaddress:
5045     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5046                              TLI.getPointerTy(DAG.getDataLayout()),
5047                              getValue(I.getArgOperand(0))));
5048     return nullptr;
5049   case Intrinsic::addressofreturnaddress:
5050     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5051                              TLI.getPointerTy(DAG.getDataLayout())));
5052     return nullptr;
5053   case Intrinsic::frameaddress:
5054     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5055                              TLI.getPointerTy(DAG.getDataLayout()),
5056                              getValue(I.getArgOperand(0))));
5057     return nullptr;
5058   case Intrinsic::read_register: {
5059     Value *Reg = I.getArgOperand(0);
5060     SDValue Chain = getRoot();
5061     SDValue RegName =
5062         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5063     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5064     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5065       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5066     setValue(&I, Res);
5067     DAG.setRoot(Res.getValue(1));
5068     return nullptr;
5069   }
5070   case Intrinsic::write_register: {
5071     Value *Reg = I.getArgOperand(0);
5072     Value *RegValue = I.getArgOperand(1);
5073     SDValue Chain = getRoot();
5074     SDValue RegName =
5075         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5076     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5077                             RegName, getValue(RegValue)));
5078     return nullptr;
5079   }
5080   case Intrinsic::setjmp:
5081     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5082   case Intrinsic::longjmp:
5083     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5084   case Intrinsic::memcpy: {
5085     const auto &MCI = cast<MemCpyInst>(I);
5086     SDValue Op1 = getValue(I.getArgOperand(0));
5087     SDValue Op2 = getValue(I.getArgOperand(1));
5088     SDValue Op3 = getValue(I.getArgOperand(2));
5089     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5090     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5091     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5092     unsigned Align = MinAlign(DstAlign, SrcAlign);
5093     bool isVol = MCI.isVolatile();
5094     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5095     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5096     // node.
5097     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5098                                false, isTC,
5099                                MachinePointerInfo(I.getArgOperand(0)),
5100                                MachinePointerInfo(I.getArgOperand(1)));
5101     updateDAGForMaybeTailCall(MC);
5102     return nullptr;
5103   }
5104   case Intrinsic::memset: {
5105     const auto &MSI = cast<MemSetInst>(I);
5106     SDValue Op1 = getValue(I.getArgOperand(0));
5107     SDValue Op2 = getValue(I.getArgOperand(1));
5108     SDValue Op3 = getValue(I.getArgOperand(2));
5109     // @llvm.memset defines 0 and 1 to both mean no alignment.
5110     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5111     bool isVol = MSI.isVolatile();
5112     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5113     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5114                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5115     updateDAGForMaybeTailCall(MS);
5116     return nullptr;
5117   }
5118   case Intrinsic::memmove: {
5119     const auto &MMI = cast<MemMoveInst>(I);
5120     SDValue Op1 = getValue(I.getArgOperand(0));
5121     SDValue Op2 = getValue(I.getArgOperand(1));
5122     SDValue Op3 = getValue(I.getArgOperand(2));
5123     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5124     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5125     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5126     unsigned Align = MinAlign(DstAlign, SrcAlign);
5127     bool isVol = MMI.isVolatile();
5128     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5129     // FIXME: Support passing different dest/src alignments to the memmove DAG
5130     // node.
5131     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5132                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5133                                 MachinePointerInfo(I.getArgOperand(1)));
5134     updateDAGForMaybeTailCall(MM);
5135     return nullptr;
5136   }
5137   case Intrinsic::memcpy_element_unordered_atomic: {
5138     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5139     SDValue Dst = getValue(MI.getRawDest());
5140     SDValue Src = getValue(MI.getRawSource());
5141     SDValue Length = getValue(MI.getLength());
5142 
5143     unsigned DstAlign = MI.getDestAlignment();
5144     unsigned SrcAlign = MI.getSourceAlignment();
5145     Type *LengthTy = MI.getLength()->getType();
5146     unsigned ElemSz = MI.getElementSizeInBytes();
5147     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5148     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5149                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5150                                      MachinePointerInfo(MI.getRawDest()),
5151                                      MachinePointerInfo(MI.getRawSource()));
5152     updateDAGForMaybeTailCall(MC);
5153     return nullptr;
5154   }
5155   case Intrinsic::memmove_element_unordered_atomic: {
5156     auto &MI = cast<AtomicMemMoveInst>(I);
5157     SDValue Dst = getValue(MI.getRawDest());
5158     SDValue Src = getValue(MI.getRawSource());
5159     SDValue Length = getValue(MI.getLength());
5160 
5161     unsigned DstAlign = MI.getDestAlignment();
5162     unsigned SrcAlign = MI.getSourceAlignment();
5163     Type *LengthTy = MI.getLength()->getType();
5164     unsigned ElemSz = MI.getElementSizeInBytes();
5165     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5166     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5167                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5168                                       MachinePointerInfo(MI.getRawDest()),
5169                                       MachinePointerInfo(MI.getRawSource()));
5170     updateDAGForMaybeTailCall(MC);
5171     return nullptr;
5172   }
5173   case Intrinsic::memset_element_unordered_atomic: {
5174     auto &MI = cast<AtomicMemSetInst>(I);
5175     SDValue Dst = getValue(MI.getRawDest());
5176     SDValue Val = getValue(MI.getValue());
5177     SDValue Length = getValue(MI.getLength());
5178 
5179     unsigned DstAlign = MI.getDestAlignment();
5180     Type *LengthTy = MI.getLength()->getType();
5181     unsigned ElemSz = MI.getElementSizeInBytes();
5182     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5183     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5184                                      LengthTy, ElemSz, isTC,
5185                                      MachinePointerInfo(MI.getRawDest()));
5186     updateDAGForMaybeTailCall(MC);
5187     return nullptr;
5188   }
5189   case Intrinsic::dbg_addr:
5190   case Intrinsic::dbg_declare: {
5191     const auto &DI = cast<DbgVariableIntrinsic>(I);
5192     DILocalVariable *Variable = DI.getVariable();
5193     DIExpression *Expression = DI.getExpression();
5194     dropDanglingDebugInfo(Variable, Expression);
5195     assert(Variable && "Missing variable");
5196 
5197     // Check if address has undef value.
5198     const Value *Address = DI.getVariableLocation();
5199     if (!Address || isa<UndefValue>(Address) ||
5200         (Address->use_empty() && !isa<Argument>(Address))) {
5201       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5202       return nullptr;
5203     }
5204 
5205     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5206 
5207     // Check if this variable can be described by a frame index, typically
5208     // either as a static alloca or a byval parameter.
5209     int FI = std::numeric_limits<int>::max();
5210     if (const auto *AI =
5211             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5212       if (AI->isStaticAlloca()) {
5213         auto I = FuncInfo.StaticAllocaMap.find(AI);
5214         if (I != FuncInfo.StaticAllocaMap.end())
5215           FI = I->second;
5216       }
5217     } else if (const auto *Arg = dyn_cast<Argument>(
5218                    Address->stripInBoundsConstantOffsets())) {
5219       FI = FuncInfo.getArgumentFrameIndex(Arg);
5220     }
5221 
5222     // llvm.dbg.addr is control dependent and always generates indirect
5223     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5224     // the MachineFunction variable table.
5225     if (FI != std::numeric_limits<int>::max()) {
5226       if (Intrinsic == Intrinsic::dbg_addr) {
5227         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5228             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5229         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5230       }
5231       return nullptr;
5232     }
5233 
5234     SDValue &N = NodeMap[Address];
5235     if (!N.getNode() && isa<Argument>(Address))
5236       // Check unused arguments map.
5237       N = UnusedArgNodeMap[Address];
5238     SDDbgValue *SDV;
5239     if (N.getNode()) {
5240       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5241         Address = BCI->getOperand(0);
5242       // Parameters are handled specially.
5243       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5244       if (isParameter && FINode) {
5245         // Byval parameter. We have a frame index at this point.
5246         SDV =
5247             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5248                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5249       } else if (isa<Argument>(Address)) {
5250         // Address is an argument, so try to emit its dbg value using
5251         // virtual register info from the FuncInfo.ValueMap.
5252         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5253         return nullptr;
5254       } else {
5255         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5256                               true, dl, SDNodeOrder);
5257       }
5258       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5259     } else {
5260       // If Address is an argument then try to emit its dbg value using
5261       // virtual register info from the FuncInfo.ValueMap.
5262       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5263                                     N)) {
5264         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5265       }
5266     }
5267     return nullptr;
5268   }
5269   case Intrinsic::dbg_label: {
5270     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5271     DILabel *Label = DI.getLabel();
5272     assert(Label && "Missing label");
5273 
5274     SDDbgLabel *SDV;
5275     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5276     DAG.AddDbgLabel(SDV);
5277     return nullptr;
5278   }
5279   case Intrinsic::dbg_value: {
5280     const DbgValueInst &DI = cast<DbgValueInst>(I);
5281     assert(DI.getVariable() && "Missing variable");
5282 
5283     DILocalVariable *Variable = DI.getVariable();
5284     DIExpression *Expression = DI.getExpression();
5285     dropDanglingDebugInfo(Variable, Expression);
5286     const Value *V = DI.getValue();
5287     if (!V)
5288       return nullptr;
5289 
5290     SDDbgValue *SDV;
5291     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
5292       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5293       DAG.AddDbgValue(SDV, nullptr, false);
5294       return nullptr;
5295     }
5296 
5297     // Do not use getValue() in here; we don't want to generate code at
5298     // this point if it hasn't been done yet.
5299     SDValue N = NodeMap[V];
5300     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5301       N = UnusedArgNodeMap[V];
5302     if (N.getNode()) {
5303       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5304         return nullptr;
5305       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5306       DAG.AddDbgValue(SDV, N.getNode(), false);
5307       return nullptr;
5308     }
5309 
5310     // PHI nodes have already been selected, so we should know which VReg that
5311     // is assigns to already.
5312     if (isa<PHINode>(V)) {
5313       auto VMI = FuncInfo.ValueMap.find(V);
5314       if (VMI != FuncInfo.ValueMap.end()) {
5315         unsigned Reg = VMI->second;
5316         // The PHI node may be split up into several MI PHI nodes (in
5317         // FunctionLoweringInfo::set).
5318         RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
5319                          V->getType(), None);
5320         if (RFV.occupiesMultipleRegs()) {
5321           unsigned Offset = 0;
5322           unsigned BitsToDescribe = 0;
5323           if (auto VarSize = Variable->getSizeInBits())
5324             BitsToDescribe = *VarSize;
5325           if (auto Fragment = Expression->getFragmentInfo())
5326             BitsToDescribe = Fragment->SizeInBits;
5327           for (auto RegAndSize : RFV.getRegsAndSizes()) {
5328             unsigned RegisterSize = RegAndSize.second;
5329             // Bail out if all bits are described already.
5330             if (Offset >= BitsToDescribe)
5331               break;
5332             unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
5333                 ? BitsToDescribe - Offset
5334                 : RegisterSize;
5335             auto FragmentExpr = DIExpression::createFragmentExpression(
5336                 Expression, Offset, FragmentSize);
5337             if (!FragmentExpr)
5338                 continue;
5339             SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
5340                                       false, dl, SDNodeOrder);
5341             DAG.AddDbgValue(SDV, nullptr, false);
5342             Offset += RegisterSize;
5343           }
5344         } else {
5345           SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
5346                                     SDNodeOrder);
5347           DAG.AddDbgValue(SDV, nullptr, false);
5348         }
5349         return nullptr;
5350       }
5351     }
5352 
5353     // TODO: When we get here we will either drop the dbg.value completely, or
5354     // we try to move it forward by letting it dangle for awhile. So we should
5355     // probably add an extra DbgValue to the DAG here, with a reference to
5356     // "noreg", to indicate that we have lost the debug location for the
5357     // variable.
5358 
5359     if (!V->use_empty() ) {
5360       // Do not call getValue(V) yet, as we don't want to generate code.
5361       // Remember it for later.
5362       DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5363       return nullptr;
5364     }
5365 
5366     LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5367     LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5368     return nullptr;
5369   }
5370 
5371   case Intrinsic::eh_typeid_for: {
5372     // Find the type id for the given typeinfo.
5373     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5374     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5375     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5376     setValue(&I, Res);
5377     return nullptr;
5378   }
5379 
5380   case Intrinsic::eh_return_i32:
5381   case Intrinsic::eh_return_i64:
5382     DAG.getMachineFunction().setCallsEHReturn(true);
5383     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5384                             MVT::Other,
5385                             getControlRoot(),
5386                             getValue(I.getArgOperand(0)),
5387                             getValue(I.getArgOperand(1))));
5388     return nullptr;
5389   case Intrinsic::eh_unwind_init:
5390     DAG.getMachineFunction().setCallsUnwindInit(true);
5391     return nullptr;
5392   case Intrinsic::eh_dwarf_cfa:
5393     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5394                              TLI.getPointerTy(DAG.getDataLayout()),
5395                              getValue(I.getArgOperand(0))));
5396     return nullptr;
5397   case Intrinsic::eh_sjlj_callsite: {
5398     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5399     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5400     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5401     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5402 
5403     MMI.setCurrentCallSite(CI->getZExtValue());
5404     return nullptr;
5405   }
5406   case Intrinsic::eh_sjlj_functioncontext: {
5407     // Get and store the index of the function context.
5408     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5409     AllocaInst *FnCtx =
5410       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5411     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5412     MFI.setFunctionContextIndex(FI);
5413     return nullptr;
5414   }
5415   case Intrinsic::eh_sjlj_setjmp: {
5416     SDValue Ops[2];
5417     Ops[0] = getRoot();
5418     Ops[1] = getValue(I.getArgOperand(0));
5419     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5420                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5421     setValue(&I, Op.getValue(0));
5422     DAG.setRoot(Op.getValue(1));
5423     return nullptr;
5424   }
5425   case Intrinsic::eh_sjlj_longjmp:
5426     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5427                             getRoot(), getValue(I.getArgOperand(0))));
5428     return nullptr;
5429   case Intrinsic::eh_sjlj_setup_dispatch:
5430     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5431                             getRoot()));
5432     return nullptr;
5433   case Intrinsic::masked_gather:
5434     visitMaskedGather(I);
5435     return nullptr;
5436   case Intrinsic::masked_load:
5437     visitMaskedLoad(I);
5438     return nullptr;
5439   case Intrinsic::masked_scatter:
5440     visitMaskedScatter(I);
5441     return nullptr;
5442   case Intrinsic::masked_store:
5443     visitMaskedStore(I);
5444     return nullptr;
5445   case Intrinsic::masked_expandload:
5446     visitMaskedLoad(I, true /* IsExpanding */);
5447     return nullptr;
5448   case Intrinsic::masked_compressstore:
5449     visitMaskedStore(I, true /* IsCompressing */);
5450     return nullptr;
5451   case Intrinsic::x86_mmx_pslli_w:
5452   case Intrinsic::x86_mmx_pslli_d:
5453   case Intrinsic::x86_mmx_pslli_q:
5454   case Intrinsic::x86_mmx_psrli_w:
5455   case Intrinsic::x86_mmx_psrli_d:
5456   case Intrinsic::x86_mmx_psrli_q:
5457   case Intrinsic::x86_mmx_psrai_w:
5458   case Intrinsic::x86_mmx_psrai_d: {
5459     SDValue ShAmt = getValue(I.getArgOperand(1));
5460     if (isa<ConstantSDNode>(ShAmt)) {
5461       visitTargetIntrinsic(I, Intrinsic);
5462       return nullptr;
5463     }
5464     unsigned NewIntrinsic = 0;
5465     EVT ShAmtVT = MVT::v2i32;
5466     switch (Intrinsic) {
5467     case Intrinsic::x86_mmx_pslli_w:
5468       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5469       break;
5470     case Intrinsic::x86_mmx_pslli_d:
5471       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5472       break;
5473     case Intrinsic::x86_mmx_pslli_q:
5474       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5475       break;
5476     case Intrinsic::x86_mmx_psrli_w:
5477       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5478       break;
5479     case Intrinsic::x86_mmx_psrli_d:
5480       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5481       break;
5482     case Intrinsic::x86_mmx_psrli_q:
5483       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5484       break;
5485     case Intrinsic::x86_mmx_psrai_w:
5486       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5487       break;
5488     case Intrinsic::x86_mmx_psrai_d:
5489       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5490       break;
5491     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5492     }
5493 
5494     // The vector shift intrinsics with scalars uses 32b shift amounts but
5495     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5496     // to be zero.
5497     // We must do this early because v2i32 is not a legal type.
5498     SDValue ShOps[2];
5499     ShOps[0] = ShAmt;
5500     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5501     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5502     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5503     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5504     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5505                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5506                        getValue(I.getArgOperand(0)), ShAmt);
5507     setValue(&I, Res);
5508     return nullptr;
5509   }
5510   case Intrinsic::powi:
5511     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5512                             getValue(I.getArgOperand(1)), DAG));
5513     return nullptr;
5514   case Intrinsic::log:
5515     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5516     return nullptr;
5517   case Intrinsic::log2:
5518     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5519     return nullptr;
5520   case Intrinsic::log10:
5521     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5522     return nullptr;
5523   case Intrinsic::exp:
5524     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5525     return nullptr;
5526   case Intrinsic::exp2:
5527     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5528     return nullptr;
5529   case Intrinsic::pow:
5530     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5531                            getValue(I.getArgOperand(1)), DAG, TLI));
5532     return nullptr;
5533   case Intrinsic::sqrt:
5534   case Intrinsic::fabs:
5535   case Intrinsic::sin:
5536   case Intrinsic::cos:
5537   case Intrinsic::floor:
5538   case Intrinsic::ceil:
5539   case Intrinsic::trunc:
5540   case Intrinsic::rint:
5541   case Intrinsic::nearbyint:
5542   case Intrinsic::round:
5543   case Intrinsic::canonicalize: {
5544     unsigned Opcode;
5545     switch (Intrinsic) {
5546     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5547     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5548     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5549     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5550     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5551     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5552     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5553     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5554     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5555     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5556     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5557     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5558     }
5559 
5560     setValue(&I, DAG.getNode(Opcode, sdl,
5561                              getValue(I.getArgOperand(0)).getValueType(),
5562                              getValue(I.getArgOperand(0))));
5563     return nullptr;
5564   }
5565   case Intrinsic::minnum: {
5566     auto VT = getValue(I.getArgOperand(0)).getValueType();
5567     unsigned Opc =
5568         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
5569             ? ISD::FMINIMUM
5570             : ISD::FMINNUM;
5571     setValue(&I, DAG.getNode(Opc, sdl, VT,
5572                              getValue(I.getArgOperand(0)),
5573                              getValue(I.getArgOperand(1))));
5574     return nullptr;
5575   }
5576   case Intrinsic::maxnum: {
5577     auto VT = getValue(I.getArgOperand(0)).getValueType();
5578     unsigned Opc =
5579         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
5580             ? ISD::FMAXIMUM
5581             : ISD::FMAXNUM;
5582     setValue(&I, DAG.getNode(Opc, sdl, VT,
5583                              getValue(I.getArgOperand(0)),
5584                              getValue(I.getArgOperand(1))));
5585     return nullptr;
5586   }
5587   case Intrinsic::minimum:
5588     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
5589                              getValue(I.getArgOperand(0)).getValueType(),
5590                              getValue(I.getArgOperand(0)),
5591                              getValue(I.getArgOperand(1))));
5592     return nullptr;
5593   case Intrinsic::maximum:
5594     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
5595                              getValue(I.getArgOperand(0)).getValueType(),
5596                              getValue(I.getArgOperand(0)),
5597                              getValue(I.getArgOperand(1))));
5598     return nullptr;
5599   case Intrinsic::copysign:
5600     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5601                              getValue(I.getArgOperand(0)).getValueType(),
5602                              getValue(I.getArgOperand(0)),
5603                              getValue(I.getArgOperand(1))));
5604     return nullptr;
5605   case Intrinsic::fma:
5606     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5607                              getValue(I.getArgOperand(0)).getValueType(),
5608                              getValue(I.getArgOperand(0)),
5609                              getValue(I.getArgOperand(1)),
5610                              getValue(I.getArgOperand(2))));
5611     return nullptr;
5612   case Intrinsic::experimental_constrained_fadd:
5613   case Intrinsic::experimental_constrained_fsub:
5614   case Intrinsic::experimental_constrained_fmul:
5615   case Intrinsic::experimental_constrained_fdiv:
5616   case Intrinsic::experimental_constrained_frem:
5617   case Intrinsic::experimental_constrained_fma:
5618   case Intrinsic::experimental_constrained_sqrt:
5619   case Intrinsic::experimental_constrained_pow:
5620   case Intrinsic::experimental_constrained_powi:
5621   case Intrinsic::experimental_constrained_sin:
5622   case Intrinsic::experimental_constrained_cos:
5623   case Intrinsic::experimental_constrained_exp:
5624   case Intrinsic::experimental_constrained_exp2:
5625   case Intrinsic::experimental_constrained_log:
5626   case Intrinsic::experimental_constrained_log10:
5627   case Intrinsic::experimental_constrained_log2:
5628   case Intrinsic::experimental_constrained_rint:
5629   case Intrinsic::experimental_constrained_nearbyint:
5630     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5631     return nullptr;
5632   case Intrinsic::fmuladd: {
5633     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5634     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5635         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5636       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5637                                getValue(I.getArgOperand(0)).getValueType(),
5638                                getValue(I.getArgOperand(0)),
5639                                getValue(I.getArgOperand(1)),
5640                                getValue(I.getArgOperand(2))));
5641     } else {
5642       // TODO: Intrinsic calls should have fast-math-flags.
5643       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5644                                 getValue(I.getArgOperand(0)).getValueType(),
5645                                 getValue(I.getArgOperand(0)),
5646                                 getValue(I.getArgOperand(1)));
5647       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5648                                 getValue(I.getArgOperand(0)).getValueType(),
5649                                 Mul,
5650                                 getValue(I.getArgOperand(2)));
5651       setValue(&I, Add);
5652     }
5653     return nullptr;
5654   }
5655   case Intrinsic::convert_to_fp16:
5656     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5657                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5658                                          getValue(I.getArgOperand(0)),
5659                                          DAG.getTargetConstant(0, sdl,
5660                                                                MVT::i32))));
5661     return nullptr;
5662   case Intrinsic::convert_from_fp16:
5663     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5664                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5665                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5666                                          getValue(I.getArgOperand(0)))));
5667     return nullptr;
5668   case Intrinsic::pcmarker: {
5669     SDValue Tmp = getValue(I.getArgOperand(0));
5670     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5671     return nullptr;
5672   }
5673   case Intrinsic::readcyclecounter: {
5674     SDValue Op = getRoot();
5675     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5676                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5677     setValue(&I, Res);
5678     DAG.setRoot(Res.getValue(1));
5679     return nullptr;
5680   }
5681   case Intrinsic::bitreverse:
5682     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5683                              getValue(I.getArgOperand(0)).getValueType(),
5684                              getValue(I.getArgOperand(0))));
5685     return nullptr;
5686   case Intrinsic::bswap:
5687     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5688                              getValue(I.getArgOperand(0)).getValueType(),
5689                              getValue(I.getArgOperand(0))));
5690     return nullptr;
5691   case Intrinsic::cttz: {
5692     SDValue Arg = getValue(I.getArgOperand(0));
5693     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5694     EVT Ty = Arg.getValueType();
5695     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5696                              sdl, Ty, Arg));
5697     return nullptr;
5698   }
5699   case Intrinsic::ctlz: {
5700     SDValue Arg = getValue(I.getArgOperand(0));
5701     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5702     EVT Ty = Arg.getValueType();
5703     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5704                              sdl, Ty, Arg));
5705     return nullptr;
5706   }
5707   case Intrinsic::ctpop: {
5708     SDValue Arg = getValue(I.getArgOperand(0));
5709     EVT Ty = Arg.getValueType();
5710     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5711     return nullptr;
5712   }
5713   case Intrinsic::fshl:
5714   case Intrinsic::fshr: {
5715     bool IsFSHL = Intrinsic == Intrinsic::fshl;
5716     SDValue X = getValue(I.getArgOperand(0));
5717     SDValue Y = getValue(I.getArgOperand(1));
5718     SDValue Z = getValue(I.getArgOperand(2));
5719     EVT VT = X.getValueType();
5720     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
5721     SDValue Zero = DAG.getConstant(0, sdl, VT);
5722     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
5723 
5724     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
5725     // avoid the select that is necessary in the general case to filter out
5726     // the 0-shift possibility that leads to UB.
5727     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
5728       // TODO: This should also be done if the operation is custom, but we have
5729       // to make sure targets are handling the modulo shift amount as expected.
5730       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
5731       if (TLI.isOperationLegal(RotateOpcode, VT)) {
5732         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
5733         return nullptr;
5734       }
5735 
5736       // Some targets only rotate one way. Try the opposite direction.
5737       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
5738       if (TLI.isOperationLegal(RotateOpcode, VT)) {
5739         // Negate the shift amount because it is safe to ignore the high bits.
5740         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5741         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
5742         return nullptr;
5743       }
5744 
5745       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
5746       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
5747       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5748       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
5749       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
5750       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
5751       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
5752       return nullptr;
5753     }
5754 
5755     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
5756     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
5757     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
5758     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
5759     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
5760     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
5761 
5762     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
5763     // and that is undefined. We must compare and select to avoid UB.
5764     EVT CCVT = MVT::i1;
5765     if (VT.isVector())
5766       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
5767 
5768     // For fshl, 0-shift returns the 1st arg (X).
5769     // For fshr, 0-shift returns the 2nd arg (Y).
5770     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
5771     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
5772     return nullptr;
5773   }
5774   case Intrinsic::sadd_sat: {
5775     SDValue Op1 = getValue(I.getArgOperand(0));
5776     SDValue Op2 = getValue(I.getArgOperand(1));
5777     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
5778     return nullptr;
5779   }
5780   case Intrinsic::uadd_sat: {
5781     SDValue Op1 = getValue(I.getArgOperand(0));
5782     SDValue Op2 = getValue(I.getArgOperand(1));
5783     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
5784     return nullptr;
5785   }
5786   case Intrinsic::ssub_sat: {
5787     SDValue Op1 = getValue(I.getArgOperand(0));
5788     SDValue Op2 = getValue(I.getArgOperand(1));
5789     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
5790     return nullptr;
5791   }
5792   case Intrinsic::usub_sat: {
5793     SDValue Op1 = getValue(I.getArgOperand(0));
5794     SDValue Op2 = getValue(I.getArgOperand(1));
5795     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
5796     return nullptr;
5797   }
5798   case Intrinsic::stacksave: {
5799     SDValue Op = getRoot();
5800     Res = DAG.getNode(
5801         ISD::STACKSAVE, sdl,
5802         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5803     setValue(&I, Res);
5804     DAG.setRoot(Res.getValue(1));
5805     return nullptr;
5806   }
5807   case Intrinsic::stackrestore:
5808     Res = getValue(I.getArgOperand(0));
5809     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5810     return nullptr;
5811   case Intrinsic::get_dynamic_area_offset: {
5812     SDValue Op = getRoot();
5813     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5814     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5815     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5816     // target.
5817     if (PtrTy != ResTy)
5818       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5819                          " intrinsic!");
5820     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5821                       Op);
5822     DAG.setRoot(Op);
5823     setValue(&I, Res);
5824     return nullptr;
5825   }
5826   case Intrinsic::stackguard: {
5827     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5828     MachineFunction &MF = DAG.getMachineFunction();
5829     const Module &M = *MF.getFunction().getParent();
5830     SDValue Chain = getRoot();
5831     if (TLI.useLoadStackGuardNode()) {
5832       Res = getLoadStackGuard(DAG, sdl, Chain);
5833     } else {
5834       const Value *Global = TLI.getSDagStackGuard(M);
5835       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5836       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5837                         MachinePointerInfo(Global, 0), Align,
5838                         MachineMemOperand::MOVolatile);
5839     }
5840     if (TLI.useStackGuardXorFP())
5841       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
5842     DAG.setRoot(Chain);
5843     setValue(&I, Res);
5844     return nullptr;
5845   }
5846   case Intrinsic::stackprotector: {
5847     // Emit code into the DAG to store the stack guard onto the stack.
5848     MachineFunction &MF = DAG.getMachineFunction();
5849     MachineFrameInfo &MFI = MF.getFrameInfo();
5850     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5851     SDValue Src, Chain = getRoot();
5852 
5853     if (TLI.useLoadStackGuardNode())
5854       Src = getLoadStackGuard(DAG, sdl, Chain);
5855     else
5856       Src = getValue(I.getArgOperand(0));   // The guard's value.
5857 
5858     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5859 
5860     int FI = FuncInfo.StaticAllocaMap[Slot];
5861     MFI.setStackProtectorIndex(FI);
5862 
5863     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5864 
5865     // Store the stack protector onto the stack.
5866     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5867                                                  DAG.getMachineFunction(), FI),
5868                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5869     setValue(&I, Res);
5870     DAG.setRoot(Res);
5871     return nullptr;
5872   }
5873   case Intrinsic::objectsize: {
5874     // If we don't know by now, we're never going to know.
5875     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5876 
5877     assert(CI && "Non-constant type in __builtin_object_size?");
5878 
5879     SDValue Arg = getValue(I.getCalledValue());
5880     EVT Ty = Arg.getValueType();
5881 
5882     if (CI->isZero())
5883       Res = DAG.getConstant(-1ULL, sdl, Ty);
5884     else
5885       Res = DAG.getConstant(0, sdl, Ty);
5886 
5887     setValue(&I, Res);
5888     return nullptr;
5889   }
5890   case Intrinsic::annotation:
5891   case Intrinsic::ptr_annotation:
5892   case Intrinsic::launder_invariant_group:
5893   case Intrinsic::strip_invariant_group:
5894     // Drop the intrinsic, but forward the value
5895     setValue(&I, getValue(I.getOperand(0)));
5896     return nullptr;
5897   case Intrinsic::assume:
5898   case Intrinsic::var_annotation:
5899   case Intrinsic::sideeffect:
5900     // Discard annotate attributes, assumptions, and artificial side-effects.
5901     return nullptr;
5902 
5903   case Intrinsic::codeview_annotation: {
5904     // Emit a label associated with this metadata.
5905     MachineFunction &MF = DAG.getMachineFunction();
5906     MCSymbol *Label =
5907         MF.getMMI().getContext().createTempSymbol("annotation", true);
5908     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
5909     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
5910     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
5911     DAG.setRoot(Res);
5912     return nullptr;
5913   }
5914 
5915   case Intrinsic::init_trampoline: {
5916     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5917 
5918     SDValue Ops[6];
5919     Ops[0] = getRoot();
5920     Ops[1] = getValue(I.getArgOperand(0));
5921     Ops[2] = getValue(I.getArgOperand(1));
5922     Ops[3] = getValue(I.getArgOperand(2));
5923     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5924     Ops[5] = DAG.getSrcValue(F);
5925 
5926     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5927 
5928     DAG.setRoot(Res);
5929     return nullptr;
5930   }
5931   case Intrinsic::adjust_trampoline:
5932     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5933                              TLI.getPointerTy(DAG.getDataLayout()),
5934                              getValue(I.getArgOperand(0))));
5935     return nullptr;
5936   case Intrinsic::gcroot: {
5937     assert(DAG.getMachineFunction().getFunction().hasGC() &&
5938            "only valid in functions with gc specified, enforced by Verifier");
5939     assert(GFI && "implied by previous");
5940     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5941     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5942 
5943     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5944     GFI->addStackRoot(FI->getIndex(), TypeMap);
5945     return nullptr;
5946   }
5947   case Intrinsic::gcread:
5948   case Intrinsic::gcwrite:
5949     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5950   case Intrinsic::flt_rounds:
5951     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5952     return nullptr;
5953 
5954   case Intrinsic::expect:
5955     // Just replace __builtin_expect(exp, c) with EXP.
5956     setValue(&I, getValue(I.getArgOperand(0)));
5957     return nullptr;
5958 
5959   case Intrinsic::debugtrap:
5960   case Intrinsic::trap: {
5961     StringRef TrapFuncName =
5962         I.getAttributes()
5963             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
5964             .getValueAsString();
5965     if (TrapFuncName.empty()) {
5966       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5967         ISD::TRAP : ISD::DEBUGTRAP;
5968       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5969       return nullptr;
5970     }
5971     TargetLowering::ArgListTy Args;
5972 
5973     TargetLowering::CallLoweringInfo CLI(DAG);
5974     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5975         CallingConv::C, I.getType(),
5976         DAG.getExternalSymbol(TrapFuncName.data(),
5977                               TLI.getPointerTy(DAG.getDataLayout())),
5978         std::move(Args));
5979 
5980     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5981     DAG.setRoot(Result.second);
5982     return nullptr;
5983   }
5984 
5985   case Intrinsic::uadd_with_overflow:
5986   case Intrinsic::sadd_with_overflow:
5987   case Intrinsic::usub_with_overflow:
5988   case Intrinsic::ssub_with_overflow:
5989   case Intrinsic::umul_with_overflow:
5990   case Intrinsic::smul_with_overflow: {
5991     ISD::NodeType Op;
5992     switch (Intrinsic) {
5993     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5994     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5995     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5996     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5997     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5998     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5999     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6000     }
6001     SDValue Op1 = getValue(I.getArgOperand(0));
6002     SDValue Op2 = getValue(I.getArgOperand(1));
6003 
6004     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
6005     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6006     return nullptr;
6007   }
6008   case Intrinsic::prefetch: {
6009     SDValue Ops[5];
6010     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6011     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6012     Ops[0] = DAG.getRoot();
6013     Ops[1] = getValue(I.getArgOperand(0));
6014     Ops[2] = getValue(I.getArgOperand(1));
6015     Ops[3] = getValue(I.getArgOperand(2));
6016     Ops[4] = getValue(I.getArgOperand(3));
6017     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6018                                              DAG.getVTList(MVT::Other), Ops,
6019                                              EVT::getIntegerVT(*Context, 8),
6020                                              MachinePointerInfo(I.getArgOperand(0)),
6021                                              0, /* align */
6022                                              Flags);
6023 
6024     // Chain the prefetch in parallell with any pending loads, to stay out of
6025     // the way of later optimizations.
6026     PendingLoads.push_back(Result);
6027     Result = getRoot();
6028     DAG.setRoot(Result);
6029     return nullptr;
6030   }
6031   case Intrinsic::lifetime_start:
6032   case Intrinsic::lifetime_end: {
6033     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6034     // Stack coloring is not enabled in O0, discard region information.
6035     if (TM.getOptLevel() == CodeGenOpt::None)
6036       return nullptr;
6037 
6038     SmallVector<Value *, 4> Allocas;
6039     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
6040 
6041     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
6042            E = Allocas.end(); Object != E; ++Object) {
6043       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6044 
6045       // Could not find an Alloca.
6046       if (!LifetimeObject)
6047         continue;
6048 
6049       // First check that the Alloca is static, otherwise it won't have a
6050       // valid frame index.
6051       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6052       if (SI == FuncInfo.StaticAllocaMap.end())
6053         return nullptr;
6054 
6055       int FI = SI->second;
6056 
6057       SDValue Ops[2];
6058       Ops[0] = getRoot();
6059       Ops[1] =
6060           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
6061       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
6062 
6063       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
6064       DAG.setRoot(Res);
6065     }
6066     return nullptr;
6067   }
6068   case Intrinsic::invariant_start:
6069     // Discard region information.
6070     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6071     return nullptr;
6072   case Intrinsic::invariant_end:
6073     // Discard region information.
6074     return nullptr;
6075   case Intrinsic::clear_cache:
6076     return TLI.getClearCacheBuiltinName();
6077   case Intrinsic::donothing:
6078     // ignore
6079     return nullptr;
6080   case Intrinsic::experimental_stackmap:
6081     visitStackmap(I);
6082     return nullptr;
6083   case Intrinsic::experimental_patchpoint_void:
6084   case Intrinsic::experimental_patchpoint_i64:
6085     visitPatchpoint(&I);
6086     return nullptr;
6087   case Intrinsic::experimental_gc_statepoint:
6088     LowerStatepoint(ImmutableStatepoint(&I));
6089     return nullptr;
6090   case Intrinsic::experimental_gc_result:
6091     visitGCResult(cast<GCResultInst>(I));
6092     return nullptr;
6093   case Intrinsic::experimental_gc_relocate:
6094     visitGCRelocate(cast<GCRelocateInst>(I));
6095     return nullptr;
6096   case Intrinsic::instrprof_increment:
6097     llvm_unreachable("instrprof failed to lower an increment");
6098   case Intrinsic::instrprof_value_profile:
6099     llvm_unreachable("instrprof failed to lower a value profiling call");
6100   case Intrinsic::localescape: {
6101     MachineFunction &MF = DAG.getMachineFunction();
6102     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6103 
6104     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6105     // is the same on all targets.
6106     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6107       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6108       if (isa<ConstantPointerNull>(Arg))
6109         continue; // Skip null pointers. They represent a hole in index space.
6110       AllocaInst *Slot = cast<AllocaInst>(Arg);
6111       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6112              "can only escape static allocas");
6113       int FI = FuncInfo.StaticAllocaMap[Slot];
6114       MCSymbol *FrameAllocSym =
6115           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6116               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6117       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6118               TII->get(TargetOpcode::LOCAL_ESCAPE))
6119           .addSym(FrameAllocSym)
6120           .addFrameIndex(FI);
6121     }
6122 
6123     return nullptr;
6124   }
6125 
6126   case Intrinsic::localrecover: {
6127     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6128     MachineFunction &MF = DAG.getMachineFunction();
6129     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6130 
6131     // Get the symbol that defines the frame offset.
6132     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6133     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6134     unsigned IdxVal =
6135         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6136     MCSymbol *FrameAllocSym =
6137         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6138             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6139 
6140     // Create a MCSymbol for the label to avoid any target lowering
6141     // that would make this PC relative.
6142     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6143     SDValue OffsetVal =
6144         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6145 
6146     // Add the offset to the FP.
6147     Value *FP = I.getArgOperand(1);
6148     SDValue FPVal = getValue(FP);
6149     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6150     setValue(&I, Add);
6151 
6152     return nullptr;
6153   }
6154 
6155   case Intrinsic::eh_exceptionpointer:
6156   case Intrinsic::eh_exceptioncode: {
6157     // Get the exception pointer vreg, copy from it, and resize it to fit.
6158     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6159     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6160     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6161     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6162     SDValue N =
6163         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6164     if (Intrinsic == Intrinsic::eh_exceptioncode)
6165       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6166     setValue(&I, N);
6167     return nullptr;
6168   }
6169   case Intrinsic::xray_customevent: {
6170     // Here we want to make sure that the intrinsic behaves as if it has a
6171     // specific calling convention, and only for x86_64.
6172     // FIXME: Support other platforms later.
6173     const auto &Triple = DAG.getTarget().getTargetTriple();
6174     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6175       return nullptr;
6176 
6177     SDLoc DL = getCurSDLoc();
6178     SmallVector<SDValue, 8> Ops;
6179 
6180     // We want to say that we always want the arguments in registers.
6181     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6182     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6183     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6184     SDValue Chain = getRoot();
6185     Ops.push_back(LogEntryVal);
6186     Ops.push_back(StrSizeVal);
6187     Ops.push_back(Chain);
6188 
6189     // We need to enforce the calling convention for the callsite, so that
6190     // argument ordering is enforced correctly, and that register allocation can
6191     // see that some registers may be assumed clobbered and have to preserve
6192     // them across calls to the intrinsic.
6193     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6194                                            DL, NodeTys, Ops);
6195     SDValue patchableNode = SDValue(MN, 0);
6196     DAG.setRoot(patchableNode);
6197     setValue(&I, patchableNode);
6198     return nullptr;
6199   }
6200   case Intrinsic::xray_typedevent: {
6201     // Here we want to make sure that the intrinsic behaves as if it has a
6202     // specific calling convention, and only for x86_64.
6203     // FIXME: Support other platforms later.
6204     const auto &Triple = DAG.getTarget().getTargetTriple();
6205     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6206       return nullptr;
6207 
6208     SDLoc DL = getCurSDLoc();
6209     SmallVector<SDValue, 8> Ops;
6210 
6211     // We want to say that we always want the arguments in registers.
6212     // It's unclear to me how manipulating the selection DAG here forces callers
6213     // to provide arguments in registers instead of on the stack.
6214     SDValue LogTypeId = getValue(I.getArgOperand(0));
6215     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6216     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6217     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6218     SDValue Chain = getRoot();
6219     Ops.push_back(LogTypeId);
6220     Ops.push_back(LogEntryVal);
6221     Ops.push_back(StrSizeVal);
6222     Ops.push_back(Chain);
6223 
6224     // We need to enforce the calling convention for the callsite, so that
6225     // argument ordering is enforced correctly, and that register allocation can
6226     // see that some registers may be assumed clobbered and have to preserve
6227     // them across calls to the intrinsic.
6228     MachineSDNode *MN = DAG.getMachineNode(
6229         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6230     SDValue patchableNode = SDValue(MN, 0);
6231     DAG.setRoot(patchableNode);
6232     setValue(&I, patchableNode);
6233     return nullptr;
6234   }
6235   case Intrinsic::experimental_deoptimize:
6236     LowerDeoptimizeCall(&I);
6237     return nullptr;
6238 
6239   case Intrinsic::experimental_vector_reduce_fadd:
6240   case Intrinsic::experimental_vector_reduce_fmul:
6241   case Intrinsic::experimental_vector_reduce_add:
6242   case Intrinsic::experimental_vector_reduce_mul:
6243   case Intrinsic::experimental_vector_reduce_and:
6244   case Intrinsic::experimental_vector_reduce_or:
6245   case Intrinsic::experimental_vector_reduce_xor:
6246   case Intrinsic::experimental_vector_reduce_smax:
6247   case Intrinsic::experimental_vector_reduce_smin:
6248   case Intrinsic::experimental_vector_reduce_umax:
6249   case Intrinsic::experimental_vector_reduce_umin:
6250   case Intrinsic::experimental_vector_reduce_fmax:
6251   case Intrinsic::experimental_vector_reduce_fmin:
6252     visitVectorReduce(I, Intrinsic);
6253     return nullptr;
6254 
6255   case Intrinsic::icall_branch_funnel: {
6256     SmallVector<SDValue, 16> Ops;
6257     Ops.push_back(DAG.getRoot());
6258     Ops.push_back(getValue(I.getArgOperand(0)));
6259 
6260     int64_t Offset;
6261     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6262         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6263     if (!Base)
6264       report_fatal_error(
6265           "llvm.icall.branch.funnel operand must be a GlobalValue");
6266     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6267 
6268     struct BranchFunnelTarget {
6269       int64_t Offset;
6270       SDValue Target;
6271     };
6272     SmallVector<BranchFunnelTarget, 8> Targets;
6273 
6274     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6275       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6276           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6277       if (ElemBase != Base)
6278         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6279                            "to the same GlobalValue");
6280 
6281       SDValue Val = getValue(I.getArgOperand(Op + 1));
6282       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6283       if (!GA)
6284         report_fatal_error(
6285             "llvm.icall.branch.funnel operand must be a GlobalValue");
6286       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6287                                      GA->getGlobal(), getCurSDLoc(),
6288                                      Val.getValueType(), GA->getOffset())});
6289     }
6290     llvm::sort(Targets,
6291                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6292                  return T1.Offset < T2.Offset;
6293                });
6294 
6295     for (auto &T : Targets) {
6296       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6297       Ops.push_back(T.Target);
6298     }
6299 
6300     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6301                                  getCurSDLoc(), MVT::Other, Ops),
6302               0);
6303     DAG.setRoot(N);
6304     setValue(&I, N);
6305     HasTailCall = true;
6306     return nullptr;
6307   }
6308 
6309   case Intrinsic::wasm_landingpad_index:
6310     // Information this intrinsic contained has been transferred to
6311     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6312     // delete it now.
6313     return nullptr;
6314   }
6315 }
6316 
6317 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6318     const ConstrainedFPIntrinsic &FPI) {
6319   SDLoc sdl = getCurSDLoc();
6320   unsigned Opcode;
6321   switch (FPI.getIntrinsicID()) {
6322   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6323   case Intrinsic::experimental_constrained_fadd:
6324     Opcode = ISD::STRICT_FADD;
6325     break;
6326   case Intrinsic::experimental_constrained_fsub:
6327     Opcode = ISD::STRICT_FSUB;
6328     break;
6329   case Intrinsic::experimental_constrained_fmul:
6330     Opcode = ISD::STRICT_FMUL;
6331     break;
6332   case Intrinsic::experimental_constrained_fdiv:
6333     Opcode = ISD::STRICT_FDIV;
6334     break;
6335   case Intrinsic::experimental_constrained_frem:
6336     Opcode = ISD::STRICT_FREM;
6337     break;
6338   case Intrinsic::experimental_constrained_fma:
6339     Opcode = ISD::STRICT_FMA;
6340     break;
6341   case Intrinsic::experimental_constrained_sqrt:
6342     Opcode = ISD::STRICT_FSQRT;
6343     break;
6344   case Intrinsic::experimental_constrained_pow:
6345     Opcode = ISD::STRICT_FPOW;
6346     break;
6347   case Intrinsic::experimental_constrained_powi:
6348     Opcode = ISD::STRICT_FPOWI;
6349     break;
6350   case Intrinsic::experimental_constrained_sin:
6351     Opcode = ISD::STRICT_FSIN;
6352     break;
6353   case Intrinsic::experimental_constrained_cos:
6354     Opcode = ISD::STRICT_FCOS;
6355     break;
6356   case Intrinsic::experimental_constrained_exp:
6357     Opcode = ISD::STRICT_FEXP;
6358     break;
6359   case Intrinsic::experimental_constrained_exp2:
6360     Opcode = ISD::STRICT_FEXP2;
6361     break;
6362   case Intrinsic::experimental_constrained_log:
6363     Opcode = ISD::STRICT_FLOG;
6364     break;
6365   case Intrinsic::experimental_constrained_log10:
6366     Opcode = ISD::STRICT_FLOG10;
6367     break;
6368   case Intrinsic::experimental_constrained_log2:
6369     Opcode = ISD::STRICT_FLOG2;
6370     break;
6371   case Intrinsic::experimental_constrained_rint:
6372     Opcode = ISD::STRICT_FRINT;
6373     break;
6374   case Intrinsic::experimental_constrained_nearbyint:
6375     Opcode = ISD::STRICT_FNEARBYINT;
6376     break;
6377   }
6378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6379   SDValue Chain = getRoot();
6380   SmallVector<EVT, 4> ValueVTs;
6381   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6382   ValueVTs.push_back(MVT::Other); // Out chain
6383 
6384   SDVTList VTs = DAG.getVTList(ValueVTs);
6385   SDValue Result;
6386   if (FPI.isUnaryOp())
6387     Result = DAG.getNode(Opcode, sdl, VTs,
6388                          { Chain, getValue(FPI.getArgOperand(0)) });
6389   else if (FPI.isTernaryOp())
6390     Result = DAG.getNode(Opcode, sdl, VTs,
6391                          { Chain, getValue(FPI.getArgOperand(0)),
6392                                   getValue(FPI.getArgOperand(1)),
6393                                   getValue(FPI.getArgOperand(2)) });
6394   else
6395     Result = DAG.getNode(Opcode, sdl, VTs,
6396                          { Chain, getValue(FPI.getArgOperand(0)),
6397                            getValue(FPI.getArgOperand(1))  });
6398 
6399   assert(Result.getNode()->getNumValues() == 2);
6400   SDValue OutChain = Result.getValue(1);
6401   DAG.setRoot(OutChain);
6402   SDValue FPResult = Result.getValue(0);
6403   setValue(&FPI, FPResult);
6404 }
6405 
6406 std::pair<SDValue, SDValue>
6407 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6408                                     const BasicBlock *EHPadBB) {
6409   MachineFunction &MF = DAG.getMachineFunction();
6410   MachineModuleInfo &MMI = MF.getMMI();
6411   MCSymbol *BeginLabel = nullptr;
6412 
6413   if (EHPadBB) {
6414     // Insert a label before the invoke call to mark the try range.  This can be
6415     // used to detect deletion of the invoke via the MachineModuleInfo.
6416     BeginLabel = MMI.getContext().createTempSymbol();
6417 
6418     // For SjLj, keep track of which landing pads go with which invokes
6419     // so as to maintain the ordering of pads in the LSDA.
6420     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6421     if (CallSiteIndex) {
6422       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6423       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6424 
6425       // Now that the call site is handled, stop tracking it.
6426       MMI.setCurrentCallSite(0);
6427     }
6428 
6429     // Both PendingLoads and PendingExports must be flushed here;
6430     // this call might not return.
6431     (void)getRoot();
6432     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6433 
6434     CLI.setChain(getRoot());
6435   }
6436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6437   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6438 
6439   assert((CLI.IsTailCall || Result.second.getNode()) &&
6440          "Non-null chain expected with non-tail call!");
6441   assert((Result.second.getNode() || !Result.first.getNode()) &&
6442          "Null value expected with tail call!");
6443 
6444   if (!Result.second.getNode()) {
6445     // As a special case, a null chain means that a tail call has been emitted
6446     // and the DAG root is already updated.
6447     HasTailCall = true;
6448 
6449     // Since there's no actual continuation from this block, nothing can be
6450     // relying on us setting vregs for them.
6451     PendingExports.clear();
6452   } else {
6453     DAG.setRoot(Result.second);
6454   }
6455 
6456   if (EHPadBB) {
6457     // Insert a label at the end of the invoke call to mark the try range.  This
6458     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6459     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6460     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6461 
6462     // Inform MachineModuleInfo of range.
6463     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6464     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6465     // actually use outlined funclets and their LSDA info style.
6466     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6467       assert(CLI.CS);
6468       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6469       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6470                                 BeginLabel, EndLabel);
6471     } else if (!isScopedEHPersonality(Pers)) {
6472       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6473     }
6474   }
6475 
6476   return Result;
6477 }
6478 
6479 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6480                                       bool isTailCall,
6481                                       const BasicBlock *EHPadBB) {
6482   auto &DL = DAG.getDataLayout();
6483   FunctionType *FTy = CS.getFunctionType();
6484   Type *RetTy = CS.getType();
6485 
6486   TargetLowering::ArgListTy Args;
6487   Args.reserve(CS.arg_size());
6488 
6489   const Value *SwiftErrorVal = nullptr;
6490   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6491 
6492   // We can't tail call inside a function with a swifterror argument. Lowering
6493   // does not support this yet. It would have to move into the swifterror
6494   // register before the call.
6495   auto *Caller = CS.getInstruction()->getParent()->getParent();
6496   if (TLI.supportSwiftError() &&
6497       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6498     isTailCall = false;
6499 
6500   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6501        i != e; ++i) {
6502     TargetLowering::ArgListEntry Entry;
6503     const Value *V = *i;
6504 
6505     // Skip empty types
6506     if (V->getType()->isEmptyTy())
6507       continue;
6508 
6509     SDValue ArgNode = getValue(V);
6510     Entry.Node = ArgNode; Entry.Ty = V->getType();
6511 
6512     Entry.setAttributes(&CS, i - CS.arg_begin());
6513 
6514     // Use swifterror virtual register as input to the call.
6515     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6516       SwiftErrorVal = V;
6517       // We find the virtual register for the actual swifterror argument.
6518       // Instead of using the Value, we use the virtual register instead.
6519       Entry.Node = DAG.getRegister(FuncInfo
6520                                        .getOrCreateSwiftErrorVRegUseAt(
6521                                            CS.getInstruction(), FuncInfo.MBB, V)
6522                                        .first,
6523                                    EVT(TLI.getPointerTy(DL)));
6524     }
6525 
6526     Args.push_back(Entry);
6527 
6528     // If we have an explicit sret argument that is an Instruction, (i.e., it
6529     // might point to function-local memory), we can't meaningfully tail-call.
6530     if (Entry.IsSRet && isa<Instruction>(V))
6531       isTailCall = false;
6532   }
6533 
6534   // Check if target-independent constraints permit a tail call here.
6535   // Target-dependent constraints are checked within TLI->LowerCallTo.
6536   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6537     isTailCall = false;
6538 
6539   // Disable tail calls if there is an swifterror argument. Targets have not
6540   // been updated to support tail calls.
6541   if (TLI.supportSwiftError() && SwiftErrorVal)
6542     isTailCall = false;
6543 
6544   TargetLowering::CallLoweringInfo CLI(DAG);
6545   CLI.setDebugLoc(getCurSDLoc())
6546       .setChain(getRoot())
6547       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6548       .setTailCall(isTailCall)
6549       .setConvergent(CS.isConvergent());
6550   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6551 
6552   if (Result.first.getNode()) {
6553     const Instruction *Inst = CS.getInstruction();
6554     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6555     setValue(Inst, Result.first);
6556   }
6557 
6558   // The last element of CLI.InVals has the SDValue for swifterror return.
6559   // Here we copy it to a virtual register and update SwiftErrorMap for
6560   // book-keeping.
6561   if (SwiftErrorVal && TLI.supportSwiftError()) {
6562     // Get the last element of InVals.
6563     SDValue Src = CLI.InVals.back();
6564     unsigned VReg; bool CreatedVReg;
6565     std::tie(VReg, CreatedVReg) =
6566         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6567     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6568     // We update the virtual register for the actual swifterror argument.
6569     if (CreatedVReg)
6570       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6571     DAG.setRoot(CopyNode);
6572   }
6573 }
6574 
6575 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6576                              SelectionDAGBuilder &Builder) {
6577   // Check to see if this load can be trivially constant folded, e.g. if the
6578   // input is from a string literal.
6579   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6580     // Cast pointer to the type we really want to load.
6581     Type *LoadTy =
6582         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6583     if (LoadVT.isVector())
6584       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6585 
6586     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6587                                          PointerType::getUnqual(LoadTy));
6588 
6589     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6590             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6591       return Builder.getValue(LoadCst);
6592   }
6593 
6594   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6595   // still constant memory, the input chain can be the entry node.
6596   SDValue Root;
6597   bool ConstantMemory = false;
6598 
6599   // Do not serialize (non-volatile) loads of constant memory with anything.
6600   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6601     Root = Builder.DAG.getEntryNode();
6602     ConstantMemory = true;
6603   } else {
6604     // Do not serialize non-volatile loads against each other.
6605     Root = Builder.DAG.getRoot();
6606   }
6607 
6608   SDValue Ptr = Builder.getValue(PtrVal);
6609   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6610                                         Ptr, MachinePointerInfo(PtrVal),
6611                                         /* Alignment = */ 1);
6612 
6613   if (!ConstantMemory)
6614     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6615   return LoadVal;
6616 }
6617 
6618 /// Record the value for an instruction that produces an integer result,
6619 /// converting the type where necessary.
6620 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6621                                                   SDValue Value,
6622                                                   bool IsSigned) {
6623   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6624                                                     I.getType(), true);
6625   if (IsSigned)
6626     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6627   else
6628     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6629   setValue(&I, Value);
6630 }
6631 
6632 /// See if we can lower a memcmp call into an optimized form. If so, return
6633 /// true and lower it. Otherwise return false, and it will be lowered like a
6634 /// normal call.
6635 /// The caller already checked that \p I calls the appropriate LibFunc with a
6636 /// correct prototype.
6637 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6638   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6639   const Value *Size = I.getArgOperand(2);
6640   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6641   if (CSize && CSize->getZExtValue() == 0) {
6642     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6643                                                           I.getType(), true);
6644     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6645     return true;
6646   }
6647 
6648   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6649   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6650       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6651       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6652   if (Res.first.getNode()) {
6653     processIntegerCallValue(I, Res.first, true);
6654     PendingLoads.push_back(Res.second);
6655     return true;
6656   }
6657 
6658   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6659   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6660   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6661     return false;
6662 
6663   // If the target has a fast compare for the given size, it will return a
6664   // preferred load type for that size. Require that the load VT is legal and
6665   // that the target supports unaligned loads of that type. Otherwise, return
6666   // INVALID.
6667   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6668     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6669     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6670     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6671       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6672       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6673       // TODO: Check alignment of src and dest ptrs.
6674       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6675       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6676       if (!TLI.isTypeLegal(LVT) ||
6677           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6678           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6679         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6680     }
6681 
6682     return LVT;
6683   };
6684 
6685   // This turns into unaligned loads. We only do this if the target natively
6686   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6687   // we'll only produce a small number of byte loads.
6688   MVT LoadVT;
6689   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6690   switch (NumBitsToCompare) {
6691   default:
6692     return false;
6693   case 16:
6694     LoadVT = MVT::i16;
6695     break;
6696   case 32:
6697     LoadVT = MVT::i32;
6698     break;
6699   case 64:
6700   case 128:
6701   case 256:
6702     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6703     break;
6704   }
6705 
6706   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6707     return false;
6708 
6709   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6710   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6711 
6712   // Bitcast to a wide integer type if the loads are vectors.
6713   if (LoadVT.isVector()) {
6714     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6715     LoadL = DAG.getBitcast(CmpVT, LoadL);
6716     LoadR = DAG.getBitcast(CmpVT, LoadR);
6717   }
6718 
6719   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6720   processIntegerCallValue(I, Cmp, false);
6721   return true;
6722 }
6723 
6724 /// See if we can lower a memchr call into an optimized form. If so, return
6725 /// true and lower it. Otherwise return false, and it will be lowered like a
6726 /// normal call.
6727 /// The caller already checked that \p I calls the appropriate LibFunc with a
6728 /// correct prototype.
6729 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6730   const Value *Src = I.getArgOperand(0);
6731   const Value *Char = I.getArgOperand(1);
6732   const Value *Length = I.getArgOperand(2);
6733 
6734   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6735   std::pair<SDValue, SDValue> Res =
6736     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6737                                 getValue(Src), getValue(Char), getValue(Length),
6738                                 MachinePointerInfo(Src));
6739   if (Res.first.getNode()) {
6740     setValue(&I, Res.first);
6741     PendingLoads.push_back(Res.second);
6742     return true;
6743   }
6744 
6745   return false;
6746 }
6747 
6748 /// See if we can lower a mempcpy call into an optimized form. If so, return
6749 /// true and lower it. Otherwise return false, and it will be lowered like a
6750 /// normal call.
6751 /// The caller already checked that \p I calls the appropriate LibFunc with a
6752 /// correct prototype.
6753 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6754   SDValue Dst = getValue(I.getArgOperand(0));
6755   SDValue Src = getValue(I.getArgOperand(1));
6756   SDValue Size = getValue(I.getArgOperand(2));
6757 
6758   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6759   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6760   unsigned Align = std::min(DstAlign, SrcAlign);
6761   if (Align == 0) // Alignment of one or both could not be inferred.
6762     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6763 
6764   bool isVol = false;
6765   SDLoc sdl = getCurSDLoc();
6766 
6767   // In the mempcpy context we need to pass in a false value for isTailCall
6768   // because the return pointer needs to be adjusted by the size of
6769   // the copied memory.
6770   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6771                              false, /*isTailCall=*/false,
6772                              MachinePointerInfo(I.getArgOperand(0)),
6773                              MachinePointerInfo(I.getArgOperand(1)));
6774   assert(MC.getNode() != nullptr &&
6775          "** memcpy should not be lowered as TailCall in mempcpy context **");
6776   DAG.setRoot(MC);
6777 
6778   // Check if Size needs to be truncated or extended.
6779   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6780 
6781   // Adjust return pointer to point just past the last dst byte.
6782   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6783                                     Dst, Size);
6784   setValue(&I, DstPlusSize);
6785   return true;
6786 }
6787 
6788 /// See if we can lower a strcpy call into an optimized form.  If so, return
6789 /// true and lower it, otherwise return false and it will be lowered like a
6790 /// normal call.
6791 /// The caller already checked that \p I calls the appropriate LibFunc with a
6792 /// correct prototype.
6793 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6794   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6795 
6796   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6797   std::pair<SDValue, SDValue> Res =
6798     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6799                                 getValue(Arg0), getValue(Arg1),
6800                                 MachinePointerInfo(Arg0),
6801                                 MachinePointerInfo(Arg1), isStpcpy);
6802   if (Res.first.getNode()) {
6803     setValue(&I, Res.first);
6804     DAG.setRoot(Res.second);
6805     return true;
6806   }
6807 
6808   return false;
6809 }
6810 
6811 /// See if we can lower a strcmp call into an optimized form.  If so, return
6812 /// true and lower it, otherwise return false and it will be lowered like a
6813 /// normal call.
6814 /// The caller already checked that \p I calls the appropriate LibFunc with a
6815 /// correct prototype.
6816 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6817   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6818 
6819   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6820   std::pair<SDValue, SDValue> Res =
6821     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6822                                 getValue(Arg0), getValue(Arg1),
6823                                 MachinePointerInfo(Arg0),
6824                                 MachinePointerInfo(Arg1));
6825   if (Res.first.getNode()) {
6826     processIntegerCallValue(I, Res.first, true);
6827     PendingLoads.push_back(Res.second);
6828     return true;
6829   }
6830 
6831   return false;
6832 }
6833 
6834 /// See if we can lower a strlen call into an optimized form.  If so, return
6835 /// true and lower it, otherwise return false and it will be lowered like a
6836 /// normal call.
6837 /// The caller already checked that \p I calls the appropriate LibFunc with a
6838 /// correct prototype.
6839 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6840   const Value *Arg0 = I.getArgOperand(0);
6841 
6842   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6843   std::pair<SDValue, SDValue> Res =
6844     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6845                                 getValue(Arg0), MachinePointerInfo(Arg0));
6846   if (Res.first.getNode()) {
6847     processIntegerCallValue(I, Res.first, false);
6848     PendingLoads.push_back(Res.second);
6849     return true;
6850   }
6851 
6852   return false;
6853 }
6854 
6855 /// See if we can lower a strnlen call into an optimized form.  If so, return
6856 /// true and lower it, otherwise return false and it will be lowered like a
6857 /// normal call.
6858 /// The caller already checked that \p I calls the appropriate LibFunc with a
6859 /// correct prototype.
6860 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6861   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6862 
6863   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6864   std::pair<SDValue, SDValue> Res =
6865     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6866                                  getValue(Arg0), getValue(Arg1),
6867                                  MachinePointerInfo(Arg0));
6868   if (Res.first.getNode()) {
6869     processIntegerCallValue(I, Res.first, false);
6870     PendingLoads.push_back(Res.second);
6871     return true;
6872   }
6873 
6874   return false;
6875 }
6876 
6877 /// See if we can lower a unary floating-point operation into an SDNode with
6878 /// the specified Opcode.  If so, return true and lower it, otherwise return
6879 /// false and it will be lowered like a normal call.
6880 /// The caller already checked that \p I calls the appropriate LibFunc with a
6881 /// correct prototype.
6882 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6883                                               unsigned Opcode) {
6884   // We already checked this call's prototype; verify it doesn't modify errno.
6885   if (!I.onlyReadsMemory())
6886     return false;
6887 
6888   SDValue Tmp = getValue(I.getArgOperand(0));
6889   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6890   return true;
6891 }
6892 
6893 /// See if we can lower a binary floating-point operation into an SDNode with
6894 /// the specified Opcode. If so, return true and lower it. Otherwise return
6895 /// false, and it will be lowered like a normal call.
6896 /// The caller already checked that \p I calls the appropriate LibFunc with a
6897 /// correct prototype.
6898 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6899                                                unsigned Opcode) {
6900   // We already checked this call's prototype; verify it doesn't modify errno.
6901   if (!I.onlyReadsMemory())
6902     return false;
6903 
6904   SDValue Tmp0 = getValue(I.getArgOperand(0));
6905   SDValue Tmp1 = getValue(I.getArgOperand(1));
6906   EVT VT = Tmp0.getValueType();
6907   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6908   return true;
6909 }
6910 
6911 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6912   // Handle inline assembly differently.
6913   if (isa<InlineAsm>(I.getCalledValue())) {
6914     visitInlineAsm(&I);
6915     return;
6916   }
6917 
6918   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6919   computeUsesVAFloatArgument(I, MMI);
6920 
6921   const char *RenameFn = nullptr;
6922   if (Function *F = I.getCalledFunction()) {
6923     if (F->isDeclaration()) {
6924       // Is this an LLVM intrinsic or a target-specific intrinsic?
6925       unsigned IID = F->getIntrinsicID();
6926       if (!IID)
6927         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
6928           IID = II->getIntrinsicID(F);
6929 
6930       if (IID) {
6931         RenameFn = visitIntrinsicCall(I, IID);
6932         if (!RenameFn)
6933           return;
6934       }
6935     }
6936 
6937     // Check for well-known libc/libm calls.  If the function is internal, it
6938     // can't be a library call.  Don't do the check if marked as nobuiltin for
6939     // some reason or the call site requires strict floating point semantics.
6940     LibFunc Func;
6941     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
6942         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
6943         LibInfo->hasOptimizedCodeGen(Func)) {
6944       switch (Func) {
6945       default: break;
6946       case LibFunc_copysign:
6947       case LibFunc_copysignf:
6948       case LibFunc_copysignl:
6949         // We already checked this call's prototype; verify it doesn't modify
6950         // errno.
6951         if (I.onlyReadsMemory()) {
6952           SDValue LHS = getValue(I.getArgOperand(0));
6953           SDValue RHS = getValue(I.getArgOperand(1));
6954           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6955                                    LHS.getValueType(), LHS, RHS));
6956           return;
6957         }
6958         break;
6959       case LibFunc_fabs:
6960       case LibFunc_fabsf:
6961       case LibFunc_fabsl:
6962         if (visitUnaryFloatCall(I, ISD::FABS))
6963           return;
6964         break;
6965       case LibFunc_fmin:
6966       case LibFunc_fminf:
6967       case LibFunc_fminl:
6968         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6969           return;
6970         break;
6971       case LibFunc_fmax:
6972       case LibFunc_fmaxf:
6973       case LibFunc_fmaxl:
6974         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6975           return;
6976         break;
6977       case LibFunc_sin:
6978       case LibFunc_sinf:
6979       case LibFunc_sinl:
6980         if (visitUnaryFloatCall(I, ISD::FSIN))
6981           return;
6982         break;
6983       case LibFunc_cos:
6984       case LibFunc_cosf:
6985       case LibFunc_cosl:
6986         if (visitUnaryFloatCall(I, ISD::FCOS))
6987           return;
6988         break;
6989       case LibFunc_sqrt:
6990       case LibFunc_sqrtf:
6991       case LibFunc_sqrtl:
6992       case LibFunc_sqrt_finite:
6993       case LibFunc_sqrtf_finite:
6994       case LibFunc_sqrtl_finite:
6995         if (visitUnaryFloatCall(I, ISD::FSQRT))
6996           return;
6997         break;
6998       case LibFunc_floor:
6999       case LibFunc_floorf:
7000       case LibFunc_floorl:
7001         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7002           return;
7003         break;
7004       case LibFunc_nearbyint:
7005       case LibFunc_nearbyintf:
7006       case LibFunc_nearbyintl:
7007         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7008           return;
7009         break;
7010       case LibFunc_ceil:
7011       case LibFunc_ceilf:
7012       case LibFunc_ceill:
7013         if (visitUnaryFloatCall(I, ISD::FCEIL))
7014           return;
7015         break;
7016       case LibFunc_rint:
7017       case LibFunc_rintf:
7018       case LibFunc_rintl:
7019         if (visitUnaryFloatCall(I, ISD::FRINT))
7020           return;
7021         break;
7022       case LibFunc_round:
7023       case LibFunc_roundf:
7024       case LibFunc_roundl:
7025         if (visitUnaryFloatCall(I, ISD::FROUND))
7026           return;
7027         break;
7028       case LibFunc_trunc:
7029       case LibFunc_truncf:
7030       case LibFunc_truncl:
7031         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7032           return;
7033         break;
7034       case LibFunc_log2:
7035       case LibFunc_log2f:
7036       case LibFunc_log2l:
7037         if (visitUnaryFloatCall(I, ISD::FLOG2))
7038           return;
7039         break;
7040       case LibFunc_exp2:
7041       case LibFunc_exp2f:
7042       case LibFunc_exp2l:
7043         if (visitUnaryFloatCall(I, ISD::FEXP2))
7044           return;
7045         break;
7046       case LibFunc_memcmp:
7047         if (visitMemCmpCall(I))
7048           return;
7049         break;
7050       case LibFunc_mempcpy:
7051         if (visitMemPCpyCall(I))
7052           return;
7053         break;
7054       case LibFunc_memchr:
7055         if (visitMemChrCall(I))
7056           return;
7057         break;
7058       case LibFunc_strcpy:
7059         if (visitStrCpyCall(I, false))
7060           return;
7061         break;
7062       case LibFunc_stpcpy:
7063         if (visitStrCpyCall(I, true))
7064           return;
7065         break;
7066       case LibFunc_strcmp:
7067         if (visitStrCmpCall(I))
7068           return;
7069         break;
7070       case LibFunc_strlen:
7071         if (visitStrLenCall(I))
7072           return;
7073         break;
7074       case LibFunc_strnlen:
7075         if (visitStrNLenCall(I))
7076           return;
7077         break;
7078       }
7079     }
7080   }
7081 
7082   SDValue Callee;
7083   if (!RenameFn)
7084     Callee = getValue(I.getCalledValue());
7085   else
7086     Callee = DAG.getExternalSymbol(
7087         RenameFn,
7088         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7089 
7090   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7091   // have to do anything here to lower funclet bundles.
7092   assert(!I.hasOperandBundlesOtherThan(
7093              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7094          "Cannot lower calls with arbitrary operand bundles!");
7095 
7096   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7097     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7098   else
7099     // Check if we can potentially perform a tail call. More detailed checking
7100     // is be done within LowerCallTo, after more information about the call is
7101     // known.
7102     LowerCallTo(&I, Callee, I.isTailCall());
7103 }
7104 
7105 namespace {
7106 
7107 /// AsmOperandInfo - This contains information for each constraint that we are
7108 /// lowering.
7109 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7110 public:
7111   /// CallOperand - If this is the result output operand or a clobber
7112   /// this is null, otherwise it is the incoming operand to the CallInst.
7113   /// This gets modified as the asm is processed.
7114   SDValue CallOperand;
7115 
7116   /// AssignedRegs - If this is a register or register class operand, this
7117   /// contains the set of register corresponding to the operand.
7118   RegsForValue AssignedRegs;
7119 
7120   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7121     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7122   }
7123 
7124   /// Whether or not this operand accesses memory
7125   bool hasMemory(const TargetLowering &TLI) const {
7126     // Indirect operand accesses access memory.
7127     if (isIndirect)
7128       return true;
7129 
7130     for (const auto &Code : Codes)
7131       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7132         return true;
7133 
7134     return false;
7135   }
7136 
7137   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7138   /// corresponds to.  If there is no Value* for this operand, it returns
7139   /// MVT::Other.
7140   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7141                            const DataLayout &DL) const {
7142     if (!CallOperandVal) return MVT::Other;
7143 
7144     if (isa<BasicBlock>(CallOperandVal))
7145       return TLI.getPointerTy(DL);
7146 
7147     llvm::Type *OpTy = CallOperandVal->getType();
7148 
7149     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7150     // If this is an indirect operand, the operand is a pointer to the
7151     // accessed type.
7152     if (isIndirect) {
7153       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7154       if (!PtrTy)
7155         report_fatal_error("Indirect operand for inline asm not a pointer!");
7156       OpTy = PtrTy->getElementType();
7157     }
7158 
7159     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7160     if (StructType *STy = dyn_cast<StructType>(OpTy))
7161       if (STy->getNumElements() == 1)
7162         OpTy = STy->getElementType(0);
7163 
7164     // If OpTy is not a single value, it may be a struct/union that we
7165     // can tile with integers.
7166     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7167       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7168       switch (BitSize) {
7169       default: break;
7170       case 1:
7171       case 8:
7172       case 16:
7173       case 32:
7174       case 64:
7175       case 128:
7176         OpTy = IntegerType::get(Context, BitSize);
7177         break;
7178       }
7179     }
7180 
7181     return TLI.getValueType(DL, OpTy, true);
7182   }
7183 };
7184 
7185 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7186 
7187 } // end anonymous namespace
7188 
7189 /// Make sure that the output operand \p OpInfo and its corresponding input
7190 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7191 /// out).
7192 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7193                                SDISelAsmOperandInfo &MatchingOpInfo,
7194                                SelectionDAG &DAG) {
7195   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7196     return;
7197 
7198   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7199   const auto &TLI = DAG.getTargetLoweringInfo();
7200 
7201   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7202       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7203                                        OpInfo.ConstraintVT);
7204   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7205       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7206                                        MatchingOpInfo.ConstraintVT);
7207   if ((OpInfo.ConstraintVT.isInteger() !=
7208        MatchingOpInfo.ConstraintVT.isInteger()) ||
7209       (MatchRC.second != InputRC.second)) {
7210     // FIXME: error out in a more elegant fashion
7211     report_fatal_error("Unsupported asm: input constraint"
7212                        " with a matching output constraint of"
7213                        " incompatible type!");
7214   }
7215   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7216 }
7217 
7218 /// Get a direct memory input to behave well as an indirect operand.
7219 /// This may introduce stores, hence the need for a \p Chain.
7220 /// \return The (possibly updated) chain.
7221 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7222                                         SDISelAsmOperandInfo &OpInfo,
7223                                         SelectionDAG &DAG) {
7224   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7225 
7226   // If we don't have an indirect input, put it in the constpool if we can,
7227   // otherwise spill it to a stack slot.
7228   // TODO: This isn't quite right. We need to handle these according to
7229   // the addressing mode that the constraint wants. Also, this may take
7230   // an additional register for the computation and we don't want that
7231   // either.
7232 
7233   // If the operand is a float, integer, or vector constant, spill to a
7234   // constant pool entry to get its address.
7235   const Value *OpVal = OpInfo.CallOperandVal;
7236   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7237       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7238     OpInfo.CallOperand = DAG.getConstantPool(
7239         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7240     return Chain;
7241   }
7242 
7243   // Otherwise, create a stack slot and emit a store to it before the asm.
7244   Type *Ty = OpVal->getType();
7245   auto &DL = DAG.getDataLayout();
7246   uint64_t TySize = DL.getTypeAllocSize(Ty);
7247   unsigned Align = DL.getPrefTypeAlignment(Ty);
7248   MachineFunction &MF = DAG.getMachineFunction();
7249   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7250   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7251   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7252                        MachinePointerInfo::getFixedStack(MF, SSFI));
7253   OpInfo.CallOperand = StackSlot;
7254 
7255   return Chain;
7256 }
7257 
7258 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7259 /// specified operand.  We prefer to assign virtual registers, to allow the
7260 /// register allocator to handle the assignment process.  However, if the asm
7261 /// uses features that we can't model on machineinstrs, we have SDISel do the
7262 /// allocation.  This produces generally horrible, but correct, code.
7263 ///
7264 ///   OpInfo describes the operand
7265 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7266 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
7267                                  const SDLoc &DL, SDISelAsmOperandInfo &OpInfo,
7268                                  SDISelAsmOperandInfo &RefOpInfo) {
7269   LLVMContext &Context = *DAG.getContext();
7270 
7271   MachineFunction &MF = DAG.getMachineFunction();
7272   SmallVector<unsigned, 4> Regs;
7273   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7274 
7275   // If this is a constraint for a single physreg, or a constraint for a
7276   // register class, find it.
7277   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
7278       TLI.getRegForInlineAsmConstraint(&TRI, RefOpInfo.ConstraintCode,
7279                                        RefOpInfo.ConstraintVT);
7280 
7281   unsigned NumRegs = 1;
7282   if (OpInfo.ConstraintVT != MVT::Other) {
7283     // If this is an FP operand in an integer register (or visa versa), or more
7284     // generally if the operand value disagrees with the register class we plan
7285     // to stick it in, fix the operand type.
7286     //
7287     // If this is an input value, the bitcast to the new type is done now.
7288     // Bitcast for output value is done at the end of visitInlineAsm().
7289     if ((OpInfo.Type == InlineAsm::isOutput ||
7290          OpInfo.Type == InlineAsm::isInput) &&
7291         PhysReg.second &&
7292         !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
7293       // Try to convert to the first EVT that the reg class contains.  If the
7294       // types are identical size, use a bitcast to convert (e.g. two differing
7295       // vector types).  Note: output bitcast is done at the end of
7296       // visitInlineAsm().
7297       MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
7298       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7299         // Exclude indirect inputs while they are unsupported because the code
7300         // to perform the load is missing and thus OpInfo.CallOperand still
7301         // refers to the input address rather than the pointed-to value.
7302         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7303           OpInfo.CallOperand =
7304               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7305         OpInfo.ConstraintVT = RegVT;
7306         // If the operand is an FP value and we want it in integer registers,
7307         // use the corresponding integer type. This turns an f64 value into
7308         // i64, which can be passed with two i32 values on a 32-bit machine.
7309       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7310         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7311         if (OpInfo.Type == InlineAsm::isInput)
7312           OpInfo.CallOperand =
7313               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7314         OpInfo.ConstraintVT = RegVT;
7315       }
7316     }
7317 
7318     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7319   }
7320 
7321   // No need to allocate a matching input constraint since the constraint it's
7322   // matching to has already been allocated.
7323   if (OpInfo.isMatchingInputConstraint())
7324     return;
7325 
7326   MVT RegVT;
7327   EVT ValueVT = OpInfo.ConstraintVT;
7328 
7329   // If this is a constraint for a specific physical register, like {r17},
7330   // assign it now.
7331   if (unsigned AssignedReg = PhysReg.first) {
7332     const TargetRegisterClass *RC = PhysReg.second;
7333     if (OpInfo.ConstraintVT == MVT::Other)
7334       ValueVT = *TRI.legalclasstypes_begin(*RC);
7335 
7336     // Get the actual register value type.  This is important, because the user
7337     // may have asked for (e.g.) the AX register in i32 type.  We need to
7338     // remember that AX is actually i16 to get the right extension.
7339     RegVT = *TRI.legalclasstypes_begin(*RC);
7340 
7341     // This is an explicit reference to a physical register.
7342     Regs.push_back(AssignedReg);
7343 
7344     // If this is an expanded reference, add the rest of the regs to Regs.
7345     if (NumRegs != 1) {
7346       TargetRegisterClass::iterator I = RC->begin();
7347       for (; *I != AssignedReg; ++I)
7348         assert(I != RC->end() && "Didn't find reg!");
7349 
7350       // Already added the first reg.
7351       --NumRegs; ++I;
7352       for (; NumRegs; --NumRegs, ++I) {
7353         assert(I != RC->end() && "Ran out of registers to allocate!");
7354         Regs.push_back(*I);
7355       }
7356     }
7357 
7358     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7359     return;
7360   }
7361 
7362   // Otherwise, if this was a reference to an LLVM register class, create vregs
7363   // for this reference.
7364   if (const TargetRegisterClass *RC = PhysReg.second) {
7365     RegVT = *TRI.legalclasstypes_begin(*RC);
7366     if (OpInfo.ConstraintVT == MVT::Other)
7367       ValueVT = RegVT;
7368 
7369     // Create the appropriate number of virtual registers.
7370     MachineRegisterInfo &RegInfo = MF.getRegInfo();
7371     for (; NumRegs; --NumRegs)
7372       Regs.push_back(RegInfo.createVirtualRegister(RC));
7373 
7374     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7375     return;
7376   }
7377 
7378   // Otherwise, we couldn't allocate enough registers for this.
7379 }
7380 
7381 static unsigned
7382 findMatchingInlineAsmOperand(unsigned OperandNo,
7383                              const std::vector<SDValue> &AsmNodeOperands) {
7384   // Scan until we find the definition we already emitted of this operand.
7385   unsigned CurOp = InlineAsm::Op_FirstOperand;
7386   for (; OperandNo; --OperandNo) {
7387     // Advance to the next operand.
7388     unsigned OpFlag =
7389         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7390     assert((InlineAsm::isRegDefKind(OpFlag) ||
7391             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7392             InlineAsm::isMemKind(OpFlag)) &&
7393            "Skipped past definitions?");
7394     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7395   }
7396   return CurOp;
7397 }
7398 
7399 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
7400 /// \return true if it has succeeded, false otherwise
7401 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
7402                               MVT RegVT, SelectionDAG &DAG) {
7403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7404   MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
7405   for (unsigned i = 0, e = NumRegs; i != e; ++i) {
7406     if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
7407       Regs.push_back(RegInfo.createVirtualRegister(RC));
7408     else
7409       return false;
7410   }
7411   return true;
7412 }
7413 
7414 namespace {
7415 
7416 class ExtraFlags {
7417   unsigned Flags = 0;
7418 
7419 public:
7420   explicit ExtraFlags(ImmutableCallSite CS) {
7421     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7422     if (IA->hasSideEffects())
7423       Flags |= InlineAsm::Extra_HasSideEffects;
7424     if (IA->isAlignStack())
7425       Flags |= InlineAsm::Extra_IsAlignStack;
7426     if (CS.isConvergent())
7427       Flags |= InlineAsm::Extra_IsConvergent;
7428     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7429   }
7430 
7431   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7432     // Ideally, we would only check against memory constraints.  However, the
7433     // meaning of an Other constraint can be target-specific and we can't easily
7434     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7435     // for Other constraints as well.
7436     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7437         OpInfo.ConstraintType == TargetLowering::C_Other) {
7438       if (OpInfo.Type == InlineAsm::isInput)
7439         Flags |= InlineAsm::Extra_MayLoad;
7440       else if (OpInfo.Type == InlineAsm::isOutput)
7441         Flags |= InlineAsm::Extra_MayStore;
7442       else if (OpInfo.Type == InlineAsm::isClobber)
7443         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7444     }
7445   }
7446 
7447   unsigned get() const { return Flags; }
7448 };
7449 
7450 } // end anonymous namespace
7451 
7452 /// visitInlineAsm - Handle a call to an InlineAsm object.
7453 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7454   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7455 
7456   /// ConstraintOperands - Information about all of the constraints.
7457   SDISelAsmOperandInfoVector ConstraintOperands;
7458 
7459   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7460   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7461       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7462 
7463   bool hasMemory = false;
7464 
7465   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7466   ExtraFlags ExtraInfo(CS);
7467 
7468   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7469   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7470   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
7471     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
7472     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7473 
7474     MVT OpVT = MVT::Other;
7475 
7476     // Compute the value type for each operand.
7477     if (OpInfo.Type == InlineAsm::isInput ||
7478         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7479       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7480 
7481       // Process the call argument. BasicBlocks are labels, currently appearing
7482       // only in asm's.
7483       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7484         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7485       } else {
7486         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7487       }
7488 
7489       OpVT =
7490           OpInfo
7491               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7492               .getSimpleVT();
7493     }
7494 
7495     if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7496       // The return value of the call is this value.  As such, there is no
7497       // corresponding argument.
7498       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7499       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7500         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
7501                                       STy->getElementType(ResNo));
7502       } else {
7503         assert(ResNo == 0 && "Asm only has one result!");
7504         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7505       }
7506       ++ResNo;
7507     }
7508 
7509     OpInfo.ConstraintVT = OpVT;
7510 
7511     if (!hasMemory)
7512       hasMemory = OpInfo.hasMemory(TLI);
7513 
7514     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7515     // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
7516     auto TargetConstraint = TargetConstraints[i];
7517 
7518     // Compute the constraint code and ConstraintType to use.
7519     TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
7520 
7521     ExtraInfo.update(TargetConstraint);
7522   }
7523 
7524   SDValue Chain, Flag;
7525 
7526   // We won't need to flush pending loads if this asm doesn't touch
7527   // memory and is nonvolatile.
7528   if (hasMemory || IA->hasSideEffects())
7529     Chain = getRoot();
7530   else
7531     Chain = DAG.getRoot();
7532 
7533   // Second pass over the constraints: compute which constraint option to use
7534   // and assign registers to constraints that want a specific physreg.
7535   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7536     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7537 
7538     // If this is an output operand with a matching input operand, look up the
7539     // matching input. If their types mismatch, e.g. one is an integer, the
7540     // other is floating point, or their sizes are different, flag it as an
7541     // error.
7542     if (OpInfo.hasMatchingInput()) {
7543       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7544       patchMatchingInput(OpInfo, Input, DAG);
7545     }
7546 
7547     // Compute the constraint code and ConstraintType to use.
7548     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7549 
7550     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7551         OpInfo.Type == InlineAsm::isClobber)
7552       continue;
7553 
7554     // If this is a memory input, and if the operand is not indirect, do what we
7555     // need to provide an address for the memory input.
7556     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7557         !OpInfo.isIndirect) {
7558       assert((OpInfo.isMultipleAlternative ||
7559               (OpInfo.Type == InlineAsm::isInput)) &&
7560              "Can only indirectify direct input operands!");
7561 
7562       // Memory operands really want the address of the value.
7563       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7564 
7565       // There is no longer a Value* corresponding to this operand.
7566       OpInfo.CallOperandVal = nullptr;
7567 
7568       // It is now an indirect operand.
7569       OpInfo.isIndirect = true;
7570     }
7571 
7572     // If this constraint is for a specific register, allocate it before
7573     // anything else.
7574     SDISelAsmOperandInfo &RefOpInfo =
7575         OpInfo.isMatchingInputConstraint()
7576             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7577             : ConstraintOperands[i];
7578     if (RefOpInfo.ConstraintType == TargetLowering::C_Register)
7579       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo);
7580   }
7581 
7582   // Third pass - Loop over all of the operands, assigning virtual or physregs
7583   // to register class operands.
7584   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7585     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7586     SDISelAsmOperandInfo &RefOpInfo =
7587         OpInfo.isMatchingInputConstraint()
7588             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7589             : ConstraintOperands[i];
7590 
7591     // C_Register operands have already been allocated, Other/Memory don't need
7592     // to be.
7593     if (RefOpInfo.ConstraintType == TargetLowering::C_RegisterClass)
7594       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo);
7595   }
7596 
7597   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7598   std::vector<SDValue> AsmNodeOperands;
7599   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7600   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7601       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7602 
7603   // If we have a !srcloc metadata node associated with it, we want to attach
7604   // this to the ultimately generated inline asm machineinstr.  To do this, we
7605   // pass in the third operand as this (potentially null) inline asm MDNode.
7606   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7607   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7608 
7609   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7610   // bits as operand 3.
7611   AsmNodeOperands.push_back(DAG.getTargetConstant(
7612       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7613 
7614   // Loop over all of the inputs, copying the operand values into the
7615   // appropriate registers and processing the output regs.
7616   RegsForValue RetValRegs;
7617 
7618   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
7619   std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
7620 
7621   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7622     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7623 
7624     switch (OpInfo.Type) {
7625     case InlineAsm::isOutput:
7626       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
7627           OpInfo.ConstraintType != TargetLowering::C_Register) {
7628         // Memory output, or 'other' output (e.g. 'X' constraint).
7629         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
7630 
7631         unsigned ConstraintID =
7632             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7633         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7634                "Failed to convert memory constraint code to constraint id.");
7635 
7636         // Add information to the INLINEASM node to know about this output.
7637         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7638         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7639         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7640                                                         MVT::i32));
7641         AsmNodeOperands.push_back(OpInfo.CallOperand);
7642         break;
7643       }
7644 
7645       // Otherwise, this is a register or register class output.
7646 
7647       // Copy the output from the appropriate register.  Find a register that
7648       // we can use.
7649       if (OpInfo.AssignedRegs.Regs.empty()) {
7650         emitInlineAsmError(
7651             CS, "couldn't allocate output register for constraint '" +
7652                     Twine(OpInfo.ConstraintCode) + "'");
7653         return;
7654       }
7655 
7656       // If this is an indirect operand, store through the pointer after the
7657       // asm.
7658       if (OpInfo.isIndirect) {
7659         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
7660                                                       OpInfo.CallOperandVal));
7661       } else {
7662         // This is the result value of the call.
7663         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7664         // Concatenate this output onto the outputs list.
7665         RetValRegs.append(OpInfo.AssignedRegs);
7666       }
7667 
7668       // Add information to the INLINEASM node to know that this register is
7669       // set.
7670       OpInfo.AssignedRegs
7671           .AddInlineAsmOperands(OpInfo.isEarlyClobber
7672                                     ? InlineAsm::Kind_RegDefEarlyClobber
7673                                     : InlineAsm::Kind_RegDef,
7674                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7675       break;
7676 
7677     case InlineAsm::isInput: {
7678       SDValue InOperandVal = OpInfo.CallOperand;
7679 
7680       if (OpInfo.isMatchingInputConstraint()) {
7681         // If this is required to match an output register we have already set,
7682         // just use its register.
7683         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7684                                                   AsmNodeOperands);
7685         unsigned OpFlag =
7686           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7687         if (InlineAsm::isRegDefKind(OpFlag) ||
7688             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7689           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7690           if (OpInfo.isIndirect) {
7691             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7692             emitInlineAsmError(CS, "inline asm not supported yet:"
7693                                    " don't know how to handle tied "
7694                                    "indirect register inputs");
7695             return;
7696           }
7697 
7698           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7699           SmallVector<unsigned, 4> Regs;
7700 
7701           if (!createVirtualRegs(Regs,
7702                                  InlineAsm::getNumOperandRegisters(OpFlag),
7703                                  RegVT, DAG)) {
7704             emitInlineAsmError(CS, "inline asm error: This value type register "
7705                                    "class is not natively supported!");
7706             return;
7707           }
7708 
7709           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7710 
7711           SDLoc dl = getCurSDLoc();
7712           // Use the produced MatchedRegs object to
7713           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7714                                     CS.getInstruction());
7715           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7716                                            true, OpInfo.getMatchedOperand(), dl,
7717                                            DAG, AsmNodeOperands);
7718           break;
7719         }
7720 
7721         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7722         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7723                "Unexpected number of operands");
7724         // Add information to the INLINEASM node to know about this input.
7725         // See InlineAsm.h isUseOperandTiedToDef.
7726         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7727         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7728                                                     OpInfo.getMatchedOperand());
7729         AsmNodeOperands.push_back(DAG.getTargetConstant(
7730             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7731         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7732         break;
7733       }
7734 
7735       // Treat indirect 'X' constraint as memory.
7736       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7737           OpInfo.isIndirect)
7738         OpInfo.ConstraintType = TargetLowering::C_Memory;
7739 
7740       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7741         std::vector<SDValue> Ops;
7742         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7743                                           Ops, DAG);
7744         if (Ops.empty()) {
7745           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7746                                      Twine(OpInfo.ConstraintCode) + "'");
7747           return;
7748         }
7749 
7750         // Add information to the INLINEASM node to know about this input.
7751         unsigned ResOpType =
7752           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7753         AsmNodeOperands.push_back(DAG.getTargetConstant(
7754             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7755         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7756         break;
7757       }
7758 
7759       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7760         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7761         assert(InOperandVal.getValueType() ==
7762                    TLI.getPointerTy(DAG.getDataLayout()) &&
7763                "Memory operands expect pointer values");
7764 
7765         unsigned ConstraintID =
7766             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7767         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7768                "Failed to convert memory constraint code to constraint id.");
7769 
7770         // Add information to the INLINEASM node to know about this input.
7771         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7772         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7773         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7774                                                         getCurSDLoc(),
7775                                                         MVT::i32));
7776         AsmNodeOperands.push_back(InOperandVal);
7777         break;
7778       }
7779 
7780       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7781               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7782              "Unknown constraint type!");
7783 
7784       // TODO: Support this.
7785       if (OpInfo.isIndirect) {
7786         emitInlineAsmError(
7787             CS, "Don't know how to handle indirect register inputs yet "
7788                 "for constraint '" +
7789                     Twine(OpInfo.ConstraintCode) + "'");
7790         return;
7791       }
7792 
7793       // Copy the input into the appropriate registers.
7794       if (OpInfo.AssignedRegs.Regs.empty()) {
7795         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7796                                    Twine(OpInfo.ConstraintCode) + "'");
7797         return;
7798       }
7799 
7800       SDLoc dl = getCurSDLoc();
7801 
7802       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7803                                         Chain, &Flag, CS.getInstruction());
7804 
7805       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7806                                                dl, DAG, AsmNodeOperands);
7807       break;
7808     }
7809     case InlineAsm::isClobber:
7810       // Add the clobbered value to the operand list, so that the register
7811       // allocator is aware that the physreg got clobbered.
7812       if (!OpInfo.AssignedRegs.Regs.empty())
7813         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7814                                                  false, 0, getCurSDLoc(), DAG,
7815                                                  AsmNodeOperands);
7816       break;
7817     }
7818   }
7819 
7820   // Finish up input operands.  Set the input chain and add the flag last.
7821   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7822   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7823 
7824   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7825                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7826   Flag = Chain.getValue(1);
7827 
7828   // If this asm returns a register value, copy the result from that register
7829   // and set it as the value of the call.
7830   if (!RetValRegs.Regs.empty()) {
7831     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7832                                              Chain, &Flag, CS.getInstruction());
7833 
7834     llvm::Type *CSResultType = CS.getType();
7835     unsigned numRet;
7836     ArrayRef<Type *> ResultTypes;
7837     SmallVector<SDValue, 1> ResultValues(1);
7838     if (CSResultType->isSingleValueType()) {
7839       numRet = 1;
7840       ResultValues[0] = Val;
7841       ResultTypes = makeArrayRef(CSResultType);
7842     } else {
7843       numRet = CSResultType->getNumContainedTypes();
7844       assert(Val->getNumOperands() == numRet &&
7845              "Mismatch in number of output operands in asm result");
7846       ResultTypes = CSResultType->subtypes();
7847       ArrayRef<SDUse> ValueUses = Val->ops();
7848       ResultValues.resize(numRet);
7849       std::transform(ValueUses.begin(), ValueUses.end(), ResultValues.begin(),
7850                      [](const SDUse &u) -> SDValue { return u.get(); });
7851     }
7852     SmallVector<EVT, 1> ResultVTs(numRet);
7853     for (unsigned i = 0; i < numRet; i++) {
7854       EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), ResultTypes[i]);
7855       SDValue Val = ResultValues[i];
7856       assert(ResultTypes[i]->isSized() && "Unexpected unsized type");
7857       // If the type of the inline asm call site return value is different but
7858       // has same size as the type of the asm output bitcast it.  One example
7859       // of this is for vectors with different width / number of elements.
7860       // This can happen for register classes that can contain multiple
7861       // different value types.  The preg or vreg allocated may not have the
7862       // same VT as was expected.
7863       //
7864       // This can also happen for a return value that disagrees with the
7865       // register class it is put in, eg. a double in a general-purpose
7866       // register on a 32-bit machine.
7867       if (ResultVT != Val.getValueType() &&
7868           ResultVT.getSizeInBits() == Val.getValueSizeInBits())
7869         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, Val);
7870       else if (ResultVT != Val.getValueType() && ResultVT.isInteger() &&
7871                Val.getValueType().isInteger()) {
7872         // If a result value was tied to an input value, the computed result
7873         // may have a wider width than the expected result.  Extract the
7874         // relevant portion.
7875         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, Val);
7876       }
7877 
7878       assert(ResultVT == Val.getValueType() && "Asm result value mismatch!");
7879       ResultVTs[i] = ResultVT;
7880       ResultValues[i] = Val;
7881     }
7882 
7883     Val = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
7884                       DAG.getVTList(ResultVTs), ResultValues);
7885     setValue(CS.getInstruction(), Val);
7886     // Don't need to use this as a chain in this case.
7887     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
7888       return;
7889   }
7890 
7891   std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
7892 
7893   // Process indirect outputs, first output all of the flagged copies out of
7894   // physregs.
7895   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
7896     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
7897     const Value *Ptr = IndirectStoresToEmit[i].second;
7898     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7899                                              Chain, &Flag, IA);
7900     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
7901   }
7902 
7903   // Emit the non-flagged stores from the physregs.
7904   SmallVector<SDValue, 8> OutChains;
7905   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
7906     SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
7907                                getValue(StoresToEmit[i].second),
7908                                MachinePointerInfo(StoresToEmit[i].second));
7909     OutChains.push_back(Val);
7910   }
7911 
7912   if (!OutChains.empty())
7913     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7914 
7915   DAG.setRoot(Chain);
7916 }
7917 
7918 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7919                                              const Twine &Message) {
7920   LLVMContext &Ctx = *DAG.getContext();
7921   Ctx.emitError(CS.getInstruction(), Message);
7922 
7923   // Make sure we leave the DAG in a valid state
7924   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7925   SmallVector<EVT, 1> ValueVTs;
7926   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7927 
7928   if (ValueVTs.empty())
7929     return;
7930 
7931   SmallVector<SDValue, 1> Ops;
7932   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
7933     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
7934 
7935   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
7936 }
7937 
7938 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
7939   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
7940                           MVT::Other, getRoot(),
7941                           getValue(I.getArgOperand(0)),
7942                           DAG.getSrcValue(I.getArgOperand(0))));
7943 }
7944 
7945 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
7946   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7947   const DataLayout &DL = DAG.getDataLayout();
7948   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7949                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
7950                            DAG.getSrcValue(I.getOperand(0)),
7951                            DL.getABITypeAlignment(I.getType()));
7952   setValue(&I, V);
7953   DAG.setRoot(V.getValue(1));
7954 }
7955 
7956 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
7957   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
7958                           MVT::Other, getRoot(),
7959                           getValue(I.getArgOperand(0)),
7960                           DAG.getSrcValue(I.getArgOperand(0))));
7961 }
7962 
7963 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
7964   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
7965                           MVT::Other, getRoot(),
7966                           getValue(I.getArgOperand(0)),
7967                           getValue(I.getArgOperand(1)),
7968                           DAG.getSrcValue(I.getArgOperand(0)),
7969                           DAG.getSrcValue(I.getArgOperand(1))));
7970 }
7971 
7972 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
7973                                                     const Instruction &I,
7974                                                     SDValue Op) {
7975   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
7976   if (!Range)
7977     return Op;
7978 
7979   ConstantRange CR = getConstantRangeFromMetadata(*Range);
7980   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
7981     return Op;
7982 
7983   APInt Lo = CR.getUnsignedMin();
7984   if (!Lo.isMinValue())
7985     return Op;
7986 
7987   APInt Hi = CR.getUnsignedMax();
7988   unsigned Bits = Hi.getActiveBits();
7989 
7990   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7991 
7992   SDLoc SL = getCurSDLoc();
7993 
7994   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
7995                              DAG.getValueType(SmallVT));
7996   unsigned NumVals = Op.getNode()->getNumValues();
7997   if (NumVals == 1)
7998     return ZExt;
7999 
8000   SmallVector<SDValue, 4> Ops;
8001 
8002   Ops.push_back(ZExt);
8003   for (unsigned I = 1; I != NumVals; ++I)
8004     Ops.push_back(Op.getValue(I));
8005 
8006   return DAG.getMergeValues(Ops, SL);
8007 }
8008 
8009 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8010 /// the call being lowered.
8011 ///
8012 /// This is a helper for lowering intrinsics that follow a target calling
8013 /// convention or require stack pointer adjustment. Only a subset of the
8014 /// intrinsic's operands need to participate in the calling convention.
8015 void SelectionDAGBuilder::populateCallLoweringInfo(
8016     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
8017     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8018     bool IsPatchPoint) {
8019   TargetLowering::ArgListTy Args;
8020   Args.reserve(NumArgs);
8021 
8022   // Populate the argument list.
8023   // Attributes for args start at offset 1, after the return attribute.
8024   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8025        ArgI != ArgE; ++ArgI) {
8026     const Value *V = CS->getOperand(ArgI);
8027 
8028     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8029 
8030     TargetLowering::ArgListEntry Entry;
8031     Entry.Node = getValue(V);
8032     Entry.Ty = V->getType();
8033     Entry.setAttributes(&CS, ArgI);
8034     Args.push_back(Entry);
8035   }
8036 
8037   CLI.setDebugLoc(getCurSDLoc())
8038       .setChain(getRoot())
8039       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
8040       .setDiscardResult(CS->use_empty())
8041       .setIsPatchPoint(IsPatchPoint);
8042 }
8043 
8044 /// Add a stack map intrinsic call's live variable operands to a stackmap
8045 /// or patchpoint target node's operand list.
8046 ///
8047 /// Constants are converted to TargetConstants purely as an optimization to
8048 /// avoid constant materialization and register allocation.
8049 ///
8050 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8051 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8052 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8053 /// address materialization and register allocation, but may also be required
8054 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8055 /// alloca in the entry block, then the runtime may assume that the alloca's
8056 /// StackMap location can be read immediately after compilation and that the
8057 /// location is valid at any point during execution (this is similar to the
8058 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8059 /// only available in a register, then the runtime would need to trap when
8060 /// execution reaches the StackMap in order to read the alloca's location.
8061 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8062                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8063                                 SelectionDAGBuilder &Builder) {
8064   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8065     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8066     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8067       Ops.push_back(
8068         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8069       Ops.push_back(
8070         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8071     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8072       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8073       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8074           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8075     } else
8076       Ops.push_back(OpVal);
8077   }
8078 }
8079 
8080 /// Lower llvm.experimental.stackmap directly to its target opcode.
8081 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8082   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8083   //                                  [live variables...])
8084 
8085   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8086 
8087   SDValue Chain, InFlag, Callee, NullPtr;
8088   SmallVector<SDValue, 32> Ops;
8089 
8090   SDLoc DL = getCurSDLoc();
8091   Callee = getValue(CI.getCalledValue());
8092   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8093 
8094   // The stackmap intrinsic only records the live variables (the arguemnts
8095   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8096   // intrinsic, this won't be lowered to a function call. This means we don't
8097   // have to worry about calling conventions and target specific lowering code.
8098   // Instead we perform the call lowering right here.
8099   //
8100   // chain, flag = CALLSEQ_START(chain, 0, 0)
8101   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8102   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8103   //
8104   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8105   InFlag = Chain.getValue(1);
8106 
8107   // Add the <id> and <numBytes> constants.
8108   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8109   Ops.push_back(DAG.getTargetConstant(
8110                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8111   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8112   Ops.push_back(DAG.getTargetConstant(
8113                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8114                   MVT::i32));
8115 
8116   // Push live variables for the stack map.
8117   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8118 
8119   // We are not pushing any register mask info here on the operands list,
8120   // because the stackmap doesn't clobber anything.
8121 
8122   // Push the chain and the glue flag.
8123   Ops.push_back(Chain);
8124   Ops.push_back(InFlag);
8125 
8126   // Create the STACKMAP node.
8127   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8128   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8129   Chain = SDValue(SM, 0);
8130   InFlag = Chain.getValue(1);
8131 
8132   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8133 
8134   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8135 
8136   // Set the root to the target-lowered call chain.
8137   DAG.setRoot(Chain);
8138 
8139   // Inform the Frame Information that we have a stackmap in this function.
8140   FuncInfo.MF->getFrameInfo().setHasStackMap();
8141 }
8142 
8143 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8144 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8145                                           const BasicBlock *EHPadBB) {
8146   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8147   //                                                 i32 <numBytes>,
8148   //                                                 i8* <target>,
8149   //                                                 i32 <numArgs>,
8150   //                                                 [Args...],
8151   //                                                 [live variables...])
8152 
8153   CallingConv::ID CC = CS.getCallingConv();
8154   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8155   bool HasDef = !CS->getType()->isVoidTy();
8156   SDLoc dl = getCurSDLoc();
8157   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8158 
8159   // Handle immediate and symbolic callees.
8160   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8161     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8162                                    /*isTarget=*/true);
8163   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8164     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8165                                          SDLoc(SymbolicCallee),
8166                                          SymbolicCallee->getValueType(0));
8167 
8168   // Get the real number of arguments participating in the call <numArgs>
8169   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8170   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8171 
8172   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8173   // Intrinsics include all meta-operands up to but not including CC.
8174   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8175   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8176          "Not enough arguments provided to the patchpoint intrinsic");
8177 
8178   // For AnyRegCC the arguments are lowered later on manually.
8179   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8180   Type *ReturnTy =
8181     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8182 
8183   TargetLowering::CallLoweringInfo CLI(DAG);
8184   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
8185                            true);
8186   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8187 
8188   SDNode *CallEnd = Result.second.getNode();
8189   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8190     CallEnd = CallEnd->getOperand(0).getNode();
8191 
8192   /// Get a call instruction from the call sequence chain.
8193   /// Tail calls are not allowed.
8194   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8195          "Expected a callseq node.");
8196   SDNode *Call = CallEnd->getOperand(0).getNode();
8197   bool HasGlue = Call->getGluedNode();
8198 
8199   // Replace the target specific call node with the patchable intrinsic.
8200   SmallVector<SDValue, 8> Ops;
8201 
8202   // Add the <id> and <numBytes> constants.
8203   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8204   Ops.push_back(DAG.getTargetConstant(
8205                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8206   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8207   Ops.push_back(DAG.getTargetConstant(
8208                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8209                   MVT::i32));
8210 
8211   // Add the callee.
8212   Ops.push_back(Callee);
8213 
8214   // Adjust <numArgs> to account for any arguments that have been passed on the
8215   // stack instead.
8216   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8217   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8218   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8219   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8220 
8221   // Add the calling convention
8222   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8223 
8224   // Add the arguments we omitted previously. The register allocator should
8225   // place these in any free register.
8226   if (IsAnyRegCC)
8227     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8228       Ops.push_back(getValue(CS.getArgument(i)));
8229 
8230   // Push the arguments from the call instruction up to the register mask.
8231   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8232   Ops.append(Call->op_begin() + 2, e);
8233 
8234   // Push live variables for the stack map.
8235   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8236 
8237   // Push the register mask info.
8238   if (HasGlue)
8239     Ops.push_back(*(Call->op_end()-2));
8240   else
8241     Ops.push_back(*(Call->op_end()-1));
8242 
8243   // Push the chain (this is originally the first operand of the call, but
8244   // becomes now the last or second to last operand).
8245   Ops.push_back(*(Call->op_begin()));
8246 
8247   // Push the glue flag (last operand).
8248   if (HasGlue)
8249     Ops.push_back(*(Call->op_end()-1));
8250 
8251   SDVTList NodeTys;
8252   if (IsAnyRegCC && HasDef) {
8253     // Create the return types based on the intrinsic definition
8254     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8255     SmallVector<EVT, 3> ValueVTs;
8256     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8257     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8258 
8259     // There is always a chain and a glue type at the end
8260     ValueVTs.push_back(MVT::Other);
8261     ValueVTs.push_back(MVT::Glue);
8262     NodeTys = DAG.getVTList(ValueVTs);
8263   } else
8264     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8265 
8266   // Replace the target specific call node with a PATCHPOINT node.
8267   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8268                                          dl, NodeTys, Ops);
8269 
8270   // Update the NodeMap.
8271   if (HasDef) {
8272     if (IsAnyRegCC)
8273       setValue(CS.getInstruction(), SDValue(MN, 0));
8274     else
8275       setValue(CS.getInstruction(), Result.first);
8276   }
8277 
8278   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8279   // call sequence. Furthermore the location of the chain and glue can change
8280   // when the AnyReg calling convention is used and the intrinsic returns a
8281   // value.
8282   if (IsAnyRegCC && HasDef) {
8283     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8284     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8285     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8286   } else
8287     DAG.ReplaceAllUsesWith(Call, MN);
8288   DAG.DeleteNode(Call);
8289 
8290   // Inform the Frame Information that we have a patchpoint in this function.
8291   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8292 }
8293 
8294 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8295                                             unsigned Intrinsic) {
8296   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8297   SDValue Op1 = getValue(I.getArgOperand(0));
8298   SDValue Op2;
8299   if (I.getNumArgOperands() > 1)
8300     Op2 = getValue(I.getArgOperand(1));
8301   SDLoc dl = getCurSDLoc();
8302   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8303   SDValue Res;
8304   FastMathFlags FMF;
8305   if (isa<FPMathOperator>(I))
8306     FMF = I.getFastMathFlags();
8307 
8308   switch (Intrinsic) {
8309   case Intrinsic::experimental_vector_reduce_fadd:
8310     if (FMF.isFast())
8311       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8312     else
8313       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8314     break;
8315   case Intrinsic::experimental_vector_reduce_fmul:
8316     if (FMF.isFast())
8317       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8318     else
8319       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8320     break;
8321   case Intrinsic::experimental_vector_reduce_add:
8322     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8323     break;
8324   case Intrinsic::experimental_vector_reduce_mul:
8325     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8326     break;
8327   case Intrinsic::experimental_vector_reduce_and:
8328     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8329     break;
8330   case Intrinsic::experimental_vector_reduce_or:
8331     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8332     break;
8333   case Intrinsic::experimental_vector_reduce_xor:
8334     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8335     break;
8336   case Intrinsic::experimental_vector_reduce_smax:
8337     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8338     break;
8339   case Intrinsic::experimental_vector_reduce_smin:
8340     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8341     break;
8342   case Intrinsic::experimental_vector_reduce_umax:
8343     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8344     break;
8345   case Intrinsic::experimental_vector_reduce_umin:
8346     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8347     break;
8348   case Intrinsic::experimental_vector_reduce_fmax:
8349     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8350     break;
8351   case Intrinsic::experimental_vector_reduce_fmin:
8352     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8353     break;
8354   default:
8355     llvm_unreachable("Unhandled vector reduce intrinsic");
8356   }
8357   setValue(&I, Res);
8358 }
8359 
8360 /// Returns an AttributeList representing the attributes applied to the return
8361 /// value of the given call.
8362 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8363   SmallVector<Attribute::AttrKind, 2> Attrs;
8364   if (CLI.RetSExt)
8365     Attrs.push_back(Attribute::SExt);
8366   if (CLI.RetZExt)
8367     Attrs.push_back(Attribute::ZExt);
8368   if (CLI.IsInReg)
8369     Attrs.push_back(Attribute::InReg);
8370 
8371   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8372                             Attrs);
8373 }
8374 
8375 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8376 /// implementation, which just calls LowerCall.
8377 /// FIXME: When all targets are
8378 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8379 std::pair<SDValue, SDValue>
8380 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8381   // Handle the incoming return values from the call.
8382   CLI.Ins.clear();
8383   Type *OrigRetTy = CLI.RetTy;
8384   SmallVector<EVT, 4> RetTys;
8385   SmallVector<uint64_t, 4> Offsets;
8386   auto &DL = CLI.DAG.getDataLayout();
8387   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8388 
8389   if (CLI.IsPostTypeLegalization) {
8390     // If we are lowering a libcall after legalization, split the return type.
8391     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8392     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8393     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8394       EVT RetVT = OldRetTys[i];
8395       uint64_t Offset = OldOffsets[i];
8396       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8397       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8398       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8399       RetTys.append(NumRegs, RegisterVT);
8400       for (unsigned j = 0; j != NumRegs; ++j)
8401         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8402     }
8403   }
8404 
8405   SmallVector<ISD::OutputArg, 4> Outs;
8406   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8407 
8408   bool CanLowerReturn =
8409       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8410                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8411 
8412   SDValue DemoteStackSlot;
8413   int DemoteStackIdx = -100;
8414   if (!CanLowerReturn) {
8415     // FIXME: equivalent assert?
8416     // assert(!CS.hasInAllocaArgument() &&
8417     //        "sret demotion is incompatible with inalloca");
8418     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8419     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8420     MachineFunction &MF = CLI.DAG.getMachineFunction();
8421     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8422     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8423                                               DL.getAllocaAddrSpace());
8424 
8425     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8426     ArgListEntry Entry;
8427     Entry.Node = DemoteStackSlot;
8428     Entry.Ty = StackSlotPtrType;
8429     Entry.IsSExt = false;
8430     Entry.IsZExt = false;
8431     Entry.IsInReg = false;
8432     Entry.IsSRet = true;
8433     Entry.IsNest = false;
8434     Entry.IsByVal = false;
8435     Entry.IsReturned = false;
8436     Entry.IsSwiftSelf = false;
8437     Entry.IsSwiftError = false;
8438     Entry.Alignment = Align;
8439     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8440     CLI.NumFixedArgs += 1;
8441     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8442 
8443     // sret demotion isn't compatible with tail-calls, since the sret argument
8444     // points into the callers stack frame.
8445     CLI.IsTailCall = false;
8446   } else {
8447     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8448       EVT VT = RetTys[I];
8449       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8450                                                      CLI.CallConv, VT);
8451       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8452                                                        CLI.CallConv, VT);
8453       for (unsigned i = 0; i != NumRegs; ++i) {
8454         ISD::InputArg MyFlags;
8455         MyFlags.VT = RegisterVT;
8456         MyFlags.ArgVT = VT;
8457         MyFlags.Used = CLI.IsReturnValueUsed;
8458         if (CLI.RetSExt)
8459           MyFlags.Flags.setSExt();
8460         if (CLI.RetZExt)
8461           MyFlags.Flags.setZExt();
8462         if (CLI.IsInReg)
8463           MyFlags.Flags.setInReg();
8464         CLI.Ins.push_back(MyFlags);
8465       }
8466     }
8467   }
8468 
8469   // We push in swifterror return as the last element of CLI.Ins.
8470   ArgListTy &Args = CLI.getArgs();
8471   if (supportSwiftError()) {
8472     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8473       if (Args[i].IsSwiftError) {
8474         ISD::InputArg MyFlags;
8475         MyFlags.VT = getPointerTy(DL);
8476         MyFlags.ArgVT = EVT(getPointerTy(DL));
8477         MyFlags.Flags.setSwiftError();
8478         CLI.Ins.push_back(MyFlags);
8479       }
8480     }
8481   }
8482 
8483   // Handle all of the outgoing arguments.
8484   CLI.Outs.clear();
8485   CLI.OutVals.clear();
8486   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8487     SmallVector<EVT, 4> ValueVTs;
8488     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8489     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8490     Type *FinalType = Args[i].Ty;
8491     if (Args[i].IsByVal)
8492       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8493     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8494         FinalType, CLI.CallConv, CLI.IsVarArg);
8495     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8496          ++Value) {
8497       EVT VT = ValueVTs[Value];
8498       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8499       SDValue Op = SDValue(Args[i].Node.getNode(),
8500                            Args[i].Node.getResNo() + Value);
8501       ISD::ArgFlagsTy Flags;
8502 
8503       // Certain targets (such as MIPS), may have a different ABI alignment
8504       // for a type depending on the context. Give the target a chance to
8505       // specify the alignment it wants.
8506       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8507 
8508       if (Args[i].IsZExt)
8509         Flags.setZExt();
8510       if (Args[i].IsSExt)
8511         Flags.setSExt();
8512       if (Args[i].IsInReg) {
8513         // If we are using vectorcall calling convention, a structure that is
8514         // passed InReg - is surely an HVA
8515         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8516             isa<StructType>(FinalType)) {
8517           // The first value of a structure is marked
8518           if (0 == Value)
8519             Flags.setHvaStart();
8520           Flags.setHva();
8521         }
8522         // Set InReg Flag
8523         Flags.setInReg();
8524       }
8525       if (Args[i].IsSRet)
8526         Flags.setSRet();
8527       if (Args[i].IsSwiftSelf)
8528         Flags.setSwiftSelf();
8529       if (Args[i].IsSwiftError)
8530         Flags.setSwiftError();
8531       if (Args[i].IsByVal)
8532         Flags.setByVal();
8533       if (Args[i].IsInAlloca) {
8534         Flags.setInAlloca();
8535         // Set the byval flag for CCAssignFn callbacks that don't know about
8536         // inalloca.  This way we can know how many bytes we should've allocated
8537         // and how many bytes a callee cleanup function will pop.  If we port
8538         // inalloca to more targets, we'll have to add custom inalloca handling
8539         // in the various CC lowering callbacks.
8540         Flags.setByVal();
8541       }
8542       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8543         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8544         Type *ElementTy = Ty->getElementType();
8545         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8546         // For ByVal, alignment should come from FE.  BE will guess if this
8547         // info is not there but there are cases it cannot get right.
8548         unsigned FrameAlign;
8549         if (Args[i].Alignment)
8550           FrameAlign = Args[i].Alignment;
8551         else
8552           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8553         Flags.setByValAlign(FrameAlign);
8554       }
8555       if (Args[i].IsNest)
8556         Flags.setNest();
8557       if (NeedsRegBlock)
8558         Flags.setInConsecutiveRegs();
8559       Flags.setOrigAlign(OriginalAlignment);
8560 
8561       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8562                                                  CLI.CallConv, VT);
8563       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8564                                                         CLI.CallConv, VT);
8565       SmallVector<SDValue, 4> Parts(NumParts);
8566       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8567 
8568       if (Args[i].IsSExt)
8569         ExtendKind = ISD::SIGN_EXTEND;
8570       else if (Args[i].IsZExt)
8571         ExtendKind = ISD::ZERO_EXTEND;
8572 
8573       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8574       // for now.
8575       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8576           CanLowerReturn) {
8577         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8578                "unexpected use of 'returned'");
8579         // Before passing 'returned' to the target lowering code, ensure that
8580         // either the register MVT and the actual EVT are the same size or that
8581         // the return value and argument are extended in the same way; in these
8582         // cases it's safe to pass the argument register value unchanged as the
8583         // return register value (although it's at the target's option whether
8584         // to do so)
8585         // TODO: allow code generation to take advantage of partially preserved
8586         // registers rather than clobbering the entire register when the
8587         // parameter extension method is not compatible with the return
8588         // extension method
8589         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8590             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8591              CLI.RetZExt == Args[i].IsZExt))
8592           Flags.setReturned();
8593       }
8594 
8595       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8596                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
8597 
8598       for (unsigned j = 0; j != NumParts; ++j) {
8599         // if it isn't first piece, alignment must be 1
8600         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8601                                i < CLI.NumFixedArgs,
8602                                i, j*Parts[j].getValueType().getStoreSize());
8603         if (NumParts > 1 && j == 0)
8604           MyFlags.Flags.setSplit();
8605         else if (j != 0) {
8606           MyFlags.Flags.setOrigAlign(1);
8607           if (j == NumParts - 1)
8608             MyFlags.Flags.setSplitEnd();
8609         }
8610 
8611         CLI.Outs.push_back(MyFlags);
8612         CLI.OutVals.push_back(Parts[j]);
8613       }
8614 
8615       if (NeedsRegBlock && Value == NumValues - 1)
8616         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8617     }
8618   }
8619 
8620   SmallVector<SDValue, 4> InVals;
8621   CLI.Chain = LowerCall(CLI, InVals);
8622 
8623   // Update CLI.InVals to use outside of this function.
8624   CLI.InVals = InVals;
8625 
8626   // Verify that the target's LowerCall behaved as expected.
8627   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8628          "LowerCall didn't return a valid chain!");
8629   assert((!CLI.IsTailCall || InVals.empty()) &&
8630          "LowerCall emitted a return value for a tail call!");
8631   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8632          "LowerCall didn't emit the correct number of values!");
8633 
8634   // For a tail call, the return value is merely live-out and there aren't
8635   // any nodes in the DAG representing it. Return a special value to
8636   // indicate that a tail call has been emitted and no more Instructions
8637   // should be processed in the current block.
8638   if (CLI.IsTailCall) {
8639     CLI.DAG.setRoot(CLI.Chain);
8640     return std::make_pair(SDValue(), SDValue());
8641   }
8642 
8643 #ifndef NDEBUG
8644   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8645     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8646     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8647            "LowerCall emitted a value with the wrong type!");
8648   }
8649 #endif
8650 
8651   SmallVector<SDValue, 4> ReturnValues;
8652   if (!CanLowerReturn) {
8653     // The instruction result is the result of loading from the
8654     // hidden sret parameter.
8655     SmallVector<EVT, 1> PVTs;
8656     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8657 
8658     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8659     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8660     EVT PtrVT = PVTs[0];
8661 
8662     unsigned NumValues = RetTys.size();
8663     ReturnValues.resize(NumValues);
8664     SmallVector<SDValue, 4> Chains(NumValues);
8665 
8666     // An aggregate return value cannot wrap around the address space, so
8667     // offsets to its parts don't wrap either.
8668     SDNodeFlags Flags;
8669     Flags.setNoUnsignedWrap(true);
8670 
8671     for (unsigned i = 0; i < NumValues; ++i) {
8672       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8673                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8674                                                         PtrVT), Flags);
8675       SDValue L = CLI.DAG.getLoad(
8676           RetTys[i], CLI.DL, CLI.Chain, Add,
8677           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8678                                             DemoteStackIdx, Offsets[i]),
8679           /* Alignment = */ 1);
8680       ReturnValues[i] = L;
8681       Chains[i] = L.getValue(1);
8682     }
8683 
8684     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8685   } else {
8686     // Collect the legal value parts into potentially illegal values
8687     // that correspond to the original function's return values.
8688     Optional<ISD::NodeType> AssertOp;
8689     if (CLI.RetSExt)
8690       AssertOp = ISD::AssertSext;
8691     else if (CLI.RetZExt)
8692       AssertOp = ISD::AssertZext;
8693     unsigned CurReg = 0;
8694     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8695       EVT VT = RetTys[I];
8696       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8697                                                      CLI.CallConv, VT);
8698       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8699                                                        CLI.CallConv, VT);
8700 
8701       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8702                                               NumRegs, RegisterVT, VT, nullptr,
8703                                               CLI.CallConv, AssertOp));
8704       CurReg += NumRegs;
8705     }
8706 
8707     // For a function returning void, there is no return value. We can't create
8708     // such a node, so we just return a null return value in that case. In
8709     // that case, nothing will actually look at the value.
8710     if (ReturnValues.empty())
8711       return std::make_pair(SDValue(), CLI.Chain);
8712   }
8713 
8714   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8715                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8716   return std::make_pair(Res, CLI.Chain);
8717 }
8718 
8719 void TargetLowering::LowerOperationWrapper(SDNode *N,
8720                                            SmallVectorImpl<SDValue> &Results,
8721                                            SelectionDAG &DAG) const {
8722   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8723     Results.push_back(Res);
8724 }
8725 
8726 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8727   llvm_unreachable("LowerOperation not implemented for this target!");
8728 }
8729 
8730 void
8731 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8732   SDValue Op = getNonRegisterValue(V);
8733   assert((Op.getOpcode() != ISD::CopyFromReg ||
8734           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8735          "Copy from a reg to the same reg!");
8736   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8737 
8738   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8739   // If this is an InlineAsm we have to match the registers required, not the
8740   // notional registers required by the type.
8741 
8742   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
8743                    None); // This is not an ABI copy.
8744   SDValue Chain = DAG.getEntryNode();
8745 
8746   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8747                               FuncInfo.PreferredExtendType.end())
8748                                  ? ISD::ANY_EXTEND
8749                                  : FuncInfo.PreferredExtendType[V];
8750   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8751   PendingExports.push_back(Chain);
8752 }
8753 
8754 #include "llvm/CodeGen/SelectionDAGISel.h"
8755 
8756 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8757 /// entry block, return true.  This includes arguments used by switches, since
8758 /// the switch may expand into multiple basic blocks.
8759 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8760   // With FastISel active, we may be splitting blocks, so force creation
8761   // of virtual registers for all non-dead arguments.
8762   if (FastISel)
8763     return A->use_empty();
8764 
8765   const BasicBlock &Entry = A->getParent()->front();
8766   for (const User *U : A->users())
8767     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8768       return false;  // Use not in entry block.
8769 
8770   return true;
8771 }
8772 
8773 using ArgCopyElisionMapTy =
8774     DenseMap<const Argument *,
8775              std::pair<const AllocaInst *, const StoreInst *>>;
8776 
8777 /// Scan the entry block of the function in FuncInfo for arguments that look
8778 /// like copies into a local alloca. Record any copied arguments in
8779 /// ArgCopyElisionCandidates.
8780 static void
8781 findArgumentCopyElisionCandidates(const DataLayout &DL,
8782                                   FunctionLoweringInfo *FuncInfo,
8783                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8784   // Record the state of every static alloca used in the entry block. Argument
8785   // allocas are all used in the entry block, so we need approximately as many
8786   // entries as we have arguments.
8787   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8788   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8789   unsigned NumArgs = FuncInfo->Fn->arg_size();
8790   StaticAllocas.reserve(NumArgs * 2);
8791 
8792   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8793     if (!V)
8794       return nullptr;
8795     V = V->stripPointerCasts();
8796     const auto *AI = dyn_cast<AllocaInst>(V);
8797     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8798       return nullptr;
8799     auto Iter = StaticAllocas.insert({AI, Unknown});
8800     return &Iter.first->second;
8801   };
8802 
8803   // Look for stores of arguments to static allocas. Look through bitcasts and
8804   // GEPs to handle type coercions, as long as the alloca is fully initialized
8805   // by the store. Any non-store use of an alloca escapes it and any subsequent
8806   // unanalyzed store might write it.
8807   // FIXME: Handle structs initialized with multiple stores.
8808   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8809     // Look for stores, and handle non-store uses conservatively.
8810     const auto *SI = dyn_cast<StoreInst>(&I);
8811     if (!SI) {
8812       // We will look through cast uses, so ignore them completely.
8813       if (I.isCast())
8814         continue;
8815       // Ignore debug info intrinsics, they don't escape or store to allocas.
8816       if (isa<DbgInfoIntrinsic>(I))
8817         continue;
8818       // This is an unknown instruction. Assume it escapes or writes to all
8819       // static alloca operands.
8820       for (const Use &U : I.operands()) {
8821         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
8822           *Info = StaticAllocaInfo::Clobbered;
8823       }
8824       continue;
8825     }
8826 
8827     // If the stored value is a static alloca, mark it as escaped.
8828     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
8829       *Info = StaticAllocaInfo::Clobbered;
8830 
8831     // Check if the destination is a static alloca.
8832     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
8833     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
8834     if (!Info)
8835       continue;
8836     const AllocaInst *AI = cast<AllocaInst>(Dst);
8837 
8838     // Skip allocas that have been initialized or clobbered.
8839     if (*Info != StaticAllocaInfo::Unknown)
8840       continue;
8841 
8842     // Check if the stored value is an argument, and that this store fully
8843     // initializes the alloca. Don't elide copies from the same argument twice.
8844     const Value *Val = SI->getValueOperand()->stripPointerCasts();
8845     const auto *Arg = dyn_cast<Argument>(Val);
8846     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
8847         Arg->getType()->isEmptyTy() ||
8848         DL.getTypeStoreSize(Arg->getType()) !=
8849             DL.getTypeAllocSize(AI->getAllocatedType()) ||
8850         ArgCopyElisionCandidates.count(Arg)) {
8851       *Info = StaticAllocaInfo::Clobbered;
8852       continue;
8853     }
8854 
8855     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
8856                       << '\n');
8857 
8858     // Mark this alloca and store for argument copy elision.
8859     *Info = StaticAllocaInfo::Elidable;
8860     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
8861 
8862     // Stop scanning if we've seen all arguments. This will happen early in -O0
8863     // builds, which is useful, because -O0 builds have large entry blocks and
8864     // many allocas.
8865     if (ArgCopyElisionCandidates.size() == NumArgs)
8866       break;
8867   }
8868 }
8869 
8870 /// Try to elide argument copies from memory into a local alloca. Succeeds if
8871 /// ArgVal is a load from a suitable fixed stack object.
8872 static void tryToElideArgumentCopy(
8873     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
8874     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
8875     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
8876     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
8877     SDValue ArgVal, bool &ArgHasUses) {
8878   // Check if this is a load from a fixed stack object.
8879   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
8880   if (!LNode)
8881     return;
8882   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
8883   if (!FINode)
8884     return;
8885 
8886   // Check that the fixed stack object is the right size and alignment.
8887   // Look at the alignment that the user wrote on the alloca instead of looking
8888   // at the stack object.
8889   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
8890   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
8891   const AllocaInst *AI = ArgCopyIter->second.first;
8892   int FixedIndex = FINode->getIndex();
8893   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
8894   int OldIndex = AllocaIndex;
8895   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
8896   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
8897     LLVM_DEBUG(
8898         dbgs() << "  argument copy elision failed due to bad fixed stack "
8899                   "object size\n");
8900     return;
8901   }
8902   unsigned RequiredAlignment = AI->getAlignment();
8903   if (!RequiredAlignment) {
8904     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
8905         AI->getAllocatedType());
8906   }
8907   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
8908     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
8909                          "greater than stack argument alignment ("
8910                       << RequiredAlignment << " vs "
8911                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
8912     return;
8913   }
8914 
8915   // Perform the elision. Delete the old stack object and replace its only use
8916   // in the variable info map. Mark the stack object as mutable.
8917   LLVM_DEBUG({
8918     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
8919            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
8920            << '\n';
8921   });
8922   MFI.RemoveStackObject(OldIndex);
8923   MFI.setIsImmutableObjectIndex(FixedIndex, false);
8924   AllocaIndex = FixedIndex;
8925   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
8926   Chains.push_back(ArgVal.getValue(1));
8927 
8928   // Avoid emitting code for the store implementing the copy.
8929   const StoreInst *SI = ArgCopyIter->second.second;
8930   ElidedArgCopyInstrs.insert(SI);
8931 
8932   // Check for uses of the argument again so that we can avoid exporting ArgVal
8933   // if it is't used by anything other than the store.
8934   for (const Value *U : Arg.users()) {
8935     if (U != SI) {
8936       ArgHasUses = true;
8937       break;
8938     }
8939   }
8940 }
8941 
8942 void SelectionDAGISel::LowerArguments(const Function &F) {
8943   SelectionDAG &DAG = SDB->DAG;
8944   SDLoc dl = SDB->getCurSDLoc();
8945   const DataLayout &DL = DAG.getDataLayout();
8946   SmallVector<ISD::InputArg, 16> Ins;
8947 
8948   if (!FuncInfo->CanLowerReturn) {
8949     // Put in an sret pointer parameter before all the other parameters.
8950     SmallVector<EVT, 1> ValueVTs;
8951     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8952                     F.getReturnType()->getPointerTo(
8953                         DAG.getDataLayout().getAllocaAddrSpace()),
8954                     ValueVTs);
8955 
8956     // NOTE: Assuming that a pointer will never break down to more than one VT
8957     // or one register.
8958     ISD::ArgFlagsTy Flags;
8959     Flags.setSRet();
8960     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
8961     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
8962                          ISD::InputArg::NoArgIndex, 0);
8963     Ins.push_back(RetArg);
8964   }
8965 
8966   // Look for stores of arguments to static allocas. Mark such arguments with a
8967   // flag to ask the target to give us the memory location of that argument if
8968   // available.
8969   ArgCopyElisionMapTy ArgCopyElisionCandidates;
8970   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
8971 
8972   // Set up the incoming argument description vector.
8973   for (const Argument &Arg : F.args()) {
8974     unsigned ArgNo = Arg.getArgNo();
8975     SmallVector<EVT, 4> ValueVTs;
8976     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8977     bool isArgValueUsed = !Arg.use_empty();
8978     unsigned PartBase = 0;
8979     Type *FinalType = Arg.getType();
8980     if (Arg.hasAttribute(Attribute::ByVal))
8981       FinalType = cast<PointerType>(FinalType)->getElementType();
8982     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
8983         FinalType, F.getCallingConv(), F.isVarArg());
8984     for (unsigned Value = 0, NumValues = ValueVTs.size();
8985          Value != NumValues; ++Value) {
8986       EVT VT = ValueVTs[Value];
8987       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
8988       ISD::ArgFlagsTy Flags;
8989 
8990       // Certain targets (such as MIPS), may have a different ABI alignment
8991       // for a type depending on the context. Give the target a chance to
8992       // specify the alignment it wants.
8993       unsigned OriginalAlignment =
8994           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
8995 
8996       if (Arg.hasAttribute(Attribute::ZExt))
8997         Flags.setZExt();
8998       if (Arg.hasAttribute(Attribute::SExt))
8999         Flags.setSExt();
9000       if (Arg.hasAttribute(Attribute::InReg)) {
9001         // If we are using vectorcall calling convention, a structure that is
9002         // passed InReg - is surely an HVA
9003         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9004             isa<StructType>(Arg.getType())) {
9005           // The first value of a structure is marked
9006           if (0 == Value)
9007             Flags.setHvaStart();
9008           Flags.setHva();
9009         }
9010         // Set InReg Flag
9011         Flags.setInReg();
9012       }
9013       if (Arg.hasAttribute(Attribute::StructRet))
9014         Flags.setSRet();
9015       if (Arg.hasAttribute(Attribute::SwiftSelf))
9016         Flags.setSwiftSelf();
9017       if (Arg.hasAttribute(Attribute::SwiftError))
9018         Flags.setSwiftError();
9019       if (Arg.hasAttribute(Attribute::ByVal))
9020         Flags.setByVal();
9021       if (Arg.hasAttribute(Attribute::InAlloca)) {
9022         Flags.setInAlloca();
9023         // Set the byval flag for CCAssignFn callbacks that don't know about
9024         // inalloca.  This way we can know how many bytes we should've allocated
9025         // and how many bytes a callee cleanup function will pop.  If we port
9026         // inalloca to more targets, we'll have to add custom inalloca handling
9027         // in the various CC lowering callbacks.
9028         Flags.setByVal();
9029       }
9030       if (F.getCallingConv() == CallingConv::X86_INTR) {
9031         // IA Interrupt passes frame (1st parameter) by value in the stack.
9032         if (ArgNo == 0)
9033           Flags.setByVal();
9034       }
9035       if (Flags.isByVal() || Flags.isInAlloca()) {
9036         PointerType *Ty = cast<PointerType>(Arg.getType());
9037         Type *ElementTy = Ty->getElementType();
9038         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
9039         // For ByVal, alignment should be passed from FE.  BE will guess if
9040         // this info is not there but there are cases it cannot get right.
9041         unsigned FrameAlign;
9042         if (Arg.getParamAlignment())
9043           FrameAlign = Arg.getParamAlignment();
9044         else
9045           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9046         Flags.setByValAlign(FrameAlign);
9047       }
9048       if (Arg.hasAttribute(Attribute::Nest))
9049         Flags.setNest();
9050       if (NeedsRegBlock)
9051         Flags.setInConsecutiveRegs();
9052       Flags.setOrigAlign(OriginalAlignment);
9053       if (ArgCopyElisionCandidates.count(&Arg))
9054         Flags.setCopyElisionCandidate();
9055 
9056       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9057           *CurDAG->getContext(), F.getCallingConv(), VT);
9058       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9059           *CurDAG->getContext(), F.getCallingConv(), VT);
9060       for (unsigned i = 0; i != NumRegs; ++i) {
9061         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9062                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9063         if (NumRegs > 1 && i == 0)
9064           MyFlags.Flags.setSplit();
9065         // if it isn't first piece, alignment must be 1
9066         else if (i > 0) {
9067           MyFlags.Flags.setOrigAlign(1);
9068           if (i == NumRegs - 1)
9069             MyFlags.Flags.setSplitEnd();
9070         }
9071         Ins.push_back(MyFlags);
9072       }
9073       if (NeedsRegBlock && Value == NumValues - 1)
9074         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9075       PartBase += VT.getStoreSize();
9076     }
9077   }
9078 
9079   // Call the target to set up the argument values.
9080   SmallVector<SDValue, 8> InVals;
9081   SDValue NewRoot = TLI->LowerFormalArguments(
9082       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9083 
9084   // Verify that the target's LowerFormalArguments behaved as expected.
9085   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9086          "LowerFormalArguments didn't return a valid chain!");
9087   assert(InVals.size() == Ins.size() &&
9088          "LowerFormalArguments didn't emit the correct number of values!");
9089   LLVM_DEBUG({
9090     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9091       assert(InVals[i].getNode() &&
9092              "LowerFormalArguments emitted a null value!");
9093       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9094              "LowerFormalArguments emitted a value with the wrong type!");
9095     }
9096   });
9097 
9098   // Update the DAG with the new chain value resulting from argument lowering.
9099   DAG.setRoot(NewRoot);
9100 
9101   // Set up the argument values.
9102   unsigned i = 0;
9103   if (!FuncInfo->CanLowerReturn) {
9104     // Create a virtual register for the sret pointer, and put in a copy
9105     // from the sret argument into it.
9106     SmallVector<EVT, 1> ValueVTs;
9107     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9108                     F.getReturnType()->getPointerTo(
9109                         DAG.getDataLayout().getAllocaAddrSpace()),
9110                     ValueVTs);
9111     MVT VT = ValueVTs[0].getSimpleVT();
9112     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9113     Optional<ISD::NodeType> AssertOp = None;
9114     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9115                                         nullptr, F.getCallingConv(), AssertOp);
9116 
9117     MachineFunction& MF = SDB->DAG.getMachineFunction();
9118     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9119     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9120     FuncInfo->DemoteRegister = SRetReg;
9121     NewRoot =
9122         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9123     DAG.setRoot(NewRoot);
9124 
9125     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9126     ++i;
9127   }
9128 
9129   SmallVector<SDValue, 4> Chains;
9130   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9131   for (const Argument &Arg : F.args()) {
9132     SmallVector<SDValue, 4> ArgValues;
9133     SmallVector<EVT, 4> ValueVTs;
9134     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9135     unsigned NumValues = ValueVTs.size();
9136     if (NumValues == 0)
9137       continue;
9138 
9139     bool ArgHasUses = !Arg.use_empty();
9140 
9141     // Elide the copying store if the target loaded this argument from a
9142     // suitable fixed stack object.
9143     if (Ins[i].Flags.isCopyElisionCandidate()) {
9144       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9145                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9146                              InVals[i], ArgHasUses);
9147     }
9148 
9149     // If this argument is unused then remember its value. It is used to generate
9150     // debugging information.
9151     bool isSwiftErrorArg =
9152         TLI->supportSwiftError() &&
9153         Arg.hasAttribute(Attribute::SwiftError);
9154     if (!ArgHasUses && !isSwiftErrorArg) {
9155       SDB->setUnusedArgValue(&Arg, InVals[i]);
9156 
9157       // Also remember any frame index for use in FastISel.
9158       if (FrameIndexSDNode *FI =
9159           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9160         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9161     }
9162 
9163     for (unsigned Val = 0; Val != NumValues; ++Val) {
9164       EVT VT = ValueVTs[Val];
9165       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9166                                                       F.getCallingConv(), VT);
9167       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9168           *CurDAG->getContext(), F.getCallingConv(), VT);
9169 
9170       // Even an apparant 'unused' swifterror argument needs to be returned. So
9171       // we do generate a copy for it that can be used on return from the
9172       // function.
9173       if (ArgHasUses || isSwiftErrorArg) {
9174         Optional<ISD::NodeType> AssertOp;
9175         if (Arg.hasAttribute(Attribute::SExt))
9176           AssertOp = ISD::AssertSext;
9177         else if (Arg.hasAttribute(Attribute::ZExt))
9178           AssertOp = ISD::AssertZext;
9179 
9180         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9181                                              PartVT, VT, nullptr,
9182                                              F.getCallingConv(), AssertOp));
9183       }
9184 
9185       i += NumParts;
9186     }
9187 
9188     // We don't need to do anything else for unused arguments.
9189     if (ArgValues.empty())
9190       continue;
9191 
9192     // Note down frame index.
9193     if (FrameIndexSDNode *FI =
9194         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9195       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9196 
9197     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9198                                      SDB->getCurSDLoc());
9199 
9200     SDB->setValue(&Arg, Res);
9201     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9202       // We want to associate the argument with the frame index, among
9203       // involved operands, that correspond to the lowest address. The
9204       // getCopyFromParts function, called earlier, is swapping the order of
9205       // the operands to BUILD_PAIR depending on endianness. The result of
9206       // that swapping is that the least significant bits of the argument will
9207       // be in the first operand of the BUILD_PAIR node, and the most
9208       // significant bits will be in the second operand.
9209       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9210       if (LoadSDNode *LNode =
9211           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9212         if (FrameIndexSDNode *FI =
9213             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9214           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9215     }
9216 
9217     // Update the SwiftErrorVRegDefMap.
9218     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9219       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9220       if (TargetRegisterInfo::isVirtualRegister(Reg))
9221         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9222                                            FuncInfo->SwiftErrorArg, Reg);
9223     }
9224 
9225     // If this argument is live outside of the entry block, insert a copy from
9226     // wherever we got it to the vreg that other BB's will reference it as.
9227     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9228       // If we can, though, try to skip creating an unnecessary vreg.
9229       // FIXME: This isn't very clean... it would be nice to make this more
9230       // general.  It's also subtly incompatible with the hacks FastISel
9231       // uses with vregs.
9232       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9233       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9234         FuncInfo->ValueMap[&Arg] = Reg;
9235         continue;
9236       }
9237     }
9238     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9239       FuncInfo->InitializeRegForValue(&Arg);
9240       SDB->CopyToExportRegsIfNeeded(&Arg);
9241     }
9242   }
9243 
9244   if (!Chains.empty()) {
9245     Chains.push_back(NewRoot);
9246     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9247   }
9248 
9249   DAG.setRoot(NewRoot);
9250 
9251   assert(i == InVals.size() && "Argument register count mismatch!");
9252 
9253   // If any argument copy elisions occurred and we have debug info, update the
9254   // stale frame indices used in the dbg.declare variable info table.
9255   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9256   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9257     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9258       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9259       if (I != ArgCopyElisionFrameIndexMap.end())
9260         VI.Slot = I->second;
9261     }
9262   }
9263 
9264   // Finally, if the target has anything special to do, allow it to do so.
9265   EmitFunctionEntryCode();
9266 }
9267 
9268 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9269 /// ensure constants are generated when needed.  Remember the virtual registers
9270 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9271 /// directly add them, because expansion might result in multiple MBB's for one
9272 /// BB.  As such, the start of the BB might correspond to a different MBB than
9273 /// the end.
9274 void
9275 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9276   const Instruction *TI = LLVMBB->getTerminator();
9277 
9278   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9279 
9280   // Check PHI nodes in successors that expect a value to be available from this
9281   // block.
9282   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9283     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9284     if (!isa<PHINode>(SuccBB->begin())) continue;
9285     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9286 
9287     // If this terminator has multiple identical successors (common for
9288     // switches), only handle each succ once.
9289     if (!SuccsHandled.insert(SuccMBB).second)
9290       continue;
9291 
9292     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9293 
9294     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9295     // nodes and Machine PHI nodes, but the incoming operands have not been
9296     // emitted yet.
9297     for (const PHINode &PN : SuccBB->phis()) {
9298       // Ignore dead phi's.
9299       if (PN.use_empty())
9300         continue;
9301 
9302       // Skip empty types
9303       if (PN.getType()->isEmptyTy())
9304         continue;
9305 
9306       unsigned Reg;
9307       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9308 
9309       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9310         unsigned &RegOut = ConstantsOut[C];
9311         if (RegOut == 0) {
9312           RegOut = FuncInfo.CreateRegs(C->getType());
9313           CopyValueToVirtualRegister(C, RegOut);
9314         }
9315         Reg = RegOut;
9316       } else {
9317         DenseMap<const Value *, unsigned>::iterator I =
9318           FuncInfo.ValueMap.find(PHIOp);
9319         if (I != FuncInfo.ValueMap.end())
9320           Reg = I->second;
9321         else {
9322           assert(isa<AllocaInst>(PHIOp) &&
9323                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9324                  "Didn't codegen value into a register!??");
9325           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9326           CopyValueToVirtualRegister(PHIOp, Reg);
9327         }
9328       }
9329 
9330       // Remember that this register needs to added to the machine PHI node as
9331       // the input for this MBB.
9332       SmallVector<EVT, 4> ValueVTs;
9333       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9334       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9335       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9336         EVT VT = ValueVTs[vti];
9337         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9338         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9339           FuncInfo.PHINodesToUpdate.push_back(
9340               std::make_pair(&*MBBI++, Reg + i));
9341         Reg += NumRegisters;
9342       }
9343     }
9344   }
9345 
9346   ConstantsOut.clear();
9347 }
9348 
9349 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9350 /// is 0.
9351 MachineBasicBlock *
9352 SelectionDAGBuilder::StackProtectorDescriptor::
9353 AddSuccessorMBB(const BasicBlock *BB,
9354                 MachineBasicBlock *ParentMBB,
9355                 bool IsLikely,
9356                 MachineBasicBlock *SuccMBB) {
9357   // If SuccBB has not been created yet, create it.
9358   if (!SuccMBB) {
9359     MachineFunction *MF = ParentMBB->getParent();
9360     MachineFunction::iterator BBI(ParentMBB);
9361     SuccMBB = MF->CreateMachineBasicBlock(BB);
9362     MF->insert(++BBI, SuccMBB);
9363   }
9364   // Add it as a successor of ParentMBB.
9365   ParentMBB->addSuccessor(
9366       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9367   return SuccMBB;
9368 }
9369 
9370 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9371   MachineFunction::iterator I(MBB);
9372   if (++I == FuncInfo.MF->end())
9373     return nullptr;
9374   return &*I;
9375 }
9376 
9377 /// During lowering new call nodes can be created (such as memset, etc.).
9378 /// Those will become new roots of the current DAG, but complications arise
9379 /// when they are tail calls. In such cases, the call lowering will update
9380 /// the root, but the builder still needs to know that a tail call has been
9381 /// lowered in order to avoid generating an additional return.
9382 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9383   // If the node is null, we do have a tail call.
9384   if (MaybeTC.getNode() != nullptr)
9385     DAG.setRoot(MaybeTC);
9386   else
9387     HasTailCall = true;
9388 }
9389 
9390 uint64_t
9391 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9392                                        unsigned First, unsigned Last) const {
9393   assert(Last >= First);
9394   const APInt &LowCase = Clusters[First].Low->getValue();
9395   const APInt &HighCase = Clusters[Last].High->getValue();
9396   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9397 
9398   // FIXME: A range of consecutive cases has 100% density, but only requires one
9399   // comparison to lower. We should discriminate against such consecutive ranges
9400   // in jump tables.
9401 
9402   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9403 }
9404 
9405 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9406     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9407     unsigned Last) const {
9408   assert(Last >= First);
9409   assert(TotalCases[Last] >= TotalCases[First]);
9410   uint64_t NumCases =
9411       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9412   return NumCases;
9413 }
9414 
9415 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9416                                          unsigned First, unsigned Last,
9417                                          const SwitchInst *SI,
9418                                          MachineBasicBlock *DefaultMBB,
9419                                          CaseCluster &JTCluster) {
9420   assert(First <= Last);
9421 
9422   auto Prob = BranchProbability::getZero();
9423   unsigned NumCmps = 0;
9424   std::vector<MachineBasicBlock*> Table;
9425   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9426 
9427   // Initialize probabilities in JTProbs.
9428   for (unsigned I = First; I <= Last; ++I)
9429     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9430 
9431   for (unsigned I = First; I <= Last; ++I) {
9432     assert(Clusters[I].Kind == CC_Range);
9433     Prob += Clusters[I].Prob;
9434     const APInt &Low = Clusters[I].Low->getValue();
9435     const APInt &High = Clusters[I].High->getValue();
9436     NumCmps += (Low == High) ? 1 : 2;
9437     if (I != First) {
9438       // Fill the gap between this and the previous cluster.
9439       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9440       assert(PreviousHigh.slt(Low));
9441       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9442       for (uint64_t J = 0; J < Gap; J++)
9443         Table.push_back(DefaultMBB);
9444     }
9445     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9446     for (uint64_t J = 0; J < ClusterSize; ++J)
9447       Table.push_back(Clusters[I].MBB);
9448     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9449   }
9450 
9451   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9452   unsigned NumDests = JTProbs.size();
9453   if (TLI.isSuitableForBitTests(
9454           NumDests, NumCmps, Clusters[First].Low->getValue(),
9455           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9456     // Clusters[First..Last] should be lowered as bit tests instead.
9457     return false;
9458   }
9459 
9460   // Create the MBB that will load from and jump through the table.
9461   // Note: We create it here, but it's not inserted into the function yet.
9462   MachineFunction *CurMF = FuncInfo.MF;
9463   MachineBasicBlock *JumpTableMBB =
9464       CurMF->CreateMachineBasicBlock(SI->getParent());
9465 
9466   // Add successors. Note: use table order for determinism.
9467   SmallPtrSet<MachineBasicBlock *, 8> Done;
9468   for (MachineBasicBlock *Succ : Table) {
9469     if (Done.count(Succ))
9470       continue;
9471     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9472     Done.insert(Succ);
9473   }
9474   JumpTableMBB->normalizeSuccProbs();
9475 
9476   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9477                      ->createJumpTableIndex(Table);
9478 
9479   // Set up the jump table info.
9480   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9481   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9482                       Clusters[Last].High->getValue(), SI->getCondition(),
9483                       nullptr, false);
9484   JTCases.emplace_back(std::move(JTH), std::move(JT));
9485 
9486   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9487                                      JTCases.size() - 1, Prob);
9488   return true;
9489 }
9490 
9491 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9492                                          const SwitchInst *SI,
9493                                          MachineBasicBlock *DefaultMBB) {
9494 #ifndef NDEBUG
9495   // Clusters must be non-empty, sorted, and only contain Range clusters.
9496   assert(!Clusters.empty());
9497   for (CaseCluster &C : Clusters)
9498     assert(C.Kind == CC_Range);
9499   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9500     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9501 #endif
9502 
9503   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9504   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9505     return;
9506 
9507   const int64_t N = Clusters.size();
9508   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9509   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9510 
9511   if (N < 2 || N < MinJumpTableEntries)
9512     return;
9513 
9514   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9515   SmallVector<unsigned, 8> TotalCases(N);
9516   for (unsigned i = 0; i < N; ++i) {
9517     const APInt &Hi = Clusters[i].High->getValue();
9518     const APInt &Lo = Clusters[i].Low->getValue();
9519     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9520     if (i != 0)
9521       TotalCases[i] += TotalCases[i - 1];
9522   }
9523 
9524   // Cheap case: the whole range may be suitable for jump table.
9525   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9526   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9527   assert(NumCases < UINT64_MAX / 100);
9528   assert(Range >= NumCases);
9529   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9530     CaseCluster JTCluster;
9531     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9532       Clusters[0] = JTCluster;
9533       Clusters.resize(1);
9534       return;
9535     }
9536   }
9537 
9538   // The algorithm below is not suitable for -O0.
9539   if (TM.getOptLevel() == CodeGenOpt::None)
9540     return;
9541 
9542   // Split Clusters into minimum number of dense partitions. The algorithm uses
9543   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9544   // for the Case Statement'" (1994), but builds the MinPartitions array in
9545   // reverse order to make it easier to reconstruct the partitions in ascending
9546   // order. In the choice between two optimal partitionings, it picks the one
9547   // which yields more jump tables.
9548 
9549   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9550   SmallVector<unsigned, 8> MinPartitions(N);
9551   // LastElement[i] is the last element of the partition starting at i.
9552   SmallVector<unsigned, 8> LastElement(N);
9553   // PartitionsScore[i] is used to break ties when choosing between two
9554   // partitionings resulting in the same number of partitions.
9555   SmallVector<unsigned, 8> PartitionsScore(N);
9556   // For PartitionsScore, a small number of comparisons is considered as good as
9557   // a jump table and a single comparison is considered better than a jump
9558   // table.
9559   enum PartitionScores : unsigned {
9560     NoTable = 0,
9561     Table = 1,
9562     FewCases = 1,
9563     SingleCase = 2
9564   };
9565 
9566   // Base case: There is only one way to partition Clusters[N-1].
9567   MinPartitions[N - 1] = 1;
9568   LastElement[N - 1] = N - 1;
9569   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9570 
9571   // Note: loop indexes are signed to avoid underflow.
9572   for (int64_t i = N - 2; i >= 0; i--) {
9573     // Find optimal partitioning of Clusters[i..N-1].
9574     // Baseline: Put Clusters[i] into a partition on its own.
9575     MinPartitions[i] = MinPartitions[i + 1] + 1;
9576     LastElement[i] = i;
9577     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9578 
9579     // Search for a solution that results in fewer partitions.
9580     for (int64_t j = N - 1; j > i; j--) {
9581       // Try building a partition from Clusters[i..j].
9582       uint64_t Range = getJumpTableRange(Clusters, i, j);
9583       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9584       assert(NumCases < UINT64_MAX / 100);
9585       assert(Range >= NumCases);
9586       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9587         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9588         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9589         int64_t NumEntries = j - i + 1;
9590 
9591         if (NumEntries == 1)
9592           Score += PartitionScores::SingleCase;
9593         else if (NumEntries <= SmallNumberOfEntries)
9594           Score += PartitionScores::FewCases;
9595         else if (NumEntries >= MinJumpTableEntries)
9596           Score += PartitionScores::Table;
9597 
9598         // If this leads to fewer partitions, or to the same number of
9599         // partitions with better score, it is a better partitioning.
9600         if (NumPartitions < MinPartitions[i] ||
9601             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9602           MinPartitions[i] = NumPartitions;
9603           LastElement[i] = j;
9604           PartitionsScore[i] = Score;
9605         }
9606       }
9607     }
9608   }
9609 
9610   // Iterate over the partitions, replacing some with jump tables in-place.
9611   unsigned DstIndex = 0;
9612   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9613     Last = LastElement[First];
9614     assert(Last >= First);
9615     assert(DstIndex <= First);
9616     unsigned NumClusters = Last - First + 1;
9617 
9618     CaseCluster JTCluster;
9619     if (NumClusters >= MinJumpTableEntries &&
9620         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9621       Clusters[DstIndex++] = JTCluster;
9622     } else {
9623       for (unsigned I = First; I <= Last; ++I)
9624         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9625     }
9626   }
9627   Clusters.resize(DstIndex);
9628 }
9629 
9630 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9631                                         unsigned First, unsigned Last,
9632                                         const SwitchInst *SI,
9633                                         CaseCluster &BTCluster) {
9634   assert(First <= Last);
9635   if (First == Last)
9636     return false;
9637 
9638   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9639   unsigned NumCmps = 0;
9640   for (int64_t I = First; I <= Last; ++I) {
9641     assert(Clusters[I].Kind == CC_Range);
9642     Dests.set(Clusters[I].MBB->getNumber());
9643     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9644   }
9645   unsigned NumDests = Dests.count();
9646 
9647   APInt Low = Clusters[First].Low->getValue();
9648   APInt High = Clusters[Last].High->getValue();
9649   assert(Low.slt(High));
9650 
9651   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9652   const DataLayout &DL = DAG.getDataLayout();
9653   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9654     return false;
9655 
9656   APInt LowBound;
9657   APInt CmpRange;
9658 
9659   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9660   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9661          "Case range must fit in bit mask!");
9662 
9663   // Check if the clusters cover a contiguous range such that no value in the
9664   // range will jump to the default statement.
9665   bool ContiguousRange = true;
9666   for (int64_t I = First + 1; I <= Last; ++I) {
9667     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9668       ContiguousRange = false;
9669       break;
9670     }
9671   }
9672 
9673   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9674     // Optimize the case where all the case values fit in a word without having
9675     // to subtract minValue. In this case, we can optimize away the subtraction.
9676     LowBound = APInt::getNullValue(Low.getBitWidth());
9677     CmpRange = High;
9678     ContiguousRange = false;
9679   } else {
9680     LowBound = Low;
9681     CmpRange = High - Low;
9682   }
9683 
9684   CaseBitsVector CBV;
9685   auto TotalProb = BranchProbability::getZero();
9686   for (unsigned i = First; i <= Last; ++i) {
9687     // Find the CaseBits for this destination.
9688     unsigned j;
9689     for (j = 0; j < CBV.size(); ++j)
9690       if (CBV[j].BB == Clusters[i].MBB)
9691         break;
9692     if (j == CBV.size())
9693       CBV.push_back(
9694           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9695     CaseBits *CB = &CBV[j];
9696 
9697     // Update Mask, Bits and ExtraProb.
9698     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9699     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9700     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9701     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9702     CB->Bits += Hi - Lo + 1;
9703     CB->ExtraProb += Clusters[i].Prob;
9704     TotalProb += Clusters[i].Prob;
9705   }
9706 
9707   BitTestInfo BTI;
9708   llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
9709     // Sort by probability first, number of bits second, bit mask third.
9710     if (a.ExtraProb != b.ExtraProb)
9711       return a.ExtraProb > b.ExtraProb;
9712     if (a.Bits != b.Bits)
9713       return a.Bits > b.Bits;
9714     return a.Mask < b.Mask;
9715   });
9716 
9717   for (auto &CB : CBV) {
9718     MachineBasicBlock *BitTestBB =
9719         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9720     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9721   }
9722   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9723                             SI->getCondition(), -1U, MVT::Other, false,
9724                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9725                             TotalProb);
9726 
9727   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9728                                     BitTestCases.size() - 1, TotalProb);
9729   return true;
9730 }
9731 
9732 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9733                                               const SwitchInst *SI) {
9734 // Partition Clusters into as few subsets as possible, where each subset has a
9735 // range that fits in a machine word and has <= 3 unique destinations.
9736 
9737 #ifndef NDEBUG
9738   // Clusters must be sorted and contain Range or JumpTable clusters.
9739   assert(!Clusters.empty());
9740   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9741   for (const CaseCluster &C : Clusters)
9742     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9743   for (unsigned i = 1; i < Clusters.size(); ++i)
9744     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9745 #endif
9746 
9747   // The algorithm below is not suitable for -O0.
9748   if (TM.getOptLevel() == CodeGenOpt::None)
9749     return;
9750 
9751   // If target does not have legal shift left, do not emit bit tests at all.
9752   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9753   const DataLayout &DL = DAG.getDataLayout();
9754 
9755   EVT PTy = TLI.getPointerTy(DL);
9756   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9757     return;
9758 
9759   int BitWidth = PTy.getSizeInBits();
9760   const int64_t N = Clusters.size();
9761 
9762   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9763   SmallVector<unsigned, 8> MinPartitions(N);
9764   // LastElement[i] is the last element of the partition starting at i.
9765   SmallVector<unsigned, 8> LastElement(N);
9766 
9767   // FIXME: This might not be the best algorithm for finding bit test clusters.
9768 
9769   // Base case: There is only one way to partition Clusters[N-1].
9770   MinPartitions[N - 1] = 1;
9771   LastElement[N - 1] = N - 1;
9772 
9773   // Note: loop indexes are signed to avoid underflow.
9774   for (int64_t i = N - 2; i >= 0; --i) {
9775     // Find optimal partitioning of Clusters[i..N-1].
9776     // Baseline: Put Clusters[i] into a partition on its own.
9777     MinPartitions[i] = MinPartitions[i + 1] + 1;
9778     LastElement[i] = i;
9779 
9780     // Search for a solution that results in fewer partitions.
9781     // Note: the search is limited by BitWidth, reducing time complexity.
9782     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9783       // Try building a partition from Clusters[i..j].
9784 
9785       // Check the range.
9786       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9787                                Clusters[j].High->getValue(), DL))
9788         continue;
9789 
9790       // Check nbr of destinations and cluster types.
9791       // FIXME: This works, but doesn't seem very efficient.
9792       bool RangesOnly = true;
9793       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9794       for (int64_t k = i; k <= j; k++) {
9795         if (Clusters[k].Kind != CC_Range) {
9796           RangesOnly = false;
9797           break;
9798         }
9799         Dests.set(Clusters[k].MBB->getNumber());
9800       }
9801       if (!RangesOnly || Dests.count() > 3)
9802         break;
9803 
9804       // Check if it's a better partition.
9805       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9806       if (NumPartitions < MinPartitions[i]) {
9807         // Found a better partition.
9808         MinPartitions[i] = NumPartitions;
9809         LastElement[i] = j;
9810       }
9811     }
9812   }
9813 
9814   // Iterate over the partitions, replacing with bit-test clusters in-place.
9815   unsigned DstIndex = 0;
9816   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9817     Last = LastElement[First];
9818     assert(First <= Last);
9819     assert(DstIndex <= First);
9820 
9821     CaseCluster BitTestCluster;
9822     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
9823       Clusters[DstIndex++] = BitTestCluster;
9824     } else {
9825       size_t NumClusters = Last - First + 1;
9826       std::memmove(&Clusters[DstIndex], &Clusters[First],
9827                    sizeof(Clusters[0]) * NumClusters);
9828       DstIndex += NumClusters;
9829     }
9830   }
9831   Clusters.resize(DstIndex);
9832 }
9833 
9834 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9835                                         MachineBasicBlock *SwitchMBB,
9836                                         MachineBasicBlock *DefaultMBB) {
9837   MachineFunction *CurMF = FuncInfo.MF;
9838   MachineBasicBlock *NextMBB = nullptr;
9839   MachineFunction::iterator BBI(W.MBB);
9840   if (++BBI != FuncInfo.MF->end())
9841     NextMBB = &*BBI;
9842 
9843   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9844 
9845   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9846 
9847   if (Size == 2 && W.MBB == SwitchMBB) {
9848     // If any two of the cases has the same destination, and if one value
9849     // is the same as the other, but has one bit unset that the other has set,
9850     // use bit manipulation to do two compares at once.  For example:
9851     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9852     // TODO: This could be extended to merge any 2 cases in switches with 3
9853     // cases.
9854     // TODO: Handle cases where W.CaseBB != SwitchBB.
9855     CaseCluster &Small = *W.FirstCluster;
9856     CaseCluster &Big = *W.LastCluster;
9857 
9858     if (Small.Low == Small.High && Big.Low == Big.High &&
9859         Small.MBB == Big.MBB) {
9860       const APInt &SmallValue = Small.Low->getValue();
9861       const APInt &BigValue = Big.Low->getValue();
9862 
9863       // Check that there is only one bit different.
9864       APInt CommonBit = BigValue ^ SmallValue;
9865       if (CommonBit.isPowerOf2()) {
9866         SDValue CondLHS = getValue(Cond);
9867         EVT VT = CondLHS.getValueType();
9868         SDLoc DL = getCurSDLoc();
9869 
9870         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9871                                  DAG.getConstant(CommonBit, DL, VT));
9872         SDValue Cond = DAG.getSetCC(
9873             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9874             ISD::SETEQ);
9875 
9876         // Update successor info.
9877         // Both Small and Big will jump to Small.BB, so we sum up the
9878         // probabilities.
9879         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9880         if (BPI)
9881           addSuccessorWithProb(
9882               SwitchMBB, DefaultMBB,
9883               // The default destination is the first successor in IR.
9884               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9885         else
9886           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9887 
9888         // Insert the true branch.
9889         SDValue BrCond =
9890             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9891                         DAG.getBasicBlock(Small.MBB));
9892         // Insert the false branch.
9893         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9894                              DAG.getBasicBlock(DefaultMBB));
9895 
9896         DAG.setRoot(BrCond);
9897         return;
9898       }
9899     }
9900   }
9901 
9902   if (TM.getOptLevel() != CodeGenOpt::None) {
9903     // Here, we order cases by probability so the most likely case will be
9904     // checked first. However, two clusters can have the same probability in
9905     // which case their relative ordering is non-deterministic. So we use Low
9906     // as a tie-breaker as clusters are guaranteed to never overlap.
9907     llvm::sort(W.FirstCluster, W.LastCluster + 1,
9908                [](const CaseCluster &a, const CaseCluster &b) {
9909       return a.Prob != b.Prob ?
9910              a.Prob > b.Prob :
9911              a.Low->getValue().slt(b.Low->getValue());
9912     });
9913 
9914     // Rearrange the case blocks so that the last one falls through if possible
9915     // without changing the order of probabilities.
9916     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9917       --I;
9918       if (I->Prob > W.LastCluster->Prob)
9919         break;
9920       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9921         std::swap(*I, *W.LastCluster);
9922         break;
9923       }
9924     }
9925   }
9926 
9927   // Compute total probability.
9928   BranchProbability DefaultProb = W.DefaultProb;
9929   BranchProbability UnhandledProbs = DefaultProb;
9930   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
9931     UnhandledProbs += I->Prob;
9932 
9933   MachineBasicBlock *CurMBB = W.MBB;
9934   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
9935     MachineBasicBlock *Fallthrough;
9936     if (I == W.LastCluster) {
9937       // For the last cluster, fall through to the default destination.
9938       Fallthrough = DefaultMBB;
9939     } else {
9940       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
9941       CurMF->insert(BBI, Fallthrough);
9942       // Put Cond in a virtual register to make it available from the new blocks.
9943       ExportFromCurrentBlock(Cond);
9944     }
9945     UnhandledProbs -= I->Prob;
9946 
9947     switch (I->Kind) {
9948       case CC_JumpTable: {
9949         // FIXME: Optimize away range check based on pivot comparisons.
9950         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
9951         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
9952 
9953         // The jump block hasn't been inserted yet; insert it here.
9954         MachineBasicBlock *JumpMBB = JT->MBB;
9955         CurMF->insert(BBI, JumpMBB);
9956 
9957         auto JumpProb = I->Prob;
9958         auto FallthroughProb = UnhandledProbs;
9959 
9960         // If the default statement is a target of the jump table, we evenly
9961         // distribute the default probability to successors of CurMBB. Also
9962         // update the probability on the edge from JumpMBB to Fallthrough.
9963         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
9964                                               SE = JumpMBB->succ_end();
9965              SI != SE; ++SI) {
9966           if (*SI == DefaultMBB) {
9967             JumpProb += DefaultProb / 2;
9968             FallthroughProb -= DefaultProb / 2;
9969             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
9970             JumpMBB->normalizeSuccProbs();
9971             break;
9972           }
9973         }
9974 
9975         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
9976         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
9977         CurMBB->normalizeSuccProbs();
9978 
9979         // The jump table header will be inserted in our current block, do the
9980         // range check, and fall through to our fallthrough block.
9981         JTH->HeaderBB = CurMBB;
9982         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
9983 
9984         // If we're in the right place, emit the jump table header right now.
9985         if (CurMBB == SwitchMBB) {
9986           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
9987           JTH->Emitted = true;
9988         }
9989         break;
9990       }
9991       case CC_BitTests: {
9992         // FIXME: Optimize away range check based on pivot comparisons.
9993         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
9994 
9995         // The bit test blocks haven't been inserted yet; insert them here.
9996         for (BitTestCase &BTC : BTB->Cases)
9997           CurMF->insert(BBI, BTC.ThisBB);
9998 
9999         // Fill in fields of the BitTestBlock.
10000         BTB->Parent = CurMBB;
10001         BTB->Default = Fallthrough;
10002 
10003         BTB->DefaultProb = UnhandledProbs;
10004         // If the cases in bit test don't form a contiguous range, we evenly
10005         // distribute the probability on the edge to Fallthrough to two
10006         // successors of CurMBB.
10007         if (!BTB->ContiguousRange) {
10008           BTB->Prob += DefaultProb / 2;
10009           BTB->DefaultProb -= DefaultProb / 2;
10010         }
10011 
10012         // If we're in the right place, emit the bit test header right now.
10013         if (CurMBB == SwitchMBB) {
10014           visitBitTestHeader(*BTB, SwitchMBB);
10015           BTB->Emitted = true;
10016         }
10017         break;
10018       }
10019       case CC_Range: {
10020         const Value *RHS, *LHS, *MHS;
10021         ISD::CondCode CC;
10022         if (I->Low == I->High) {
10023           // Check Cond == I->Low.
10024           CC = ISD::SETEQ;
10025           LHS = Cond;
10026           RHS=I->Low;
10027           MHS = nullptr;
10028         } else {
10029           // Check I->Low <= Cond <= I->High.
10030           CC = ISD::SETLE;
10031           LHS = I->Low;
10032           MHS = Cond;
10033           RHS = I->High;
10034         }
10035 
10036         // The false probability is the sum of all unhandled cases.
10037         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10038                      getCurSDLoc(), I->Prob, UnhandledProbs);
10039 
10040         if (CurMBB == SwitchMBB)
10041           visitSwitchCase(CB, SwitchMBB);
10042         else
10043           SwitchCases.push_back(CB);
10044 
10045         break;
10046       }
10047     }
10048     CurMBB = Fallthrough;
10049   }
10050 }
10051 
10052 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10053                                               CaseClusterIt First,
10054                                               CaseClusterIt Last) {
10055   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10056     if (X.Prob != CC.Prob)
10057       return X.Prob > CC.Prob;
10058 
10059     // Ties are broken by comparing the case value.
10060     return X.Low->getValue().slt(CC.Low->getValue());
10061   });
10062 }
10063 
10064 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10065                                         const SwitchWorkListItem &W,
10066                                         Value *Cond,
10067                                         MachineBasicBlock *SwitchMBB) {
10068   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10069          "Clusters not sorted?");
10070 
10071   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10072 
10073   // Balance the tree based on branch probabilities to create a near-optimal (in
10074   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10075   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10076   CaseClusterIt LastLeft = W.FirstCluster;
10077   CaseClusterIt FirstRight = W.LastCluster;
10078   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10079   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10080 
10081   // Move LastLeft and FirstRight towards each other from opposite directions to
10082   // find a partitioning of the clusters which balances the probability on both
10083   // sides. If LeftProb and RightProb are equal, alternate which side is
10084   // taken to ensure 0-probability nodes are distributed evenly.
10085   unsigned I = 0;
10086   while (LastLeft + 1 < FirstRight) {
10087     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10088       LeftProb += (++LastLeft)->Prob;
10089     else
10090       RightProb += (--FirstRight)->Prob;
10091     I++;
10092   }
10093 
10094   while (true) {
10095     // Our binary search tree differs from a typical BST in that ours can have up
10096     // to three values in each leaf. The pivot selection above doesn't take that
10097     // into account, which means the tree might require more nodes and be less
10098     // efficient. We compensate for this here.
10099 
10100     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10101     unsigned NumRight = W.LastCluster - FirstRight + 1;
10102 
10103     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10104       // If one side has less than 3 clusters, and the other has more than 3,
10105       // consider taking a cluster from the other side.
10106 
10107       if (NumLeft < NumRight) {
10108         // Consider moving the first cluster on the right to the left side.
10109         CaseCluster &CC = *FirstRight;
10110         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10111         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10112         if (LeftSideRank <= RightSideRank) {
10113           // Moving the cluster to the left does not demote it.
10114           ++LastLeft;
10115           ++FirstRight;
10116           continue;
10117         }
10118       } else {
10119         assert(NumRight < NumLeft);
10120         // Consider moving the last element on the left to the right side.
10121         CaseCluster &CC = *LastLeft;
10122         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10123         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10124         if (RightSideRank <= LeftSideRank) {
10125           // Moving the cluster to the right does not demot it.
10126           --LastLeft;
10127           --FirstRight;
10128           continue;
10129         }
10130       }
10131     }
10132     break;
10133   }
10134 
10135   assert(LastLeft + 1 == FirstRight);
10136   assert(LastLeft >= W.FirstCluster);
10137   assert(FirstRight <= W.LastCluster);
10138 
10139   // Use the first element on the right as pivot since we will make less-than
10140   // comparisons against it.
10141   CaseClusterIt PivotCluster = FirstRight;
10142   assert(PivotCluster > W.FirstCluster);
10143   assert(PivotCluster <= W.LastCluster);
10144 
10145   CaseClusterIt FirstLeft = W.FirstCluster;
10146   CaseClusterIt LastRight = W.LastCluster;
10147 
10148   const ConstantInt *Pivot = PivotCluster->Low;
10149 
10150   // New blocks will be inserted immediately after the current one.
10151   MachineFunction::iterator BBI(W.MBB);
10152   ++BBI;
10153 
10154   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10155   // we can branch to its destination directly if it's squeezed exactly in
10156   // between the known lower bound and Pivot - 1.
10157   MachineBasicBlock *LeftMBB;
10158   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10159       FirstLeft->Low == W.GE &&
10160       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10161     LeftMBB = FirstLeft->MBB;
10162   } else {
10163     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10164     FuncInfo.MF->insert(BBI, LeftMBB);
10165     WorkList.push_back(
10166         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10167     // Put Cond in a virtual register to make it available from the new blocks.
10168     ExportFromCurrentBlock(Cond);
10169   }
10170 
10171   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10172   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10173   // directly if RHS.High equals the current upper bound.
10174   MachineBasicBlock *RightMBB;
10175   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10176       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10177     RightMBB = FirstRight->MBB;
10178   } else {
10179     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10180     FuncInfo.MF->insert(BBI, RightMBB);
10181     WorkList.push_back(
10182         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10183     // Put Cond in a virtual register to make it available from the new blocks.
10184     ExportFromCurrentBlock(Cond);
10185   }
10186 
10187   // Create the CaseBlock record that will be used to lower the branch.
10188   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10189                getCurSDLoc(), LeftProb, RightProb);
10190 
10191   if (W.MBB == SwitchMBB)
10192     visitSwitchCase(CB, SwitchMBB);
10193   else
10194     SwitchCases.push_back(CB);
10195 }
10196 
10197 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10198 // from the swith statement.
10199 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10200                                             BranchProbability PeeledCaseProb) {
10201   if (PeeledCaseProb == BranchProbability::getOne())
10202     return BranchProbability::getZero();
10203   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10204 
10205   uint32_t Numerator = CaseProb.getNumerator();
10206   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10207   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10208 }
10209 
10210 // Try to peel the top probability case if it exceeds the threshold.
10211 // Return current MachineBasicBlock for the switch statement if the peeling
10212 // does not occur.
10213 // If the peeling is performed, return the newly created MachineBasicBlock
10214 // for the peeled switch statement. Also update Clusters to remove the peeled
10215 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10216 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10217     const SwitchInst &SI, CaseClusterVector &Clusters,
10218     BranchProbability &PeeledCaseProb) {
10219   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10220   // Don't perform if there is only one cluster or optimizing for size.
10221   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10222       TM.getOptLevel() == CodeGenOpt::None ||
10223       SwitchMBB->getParent()->getFunction().optForMinSize())
10224     return SwitchMBB;
10225 
10226   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10227   unsigned PeeledCaseIndex = 0;
10228   bool SwitchPeeled = false;
10229   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10230     CaseCluster &CC = Clusters[Index];
10231     if (CC.Prob < TopCaseProb)
10232       continue;
10233     TopCaseProb = CC.Prob;
10234     PeeledCaseIndex = Index;
10235     SwitchPeeled = true;
10236   }
10237   if (!SwitchPeeled)
10238     return SwitchMBB;
10239 
10240   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10241                     << TopCaseProb << "\n");
10242 
10243   // Record the MBB for the peeled switch statement.
10244   MachineFunction::iterator BBI(SwitchMBB);
10245   ++BBI;
10246   MachineBasicBlock *PeeledSwitchMBB =
10247       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10248   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10249 
10250   ExportFromCurrentBlock(SI.getCondition());
10251   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10252   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10253                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10254   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10255 
10256   Clusters.erase(PeeledCaseIt);
10257   for (CaseCluster &CC : Clusters) {
10258     LLVM_DEBUG(
10259         dbgs() << "Scale the probablity for one cluster, before scaling: "
10260                << CC.Prob << "\n");
10261     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10262     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10263   }
10264   PeeledCaseProb = TopCaseProb;
10265   return PeeledSwitchMBB;
10266 }
10267 
10268 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10269   // Extract cases from the switch.
10270   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10271   CaseClusterVector Clusters;
10272   Clusters.reserve(SI.getNumCases());
10273   for (auto I : SI.cases()) {
10274     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10275     const ConstantInt *CaseVal = I.getCaseValue();
10276     BranchProbability Prob =
10277         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10278             : BranchProbability(1, SI.getNumCases() + 1);
10279     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10280   }
10281 
10282   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10283 
10284   // Cluster adjacent cases with the same destination. We do this at all
10285   // optimization levels because it's cheap to do and will make codegen faster
10286   // if there are many clusters.
10287   sortAndRangeify(Clusters);
10288 
10289   if (TM.getOptLevel() != CodeGenOpt::None) {
10290     // Replace an unreachable default with the most popular destination.
10291     // FIXME: Exploit unreachable default more aggressively.
10292     bool UnreachableDefault =
10293         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10294     if (UnreachableDefault && !Clusters.empty()) {
10295       DenseMap<const BasicBlock *, unsigned> Popularity;
10296       unsigned MaxPop = 0;
10297       const BasicBlock *MaxBB = nullptr;
10298       for (auto I : SI.cases()) {
10299         const BasicBlock *BB = I.getCaseSuccessor();
10300         if (++Popularity[BB] > MaxPop) {
10301           MaxPop = Popularity[BB];
10302           MaxBB = BB;
10303         }
10304       }
10305       // Set new default.
10306       assert(MaxPop > 0 && MaxBB);
10307       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10308 
10309       // Remove cases that were pointing to the destination that is now the
10310       // default.
10311       CaseClusterVector New;
10312       New.reserve(Clusters.size());
10313       for (CaseCluster &CC : Clusters) {
10314         if (CC.MBB != DefaultMBB)
10315           New.push_back(CC);
10316       }
10317       Clusters = std::move(New);
10318     }
10319   }
10320 
10321   // The branch probablity of the peeled case.
10322   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10323   MachineBasicBlock *PeeledSwitchMBB =
10324       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10325 
10326   // If there is only the default destination, jump there directly.
10327   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10328   if (Clusters.empty()) {
10329     assert(PeeledSwitchMBB == SwitchMBB);
10330     SwitchMBB->addSuccessor(DefaultMBB);
10331     if (DefaultMBB != NextBlock(SwitchMBB)) {
10332       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10333                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10334     }
10335     return;
10336   }
10337 
10338   findJumpTables(Clusters, &SI, DefaultMBB);
10339   findBitTestClusters(Clusters, &SI);
10340 
10341   LLVM_DEBUG({
10342     dbgs() << "Case clusters: ";
10343     for (const CaseCluster &C : Clusters) {
10344       if (C.Kind == CC_JumpTable)
10345         dbgs() << "JT:";
10346       if (C.Kind == CC_BitTests)
10347         dbgs() << "BT:";
10348 
10349       C.Low->getValue().print(dbgs(), true);
10350       if (C.Low != C.High) {
10351         dbgs() << '-';
10352         C.High->getValue().print(dbgs(), true);
10353       }
10354       dbgs() << ' ';
10355     }
10356     dbgs() << '\n';
10357   });
10358 
10359   assert(!Clusters.empty());
10360   SwitchWorkList WorkList;
10361   CaseClusterIt First = Clusters.begin();
10362   CaseClusterIt Last = Clusters.end() - 1;
10363   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10364   // Scale the branchprobability for DefaultMBB if the peel occurs and
10365   // DefaultMBB is not replaced.
10366   if (PeeledCaseProb != BranchProbability::getZero() &&
10367       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10368     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10369   WorkList.push_back(
10370       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10371 
10372   while (!WorkList.empty()) {
10373     SwitchWorkListItem W = WorkList.back();
10374     WorkList.pop_back();
10375     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10376 
10377     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10378         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10379       // For optimized builds, lower large range as a balanced binary tree.
10380       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10381       continue;
10382     }
10383 
10384     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10385   }
10386 }
10387