xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision af4eb17223812e193da7d731c23956d319f06f28)
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 "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BranchProbabilityInfo.h"
31 #include "llvm/Analysis/ConstantFolding.h"
32 #include "llvm/Analysis/EHPersonalities.h"
33 #include "llvm/Analysis/Loads.h"
34 #include "llvm/Analysis/MemoryLocation.h"
35 #include "llvm/Analysis/TargetLibraryInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/Analysis/VectorUtils.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/FunctionLoweringInfo.h"
40 #include "llvm/CodeGen/GCMetadata.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineJumpTableInfo.h"
48 #include "llvm/CodeGen/MachineMemOperand.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/MachineValueType.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/Statepoint.h"
92 #include "llvm/IR/Type.h"
93 #include "llvm/IR/User.h"
94 #include "llvm/IR/Value.h"
95 #include "llvm/MC/MCContext.h"
96 #include "llvm/MC/MCSymbol.h"
97 #include "llvm/Support/AtomicOrdering.h"
98 #include "llvm/Support/BranchProbability.h"
99 #include "llvm/Support/Casting.h"
100 #include "llvm/Support/CodeGen.h"
101 #include "llvm/Support/CommandLine.h"
102 #include "llvm/Support/Compiler.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Support/ErrorHandling.h"
105 #include "llvm/Support/MathExtras.h"
106 #include "llvm/Support/raw_ostream.h"
107 #include "llvm/Target/TargetIntrinsicInfo.h"
108 #include "llvm/Target/TargetMachine.h"
109 #include "llvm/Target/TargetOptions.h"
110 #include <algorithm>
111 #include <cassert>
112 #include <cstddef>
113 #include <cstdint>
114 #include <cstring>
115 #include <iterator>
116 #include <limits>
117 #include <numeric>
118 #include <tuple>
119 #include <utility>
120 #include <vector>
121 
122 using namespace llvm;
123 
124 #define DEBUG_TYPE "isel"
125 
126 /// LimitFloatPrecision - Generate low-precision inline sequences for
127 /// some float libcalls (6, 8 or 12 bits).
128 static unsigned LimitFloatPrecision;
129 
130 static cl::opt<unsigned, true>
131     LimitFPPrecision("limit-float-precision",
132                      cl::desc("Generate low-precision inline sequences "
133                               "for some float libcalls"),
134                      cl::location(LimitFloatPrecision), cl::Hidden,
135                      cl::init(0));
136 
137 static cl::opt<unsigned> SwitchPeelThreshold(
138     "switch-peel-threshold", cl::Hidden, cl::init(66),
139     cl::desc("Set the case probability threshold for peeling the case from a "
140              "switch statement. A value greater than 100 will void this "
141              "optimization"));
142 
143 // Limit the width of DAG chains. This is important in general to prevent
144 // DAG-based analysis from blowing up. For example, alias analysis and
145 // load clustering may not complete in reasonable time. It is difficult to
146 // recognize and avoid this situation within each individual analysis, and
147 // future analyses are likely to have the same behavior. Limiting DAG width is
148 // the safe approach and will be especially important with global DAGs.
149 //
150 // MaxParallelChains default is arbitrarily high to avoid affecting
151 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
152 // sequence over this should have been converted to llvm.memcpy by the
153 // frontend. It is easy to induce this behavior with .ll code such as:
154 // %buffer = alloca [4096 x i8]
155 // %data = load [4096 x i8]* %argPtr
156 // store [4096 x i8] %data, [4096 x i8]* %buffer
157 static const unsigned MaxParallelChains = 64;
158 
159 // True if the Value passed requires ABI mangling as it is a parameter to a
160 // function or a return value from a function which is not an intrinsic.
161 static bool isABIRegCopy(const Value *V) {
162   const bool IsRetInst = V && isa<ReturnInst>(V);
163   const bool IsCallInst = V && isa<CallInst>(V);
164   const bool IsInLineAsm =
165       IsCallInst && static_cast<const CallInst *>(V)->isInlineAsm();
166   const bool IsIndirectFunctionCall =
167       IsCallInst && !IsInLineAsm &&
168       !static_cast<const CallInst *>(V)->getCalledFunction();
169   // It is possible that the call instruction is an inline asm statement or an
170   // indirect function call in which case the return value of
171   // getCalledFunction() would be nullptr.
172   const bool IsInstrinsicCall =
173       IsCallInst && !IsInLineAsm && !IsIndirectFunctionCall &&
174       static_cast<const CallInst *>(V)->getCalledFunction()->getIntrinsicID() !=
175           Intrinsic::not_intrinsic;
176 
177   return IsRetInst || (IsCallInst && (!IsInLineAsm && !IsInstrinsicCall));
178 }
179 
180 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
181                                       const SDValue *Parts, unsigned NumParts,
182                                       MVT PartVT, EVT ValueVT, const Value *V,
183                                       bool IsABIRegCopy);
184 
185 /// getCopyFromParts - Create a value that contains the specified legal parts
186 /// combined into the value they represent.  If the parts combine to a type
187 /// larger than ValueVT then AssertOp can be used to specify whether the extra
188 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
189 /// (ISD::AssertSext).
190 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
191                                 const SDValue *Parts, unsigned NumParts,
192                                 MVT PartVT, EVT ValueVT, const Value *V,
193                                 Optional<ISD::NodeType> AssertOp = None,
194                                 bool IsABIRegCopy = false) {
195   if (ValueVT.isVector())
196     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
197                                   PartVT, ValueVT, V, IsABIRegCopy);
198 
199   assert(NumParts > 0 && "No parts to assemble!");
200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
201   SDValue Val = Parts[0];
202 
203   if (NumParts > 1) {
204     // Assemble the value from multiple parts.
205     if (ValueVT.isInteger()) {
206       unsigned PartBits = PartVT.getSizeInBits();
207       unsigned ValueBits = ValueVT.getSizeInBits();
208 
209       // Assemble the power of 2 part.
210       unsigned RoundParts = NumParts & (NumParts - 1) ?
211         1 << Log2_32(NumParts) : NumParts;
212       unsigned RoundBits = PartBits * RoundParts;
213       EVT RoundVT = RoundBits == ValueBits ?
214         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
215       SDValue Lo, Hi;
216 
217       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
218 
219       if (RoundParts > 2) {
220         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
221                               PartVT, HalfVT, V);
222         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
223                               RoundParts / 2, PartVT, HalfVT, V);
224       } else {
225         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
226         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
227       }
228 
229       if (DAG.getDataLayout().isBigEndian())
230         std::swap(Lo, Hi);
231 
232       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
233 
234       if (RoundParts < NumParts) {
235         // Assemble the trailing non-power-of-2 part.
236         unsigned OddParts = NumParts - RoundParts;
237         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
238         Hi = getCopyFromParts(DAG, DL,
239                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
240 
241         // Combine the round and odd parts.
242         Lo = Val;
243         if (DAG.getDataLayout().isBigEndian())
244           std::swap(Lo, Hi);
245         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
246         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
247         Hi =
248             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
249                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
250                                         TLI.getPointerTy(DAG.getDataLayout())));
251         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
252         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
253       }
254     } else if (PartVT.isFloatingPoint()) {
255       // FP split into multiple FP parts (for ppcf128)
256       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
257              "Unexpected split");
258       SDValue Lo, Hi;
259       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
260       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
261       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
262         std::swap(Lo, Hi);
263       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
264     } else {
265       // FP split into integer parts (soft fp)
266       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
267              !PartVT.isVector() && "Unexpected split");
268       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
269       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
270     }
271   }
272 
273   // There is now one part, held in Val.  Correct it to match ValueVT.
274   // PartEVT is the type of the register class that holds the value.
275   // ValueVT is the type of the inline asm operation.
276   EVT PartEVT = Val.getValueType();
277 
278   if (PartEVT == ValueVT)
279     return Val;
280 
281   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
282       ValueVT.bitsLT(PartEVT)) {
283     // For an FP value in an integer part, we need to truncate to the right
284     // width first.
285     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
286     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
287   }
288 
289   // Handle types that have the same size.
290   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
291     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
292 
293   // Handle types with different sizes.
294   if (PartEVT.isInteger() && ValueVT.isInteger()) {
295     if (ValueVT.bitsLT(PartEVT)) {
296       // For a truncate, see if we have any information to
297       // indicate whether the truncated bits will always be
298       // zero or sign-extension.
299       if (AssertOp.hasValue())
300         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
301                           DAG.getValueType(ValueVT));
302       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
303     }
304     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
305   }
306 
307   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
308     // FP_ROUND's are always exact here.
309     if (ValueVT.bitsLT(Val.getValueType()))
310       return DAG.getNode(
311           ISD::FP_ROUND, DL, ValueVT, Val,
312           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
313 
314     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
315   }
316 
317   llvm_unreachable("Unknown mismatch!");
318 }
319 
320 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
321                                               const Twine &ErrMsg) {
322   const Instruction *I = dyn_cast_or_null<Instruction>(V);
323   if (!V)
324     return Ctx.emitError(ErrMsg);
325 
326   const char *AsmError = ", possible invalid constraint for vector type";
327   if (const CallInst *CI = dyn_cast<CallInst>(I))
328     if (isa<InlineAsm>(CI->getCalledValue()))
329       return Ctx.emitError(I, ErrMsg + AsmError);
330 
331   return Ctx.emitError(I, ErrMsg);
332 }
333 
334 /// getCopyFromPartsVector - Create a value that contains the specified legal
335 /// parts combined into the value they represent.  If the parts combine to a
336 /// type larger than ValueVT then AssertOp can be used to specify whether the
337 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
338 /// ValueVT (ISD::AssertSext).
339 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
340                                       const SDValue *Parts, unsigned NumParts,
341                                       MVT PartVT, EVT ValueVT, const Value *V,
342                                       bool IsABIRegCopy) {
343   assert(ValueVT.isVector() && "Not a vector value");
344   assert(NumParts > 0 && "No parts to assemble!");
345   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
346   SDValue Val = Parts[0];
347 
348   // Handle a multi-element vector.
349   if (NumParts > 1) {
350     EVT IntermediateVT;
351     MVT RegisterVT;
352     unsigned NumIntermediates;
353     unsigned NumRegs;
354 
355     if (IsABIRegCopy) {
356       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
357           *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
358           RegisterVT);
359     } else {
360       NumRegs =
361           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
362                                      NumIntermediates, RegisterVT);
363     }
364 
365     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
366     NumParts = NumRegs; // Silence a compiler warning.
367     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
368     assert(RegisterVT.getSizeInBits() ==
369            Parts[0].getSimpleValueType().getSizeInBits() &&
370            "Part type sizes don't match!");
371 
372     // Assemble the parts into intermediate operands.
373     SmallVector<SDValue, 8> Ops(NumIntermediates);
374     if (NumIntermediates == NumParts) {
375       // If the register was not expanded, truncate or copy the value,
376       // as appropriate.
377       for (unsigned i = 0; i != NumParts; ++i)
378         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
379                                   PartVT, IntermediateVT, V);
380     } else if (NumParts > 0) {
381       // If the intermediate type was expanded, build the intermediate
382       // operands from the parts.
383       assert(NumParts % NumIntermediates == 0 &&
384              "Must expand into a divisible number of parts!");
385       unsigned Factor = NumParts / NumIntermediates;
386       for (unsigned i = 0; i != NumIntermediates; ++i)
387         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
388                                   PartVT, IntermediateVT, V);
389     }
390 
391     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
392     // intermediate operands.
393     EVT BuiltVectorTy =
394         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
395                          (IntermediateVT.isVector()
396                               ? IntermediateVT.getVectorNumElements() * NumParts
397                               : NumIntermediates));
398     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
399                                                 : ISD::BUILD_VECTOR,
400                       DL, BuiltVectorTy, Ops);
401   }
402 
403   // There is now one part, held in Val.  Correct it to match ValueVT.
404   EVT PartEVT = Val.getValueType();
405 
406   if (PartEVT == ValueVT)
407     return Val;
408 
409   if (PartEVT.isVector()) {
410     // If the element type of the source/dest vectors are the same, but the
411     // parts vector has more elements than the value vector, then we have a
412     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
413     // elements we want.
414     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
415       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
416              "Cannot narrow, it would be a lossy transformation");
417       return DAG.getNode(
418           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
419           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
420     }
421 
422     // Vector/Vector bitcast.
423     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
424       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
425 
426     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
427       "Cannot handle this kind of promotion");
428     // Promoted vector extract
429     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
430 
431   }
432 
433   // Trivial bitcast if the types are the same size and the destination
434   // vector type is legal.
435   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
436       TLI.isTypeLegal(ValueVT))
437     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
438 
439   if (ValueVT.getVectorNumElements() != 1) {
440      // Certain ABIs require that vectors are passed as integers. For vectors
441      // are the same size, this is an obvious bitcast.
442      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
443        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
444      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
445        // Bitcast Val back the original type and extract the corresponding
446        // vector we want.
447        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
448        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
449                                            ValueVT.getVectorElementType(), Elts);
450        Val = DAG.getBitcast(WiderVecType, Val);
451        return DAG.getNode(
452            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
453            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
454      }
455 
456      diagnosePossiblyInvalidConstraint(
457          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
458      return DAG.getUNDEF(ValueVT);
459   }
460 
461   // Handle cases such as i8 -> <1 x i1>
462   EVT ValueSVT = ValueVT.getVectorElementType();
463   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
464     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
465                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
466 
467   return DAG.getBuildVector(ValueVT, DL, Val);
468 }
469 
470 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
471                                  SDValue Val, SDValue *Parts, unsigned NumParts,
472                                  MVT PartVT, const Value *V, bool IsABIRegCopy);
473 
474 /// getCopyToParts - Create a series of nodes that contain the specified value
475 /// split into legal parts.  If the parts contain more bits than Val, then, for
476 /// integers, ExtendKind can be used to specify how to generate the extra bits.
477 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
478                            SDValue *Parts, unsigned NumParts, MVT PartVT,
479                            const Value *V,
480                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND,
481                            bool IsABIRegCopy = false) {
482   EVT ValueVT = Val.getValueType();
483 
484   // Handle the vector case separately.
485   if (ValueVT.isVector())
486     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
487                                 IsABIRegCopy);
488 
489   unsigned PartBits = PartVT.getSizeInBits();
490   unsigned OrigNumParts = NumParts;
491   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
492          "Copying to an illegal type!");
493 
494   if (NumParts == 0)
495     return;
496 
497   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
498   EVT PartEVT = PartVT;
499   if (PartEVT == ValueVT) {
500     assert(NumParts == 1 && "No-op copy with multiple parts!");
501     Parts[0] = Val;
502     return;
503   }
504 
505   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
506     // If the parts cover more bits than the value has, promote the value.
507     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
508       assert(NumParts == 1 && "Do not know what to promote to!");
509       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
510     } else {
511       if (ValueVT.isFloatingPoint()) {
512         // FP values need to be bitcast, then extended if they are being put
513         // into a larger container.
514         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
515         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
516       }
517       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
518              ValueVT.isInteger() &&
519              "Unknown mismatch!");
520       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
521       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
522       if (PartVT == MVT::x86mmx)
523         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
524     }
525   } else if (PartBits == ValueVT.getSizeInBits()) {
526     // Different types of the same size.
527     assert(NumParts == 1 && PartEVT != ValueVT);
528     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
529   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
530     // If the parts cover less bits than value has, truncate the value.
531     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
532            ValueVT.isInteger() &&
533            "Unknown mismatch!");
534     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
535     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
536     if (PartVT == MVT::x86mmx)
537       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
538   }
539 
540   // The value may have changed - recompute ValueVT.
541   ValueVT = Val.getValueType();
542   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
543          "Failed to tile the value with PartVT!");
544 
545   if (NumParts == 1) {
546     if (PartEVT != ValueVT) {
547       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
548                                         "scalar-to-vector conversion failed");
549       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
550     }
551 
552     Parts[0] = Val;
553     return;
554   }
555 
556   // Expand the value into multiple parts.
557   if (NumParts & (NumParts - 1)) {
558     // The number of parts is not a power of 2.  Split off and copy the tail.
559     assert(PartVT.isInteger() && ValueVT.isInteger() &&
560            "Do not know what to expand to!");
561     unsigned RoundParts = 1 << Log2_32(NumParts);
562     unsigned RoundBits = RoundParts * PartBits;
563     unsigned OddParts = NumParts - RoundParts;
564     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
565                                  DAG.getIntPtrConstant(RoundBits, DL));
566     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
567 
568     if (DAG.getDataLayout().isBigEndian())
569       // The odd parts were reversed by getCopyToParts - unreverse them.
570       std::reverse(Parts + RoundParts, Parts + NumParts);
571 
572     NumParts = RoundParts;
573     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
574     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
575   }
576 
577   // The number of parts is a power of 2.  Repeatedly bisect the value using
578   // EXTRACT_ELEMENT.
579   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
580                          EVT::getIntegerVT(*DAG.getContext(),
581                                            ValueVT.getSizeInBits()),
582                          Val);
583 
584   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
585     for (unsigned i = 0; i < NumParts; i += StepSize) {
586       unsigned ThisBits = StepSize * PartBits / 2;
587       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
588       SDValue &Part0 = Parts[i];
589       SDValue &Part1 = Parts[i+StepSize/2];
590 
591       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
592                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
593       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
594                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
595 
596       if (ThisBits == PartBits && ThisVT != PartVT) {
597         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
598         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
599       }
600     }
601   }
602 
603   if (DAG.getDataLayout().isBigEndian())
604     std::reverse(Parts, Parts + OrigNumParts);
605 }
606 
607 
608 /// getCopyToPartsVector - Create a series of nodes that contain the specified
609 /// value split into legal parts.
610 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
611                                  SDValue Val, SDValue *Parts, unsigned NumParts,
612                                  MVT PartVT, const Value *V,
613                                  bool IsABIRegCopy) {
614   EVT ValueVT = Val.getValueType();
615   assert(ValueVT.isVector() && "Not a vector");
616   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
617 
618   if (NumParts == 1) {
619     EVT PartEVT = PartVT;
620     if (PartEVT == ValueVT) {
621       // Nothing to do.
622     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
623       // Bitconvert vector->vector case.
624       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
625     } else if (PartVT.isVector() &&
626                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
627                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
628       EVT ElementVT = PartVT.getVectorElementType();
629       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
630       // undef elements.
631       SmallVector<SDValue, 16> Ops;
632       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
633         Ops.push_back(DAG.getNode(
634             ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
635             DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
636 
637       for (unsigned i = ValueVT.getVectorNumElements(),
638            e = PartVT.getVectorNumElements(); i != e; ++i)
639         Ops.push_back(DAG.getUNDEF(ElementVT));
640 
641       Val = DAG.getBuildVector(PartVT, DL, Ops);
642 
643       // FIXME: Use CONCAT for 2x -> 4x.
644 
645       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
646       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
647     } else if (PartVT.isVector() &&
648                PartEVT.getVectorElementType().bitsGE(
649                  ValueVT.getVectorElementType()) &&
650                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
651 
652       // Promoted vector extract
653       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
654     } else {
655       if (ValueVT.getVectorNumElements() == 1) {
656         Val = DAG.getNode(
657             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
658             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
659       } else {
660         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
661                "lossy conversion of vector to scalar type");
662         EVT IntermediateType =
663             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
664         Val = DAG.getBitcast(IntermediateType, Val);
665         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
666       }
667     }
668 
669     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
670     Parts[0] = Val;
671     return;
672   }
673 
674   // Handle a multi-element vector.
675   EVT IntermediateVT;
676   MVT RegisterVT;
677   unsigned NumIntermediates;
678   unsigned NumRegs;
679   if (IsABIRegCopy) {
680     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
681         *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
682         RegisterVT);
683   } else {
684     NumRegs =
685         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
686                                    NumIntermediates, RegisterVT);
687   }
688   unsigned NumElements = ValueVT.getVectorNumElements();
689 
690   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
691   NumParts = NumRegs; // Silence a compiler warning.
692   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
693 
694   // Convert the vector to the appropiate type if necessary.
695   unsigned DestVectorNoElts =
696       NumIntermediates *
697       (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1);
698   EVT BuiltVectorTy = EVT::getVectorVT(
699       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
700   if (Val.getValueType() != BuiltVectorTy)
701     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
702 
703   // Split the vector into intermediate operands.
704   SmallVector<SDValue, 8> Ops(NumIntermediates);
705   for (unsigned i = 0; i != NumIntermediates; ++i) {
706     if (IntermediateVT.isVector())
707       Ops[i] =
708           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
709                       DAG.getConstant(i * (NumElements / NumIntermediates), DL,
710                                       TLI.getVectorIdxTy(DAG.getDataLayout())));
711     else
712       Ops[i] = DAG.getNode(
713           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
714           DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
715   }
716 
717   // Split the intermediate operands into legal parts.
718   if (NumParts == NumIntermediates) {
719     // If the register was not expanded, promote or copy the value,
720     // as appropriate.
721     for (unsigned i = 0; i != NumParts; ++i)
722       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
723   } else if (NumParts > 0) {
724     // If the intermediate type was expanded, split each the value into
725     // legal parts.
726     assert(NumIntermediates != 0 && "division by zero");
727     assert(NumParts % NumIntermediates == 0 &&
728            "Must expand into a divisible number of parts!");
729     unsigned Factor = NumParts / NumIntermediates;
730     for (unsigned i = 0; i != NumIntermediates; ++i)
731       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
732   }
733 }
734 
735 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
736                            EVT valuevt, bool IsABIMangledValue)
737     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
738       RegCount(1, regs.size()), IsABIMangled(IsABIMangledValue) {}
739 
740 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
741                            const DataLayout &DL, unsigned Reg, Type *Ty,
742                            bool IsABIMangledValue) {
743   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
744 
745   IsABIMangled = IsABIMangledValue;
746 
747   for (EVT ValueVT : ValueVTs) {
748     unsigned NumRegs = IsABIMangledValue
749                            ? TLI.getNumRegistersForCallingConv(Context, ValueVT)
750                            : TLI.getNumRegisters(Context, ValueVT);
751     MVT RegisterVT = IsABIMangledValue
752                          ? TLI.getRegisterTypeForCallingConv(Context, ValueVT)
753                          : TLI.getRegisterType(Context, ValueVT);
754     for (unsigned i = 0; i != NumRegs; ++i)
755       Regs.push_back(Reg + i);
756     RegVTs.push_back(RegisterVT);
757     RegCount.push_back(NumRegs);
758     Reg += NumRegs;
759   }
760 }
761 
762 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
763                                       FunctionLoweringInfo &FuncInfo,
764                                       const SDLoc &dl, SDValue &Chain,
765                                       SDValue *Flag, const Value *V) const {
766   // A Value with type {} or [0 x %t] needs no registers.
767   if (ValueVTs.empty())
768     return SDValue();
769 
770   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
771 
772   // Assemble the legal parts into the final values.
773   SmallVector<SDValue, 4> Values(ValueVTs.size());
774   SmallVector<SDValue, 8> Parts;
775   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
776     // Copy the legal parts from the registers.
777     EVT ValueVT = ValueVTs[Value];
778     unsigned NumRegs = RegCount[Value];
779     MVT RegisterVT = IsABIMangled
780                          ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
781                          : RegVTs[Value];
782 
783     Parts.resize(NumRegs);
784     for (unsigned i = 0; i != NumRegs; ++i) {
785       SDValue P;
786       if (!Flag) {
787         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
788       } else {
789         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
790         *Flag = P.getValue(2);
791       }
792 
793       Chain = P.getValue(1);
794       Parts[i] = P;
795 
796       // If the source register was virtual and if we know something about it,
797       // add an assert node.
798       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
799           !RegisterVT.isInteger() || RegisterVT.isVector())
800         continue;
801 
802       const FunctionLoweringInfo::LiveOutInfo *LOI =
803         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
804       if (!LOI)
805         continue;
806 
807       unsigned RegSize = RegisterVT.getSizeInBits();
808       unsigned NumSignBits = LOI->NumSignBits;
809       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
810 
811       if (NumZeroBits == RegSize) {
812         // The current value is a zero.
813         // Explicitly express that as it would be easier for
814         // optimizations to kick in.
815         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
816         continue;
817       }
818 
819       // FIXME: We capture more information than the dag can represent.  For
820       // now, just use the tightest assertzext/assertsext possible.
821       bool isSExt = true;
822       EVT FromVT(MVT::Other);
823       if (NumSignBits == RegSize) {
824         isSExt = true;   // ASSERT SEXT 1
825         FromVT = MVT::i1;
826       } else if (NumZeroBits >= RegSize - 1) {
827         isSExt = false;  // ASSERT ZEXT 1
828         FromVT = MVT::i1;
829       } else if (NumSignBits > RegSize - 8) {
830         isSExt = true;   // ASSERT SEXT 8
831         FromVT = MVT::i8;
832       } else if (NumZeroBits >= RegSize - 8) {
833         isSExt = false;  // ASSERT ZEXT 8
834         FromVT = MVT::i8;
835       } else if (NumSignBits > RegSize - 16) {
836         isSExt = true;   // ASSERT SEXT 16
837         FromVT = MVT::i16;
838       } else if (NumZeroBits >= RegSize - 16) {
839         isSExt = false;  // ASSERT ZEXT 16
840         FromVT = MVT::i16;
841       } else if (NumSignBits > RegSize - 32) {
842         isSExt = true;   // ASSERT SEXT 32
843         FromVT = MVT::i32;
844       } else if (NumZeroBits >= RegSize - 32) {
845         isSExt = false;  // ASSERT ZEXT 32
846         FromVT = MVT::i32;
847       } else {
848         continue;
849       }
850       // Add an assertion node.
851       assert(FromVT != MVT::Other);
852       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
853                              RegisterVT, P, DAG.getValueType(FromVT));
854     }
855 
856     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
857                                      NumRegs, RegisterVT, ValueVT, V);
858     Part += NumRegs;
859     Parts.clear();
860   }
861 
862   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
863 }
864 
865 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
866                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
867                                  const Value *V,
868                                  ISD::NodeType PreferredExtendType) const {
869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
870   ISD::NodeType ExtendKind = PreferredExtendType;
871 
872   // Get the list of the values's legal parts.
873   unsigned NumRegs = Regs.size();
874   SmallVector<SDValue, 8> Parts(NumRegs);
875   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
876     unsigned NumParts = RegCount[Value];
877 
878     MVT RegisterVT = IsABIMangled
879                          ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
880                          : RegVTs[Value];
881 
882     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
883       ExtendKind = ISD::ZERO_EXTEND;
884 
885     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
886                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
887     Part += NumParts;
888   }
889 
890   // Copy the parts into the registers.
891   SmallVector<SDValue, 8> Chains(NumRegs);
892   for (unsigned i = 0; i != NumRegs; ++i) {
893     SDValue Part;
894     if (!Flag) {
895       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
896     } else {
897       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
898       *Flag = Part.getValue(1);
899     }
900 
901     Chains[i] = Part.getValue(0);
902   }
903 
904   if (NumRegs == 1 || Flag)
905     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
906     // flagged to it. That is the CopyToReg nodes and the user are considered
907     // a single scheduling unit. If we create a TokenFactor and return it as
908     // chain, then the TokenFactor is both a predecessor (operand) of the
909     // user as well as a successor (the TF operands are flagged to the user).
910     // c1, f1 = CopyToReg
911     // c2, f2 = CopyToReg
912     // c3     = TokenFactor c1, c2
913     // ...
914     //        = op c3, ..., f2
915     Chain = Chains[NumRegs-1];
916   else
917     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
918 }
919 
920 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
921                                         unsigned MatchingIdx, const SDLoc &dl,
922                                         SelectionDAG &DAG,
923                                         std::vector<SDValue> &Ops) const {
924   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
925 
926   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
927   if (HasMatching)
928     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
929   else if (!Regs.empty() &&
930            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
931     // Put the register class of the virtual registers in the flag word.  That
932     // way, later passes can recompute register class constraints for inline
933     // assembly as well as normal instructions.
934     // Don't do this for tied operands that can use the regclass information
935     // from the def.
936     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
937     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
938     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
939   }
940 
941   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
942   Ops.push_back(Res);
943 
944   if (Code == InlineAsm::Kind_Clobber) {
945     // Clobbers should always have a 1:1 mapping with registers, and may
946     // reference registers that have illegal (e.g. vector) types. Hence, we
947     // shouldn't try to apply any sort of splitting logic to them.
948     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
949            "No 1:1 mapping from clobbers to regs?");
950     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
951     (void)SP;
952     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
953       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
954       assert(
955           (Regs[I] != SP ||
956            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
957           "If we clobbered the stack pointer, MFI should know about it.");
958     }
959     return;
960   }
961 
962   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
963     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
964     MVT RegisterVT = RegVTs[Value];
965     for (unsigned i = 0; i != NumRegs; ++i) {
966       assert(Reg < Regs.size() && "Mismatch in # registers expected");
967       unsigned TheReg = Regs[Reg++];
968       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
969     }
970   }
971 }
972 
973 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
974                                const TargetLibraryInfo *li) {
975   AA = aa;
976   GFI = gfi;
977   LibInfo = li;
978   DL = &DAG.getDataLayout();
979   Context = DAG.getContext();
980   LPadToCallSiteMap.clear();
981 }
982 
983 void SelectionDAGBuilder::clear() {
984   NodeMap.clear();
985   UnusedArgNodeMap.clear();
986   PendingLoads.clear();
987   PendingExports.clear();
988   CurInst = nullptr;
989   HasTailCall = false;
990   SDNodeOrder = LowestSDNodeOrder;
991   StatepointLowering.clear();
992 }
993 
994 void SelectionDAGBuilder::clearDanglingDebugInfo() {
995   DanglingDebugInfoMap.clear();
996 }
997 
998 SDValue SelectionDAGBuilder::getRoot() {
999   if (PendingLoads.empty())
1000     return DAG.getRoot();
1001 
1002   if (PendingLoads.size() == 1) {
1003     SDValue Root = PendingLoads[0];
1004     DAG.setRoot(Root);
1005     PendingLoads.clear();
1006     return Root;
1007   }
1008 
1009   // Otherwise, we have to make a token factor node.
1010   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1011                              PendingLoads);
1012   PendingLoads.clear();
1013   DAG.setRoot(Root);
1014   return Root;
1015 }
1016 
1017 SDValue SelectionDAGBuilder::getControlRoot() {
1018   SDValue Root = DAG.getRoot();
1019 
1020   if (PendingExports.empty())
1021     return Root;
1022 
1023   // Turn all of the CopyToReg chains into one factored node.
1024   if (Root.getOpcode() != ISD::EntryToken) {
1025     unsigned i = 0, e = PendingExports.size();
1026     for (; i != e; ++i) {
1027       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1028       if (PendingExports[i].getNode()->getOperand(0) == Root)
1029         break;  // Don't add the root if we already indirectly depend on it.
1030     }
1031 
1032     if (i == e)
1033       PendingExports.push_back(Root);
1034   }
1035 
1036   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1037                      PendingExports);
1038   PendingExports.clear();
1039   DAG.setRoot(Root);
1040   return Root;
1041 }
1042 
1043 void SelectionDAGBuilder::visit(const Instruction &I) {
1044   // Set up outgoing PHI node register values before emitting the terminator.
1045   if (isa<TerminatorInst>(&I)) {
1046     HandlePHINodesInSuccessorBlocks(I.getParent());
1047   }
1048 
1049   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1050   if (!isa<DbgInfoIntrinsic>(I))
1051     ++SDNodeOrder;
1052 
1053   CurInst = &I;
1054 
1055   visit(I.getOpcode(), I);
1056 
1057   if (!isa<TerminatorInst>(&I) && !HasTailCall &&
1058       !isStatepoint(&I)) // statepoints handle their exports internally
1059     CopyToExportRegsIfNeeded(&I);
1060 
1061   CurInst = nullptr;
1062 }
1063 
1064 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1065   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1066 }
1067 
1068 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1069   // Note: this doesn't use InstVisitor, because it has to work with
1070   // ConstantExpr's in addition to instructions.
1071   switch (Opcode) {
1072   default: llvm_unreachable("Unknown instruction type encountered!");
1073     // Build the switch statement using the Instruction.def file.
1074 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1075     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1076 #include "llvm/IR/Instruction.def"
1077   }
1078 }
1079 
1080 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1081 // generate the debug data structures now that we've seen its definition.
1082 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1083                                                    SDValue Val) {
1084   DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
1085   if (DDI.getDI()) {
1086     const DbgValueInst *DI = DDI.getDI();
1087     DebugLoc dl = DDI.getdl();
1088     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1089     DILocalVariable *Variable = DI->getVariable();
1090     DIExpression *Expr = DI->getExpression();
1091     assert(Variable->isValidLocationForIntrinsic(dl) &&
1092            "Expected inlined-at fields to agree");
1093     SDDbgValue *SDV;
1094     if (Val.getNode()) {
1095       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1096         SDV = getDbgValue(Val, Variable, Expr, dl, DbgSDNodeOrder);
1097         DAG.AddDbgValue(SDV, Val.getNode(), false);
1098       }
1099     } else
1100       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1101     DanglingDebugInfoMap[V] = DanglingDebugInfo();
1102   }
1103 }
1104 
1105 /// getCopyFromRegs - If there was virtual register allocated for the value V
1106 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1107 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1108   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1109   SDValue Result;
1110 
1111   if (It != FuncInfo.ValueMap.end()) {
1112     unsigned InReg = It->second;
1113 
1114     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1115                      DAG.getDataLayout(), InReg, Ty, isABIRegCopy(V));
1116     SDValue Chain = DAG.getEntryNode();
1117     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1118                                  V);
1119     resolveDanglingDebugInfo(V, Result);
1120   }
1121 
1122   return Result;
1123 }
1124 
1125 /// getValue - Return an SDValue for the given Value.
1126 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1127   // If we already have an SDValue for this value, use it. It's important
1128   // to do this first, so that we don't create a CopyFromReg if we already
1129   // have a regular SDValue.
1130   SDValue &N = NodeMap[V];
1131   if (N.getNode()) return N;
1132 
1133   // If there's a virtual register allocated and initialized for this
1134   // value, use it.
1135   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1136     return copyFromReg;
1137 
1138   // Otherwise create a new SDValue and remember it.
1139   SDValue Val = getValueImpl(V);
1140   NodeMap[V] = Val;
1141   resolveDanglingDebugInfo(V, Val);
1142   return Val;
1143 }
1144 
1145 // Return true if SDValue exists for the given Value
1146 bool SelectionDAGBuilder::findValue(const Value *V) const {
1147   return (NodeMap.find(V) != NodeMap.end()) ||
1148     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1149 }
1150 
1151 /// getNonRegisterValue - Return an SDValue for the given Value, but
1152 /// don't look in FuncInfo.ValueMap for a virtual register.
1153 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1154   // If we already have an SDValue for this value, use it.
1155   SDValue &N = NodeMap[V];
1156   if (N.getNode()) {
1157     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1158       // Remove the debug location from the node as the node is about to be used
1159       // in a location which may differ from the original debug location.  This
1160       // is relevant to Constant and ConstantFP nodes because they can appear
1161       // as constant expressions inside PHI nodes.
1162       N->setDebugLoc(DebugLoc());
1163     }
1164     return N;
1165   }
1166 
1167   // Otherwise create a new SDValue and remember it.
1168   SDValue Val = getValueImpl(V);
1169   NodeMap[V] = Val;
1170   resolveDanglingDebugInfo(V, Val);
1171   return Val;
1172 }
1173 
1174 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1175 /// Create an SDValue for the given value.
1176 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1177   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1178 
1179   if (const Constant *C = dyn_cast<Constant>(V)) {
1180     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1181 
1182     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1183       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1184 
1185     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1186       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1187 
1188     if (isa<ConstantPointerNull>(C)) {
1189       unsigned AS = V->getType()->getPointerAddressSpace();
1190       return DAG.getConstant(0, getCurSDLoc(),
1191                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1192     }
1193 
1194     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1195       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1196 
1197     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1198       return DAG.getUNDEF(VT);
1199 
1200     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1201       visit(CE->getOpcode(), *CE);
1202       SDValue N1 = NodeMap[V];
1203       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1204       return N1;
1205     }
1206 
1207     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1208       SmallVector<SDValue, 4> Constants;
1209       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1210            OI != OE; ++OI) {
1211         SDNode *Val = getValue(*OI).getNode();
1212         // If the operand is an empty aggregate, there are no values.
1213         if (!Val) continue;
1214         // Add each leaf value from the operand to the Constants list
1215         // to form a flattened list of all the values.
1216         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1217           Constants.push_back(SDValue(Val, i));
1218       }
1219 
1220       return DAG.getMergeValues(Constants, getCurSDLoc());
1221     }
1222 
1223     if (const ConstantDataSequential *CDS =
1224           dyn_cast<ConstantDataSequential>(C)) {
1225       SmallVector<SDValue, 4> Ops;
1226       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1227         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1228         // Add each leaf value from the operand to the Constants list
1229         // to form a flattened list of all the values.
1230         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1231           Ops.push_back(SDValue(Val, i));
1232       }
1233 
1234       if (isa<ArrayType>(CDS->getType()))
1235         return DAG.getMergeValues(Ops, getCurSDLoc());
1236       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1237     }
1238 
1239     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1240       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1241              "Unknown struct or array constant!");
1242 
1243       SmallVector<EVT, 4> ValueVTs;
1244       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1245       unsigned NumElts = ValueVTs.size();
1246       if (NumElts == 0)
1247         return SDValue(); // empty struct
1248       SmallVector<SDValue, 4> Constants(NumElts);
1249       for (unsigned i = 0; i != NumElts; ++i) {
1250         EVT EltVT = ValueVTs[i];
1251         if (isa<UndefValue>(C))
1252           Constants[i] = DAG.getUNDEF(EltVT);
1253         else if (EltVT.isFloatingPoint())
1254           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1255         else
1256           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1257       }
1258 
1259       return DAG.getMergeValues(Constants, getCurSDLoc());
1260     }
1261 
1262     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1263       return DAG.getBlockAddress(BA, VT);
1264 
1265     VectorType *VecTy = cast<VectorType>(V->getType());
1266     unsigned NumElements = VecTy->getNumElements();
1267 
1268     // Now that we know the number and type of the elements, get that number of
1269     // elements into the Ops array based on what kind of constant it is.
1270     SmallVector<SDValue, 16> Ops;
1271     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1272       for (unsigned i = 0; i != NumElements; ++i)
1273         Ops.push_back(getValue(CV->getOperand(i)));
1274     } else {
1275       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1276       EVT EltVT =
1277           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1278 
1279       SDValue Op;
1280       if (EltVT.isFloatingPoint())
1281         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1282       else
1283         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1284       Ops.assign(NumElements, Op);
1285     }
1286 
1287     // Create a BUILD_VECTOR node.
1288     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1289   }
1290 
1291   // If this is a static alloca, generate it as the frameindex instead of
1292   // computation.
1293   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1294     DenseMap<const AllocaInst*, int>::iterator SI =
1295       FuncInfo.StaticAllocaMap.find(AI);
1296     if (SI != FuncInfo.StaticAllocaMap.end())
1297       return DAG.getFrameIndex(SI->second,
1298                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1299   }
1300 
1301   // If this is an instruction which fast-isel has deferred, select it now.
1302   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1303     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1304 
1305     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1306                      Inst->getType(), isABIRegCopy(V));
1307     SDValue Chain = DAG.getEntryNode();
1308     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1309   }
1310 
1311   llvm_unreachable("Can't get register for value!");
1312 }
1313 
1314 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1315   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1316   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1317   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1318   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1319   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1320   if (IsMSVCCXX || IsCoreCLR)
1321     CatchPadMBB->setIsEHFuncletEntry();
1322 
1323   DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot()));
1324 }
1325 
1326 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1327   // Update machine-CFG edge.
1328   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1329   FuncInfo.MBB->addSuccessor(TargetMBB);
1330 
1331   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1332   bool IsSEH = isAsynchronousEHPersonality(Pers);
1333   if (IsSEH) {
1334     // If this is not a fall-through branch or optimizations are switched off,
1335     // emit the branch.
1336     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1337         TM.getOptLevel() == CodeGenOpt::None)
1338       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1339                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1340     return;
1341   }
1342 
1343   // Figure out the funclet membership for the catchret's successor.
1344   // This will be used by the FuncletLayout pass to determine how to order the
1345   // BB's.
1346   // A 'catchret' returns to the outer scope's color.
1347   Value *ParentPad = I.getCatchSwitchParentPad();
1348   const BasicBlock *SuccessorColor;
1349   if (isa<ConstantTokenNone>(ParentPad))
1350     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1351   else
1352     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1353   assert(SuccessorColor && "No parent funclet for catchret!");
1354   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1355   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1356 
1357   // Create the terminator node.
1358   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1359                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1360                             DAG.getBasicBlock(SuccessorColorMBB));
1361   DAG.setRoot(Ret);
1362 }
1363 
1364 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1365   // Don't emit any special code for the cleanuppad instruction. It just marks
1366   // the start of a funclet.
1367   FuncInfo.MBB->setIsEHFuncletEntry();
1368   FuncInfo.MBB->setIsCleanupFuncletEntry();
1369 }
1370 
1371 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1372 /// many places it could ultimately go. In the IR, we have a single unwind
1373 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1374 /// This function skips over imaginary basic blocks that hold catchswitch
1375 /// instructions, and finds all the "real" machine
1376 /// basic block destinations. As those destinations may not be successors of
1377 /// EHPadBB, here we also calculate the edge probability to those destinations.
1378 /// The passed-in Prob is the edge probability to EHPadBB.
1379 static void findUnwindDestinations(
1380     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1381     BranchProbability Prob,
1382     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1383         &UnwindDests) {
1384   EHPersonality Personality =
1385     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1386   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1387   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1388 
1389   while (EHPadBB) {
1390     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1391     BasicBlock *NewEHPadBB = nullptr;
1392     if (isa<LandingPadInst>(Pad)) {
1393       // Stop on landingpads. They are not funclets.
1394       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1395       break;
1396     } else if (isa<CleanupPadInst>(Pad)) {
1397       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1398       // personalities.
1399       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1400       UnwindDests.back().first->setIsEHFuncletEntry();
1401       break;
1402     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1403       // Add the catchpad handlers to the possible destinations.
1404       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1405         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1406         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1407         if (IsMSVCCXX || IsCoreCLR)
1408           UnwindDests.back().first->setIsEHFuncletEntry();
1409       }
1410       NewEHPadBB = CatchSwitch->getUnwindDest();
1411     } else {
1412       continue;
1413     }
1414 
1415     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1416     if (BPI && NewEHPadBB)
1417       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1418     EHPadBB = NewEHPadBB;
1419   }
1420 }
1421 
1422 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1423   // Update successor info.
1424   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1425   auto UnwindDest = I.getUnwindDest();
1426   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1427   BranchProbability UnwindDestProb =
1428       (BPI && UnwindDest)
1429           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1430           : BranchProbability::getZero();
1431   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1432   for (auto &UnwindDest : UnwindDests) {
1433     UnwindDest.first->setIsEHPad();
1434     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1435   }
1436   FuncInfo.MBB->normalizeSuccProbs();
1437 
1438   // Create the terminator node.
1439   SDValue Ret =
1440       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1441   DAG.setRoot(Ret);
1442 }
1443 
1444 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1445   report_fatal_error("visitCatchSwitch not yet implemented!");
1446 }
1447 
1448 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1449   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1450   auto &DL = DAG.getDataLayout();
1451   SDValue Chain = getControlRoot();
1452   SmallVector<ISD::OutputArg, 8> Outs;
1453   SmallVector<SDValue, 8> OutVals;
1454 
1455   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1456   // lower
1457   //
1458   //   %val = call <ty> @llvm.experimental.deoptimize()
1459   //   ret <ty> %val
1460   //
1461   // differently.
1462   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1463     LowerDeoptimizingReturn();
1464     return;
1465   }
1466 
1467   if (!FuncInfo.CanLowerReturn) {
1468     unsigned DemoteReg = FuncInfo.DemoteRegister;
1469     const Function *F = I.getParent()->getParent();
1470 
1471     // Emit a store of the return value through the virtual register.
1472     // Leave Outs empty so that LowerReturn won't try to load return
1473     // registers the usual way.
1474     SmallVector<EVT, 1> PtrValueVTs;
1475     ComputeValueVTs(TLI, DL,
1476                     F->getReturnType()->getPointerTo(
1477                         DAG.getDataLayout().getAllocaAddrSpace()),
1478                     PtrValueVTs);
1479 
1480     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1481                                         DemoteReg, PtrValueVTs[0]);
1482     SDValue RetOp = getValue(I.getOperand(0));
1483 
1484     SmallVector<EVT, 4> ValueVTs;
1485     SmallVector<uint64_t, 4> Offsets;
1486     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1487     unsigned NumValues = ValueVTs.size();
1488 
1489     SmallVector<SDValue, 4> Chains(NumValues);
1490     for (unsigned i = 0; i != NumValues; ++i) {
1491       // An aggregate return value cannot wrap around the address space, so
1492       // offsets to its parts don't wrap either.
1493       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1494       Chains[i] = DAG.getStore(
1495           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1496           // FIXME: better loc info would be nice.
1497           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1498     }
1499 
1500     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1501                         MVT::Other, Chains);
1502   } else if (I.getNumOperands() != 0) {
1503     SmallVector<EVT, 4> ValueVTs;
1504     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1505     unsigned NumValues = ValueVTs.size();
1506     if (NumValues) {
1507       SDValue RetOp = getValue(I.getOperand(0));
1508 
1509       const Function *F = I.getParent()->getParent();
1510 
1511       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1512       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1513                                           Attribute::SExt))
1514         ExtendKind = ISD::SIGN_EXTEND;
1515       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1516                                                Attribute::ZExt))
1517         ExtendKind = ISD::ZERO_EXTEND;
1518 
1519       LLVMContext &Context = F->getContext();
1520       bool RetInReg = F->getAttributes().hasAttribute(
1521           AttributeList::ReturnIndex, Attribute::InReg);
1522 
1523       for (unsigned j = 0; j != NumValues; ++j) {
1524         EVT VT = ValueVTs[j];
1525 
1526         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1527           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1528 
1529         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT);
1530         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT);
1531         SmallVector<SDValue, 4> Parts(NumParts);
1532         getCopyToParts(DAG, getCurSDLoc(),
1533                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1534                        &Parts[0], NumParts, PartVT, &I, ExtendKind, true);
1535 
1536         // 'inreg' on function refers to return value
1537         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1538         if (RetInReg)
1539           Flags.setInReg();
1540 
1541         // Propagate extension type if any
1542         if (ExtendKind == ISD::SIGN_EXTEND)
1543           Flags.setSExt();
1544         else if (ExtendKind == ISD::ZERO_EXTEND)
1545           Flags.setZExt();
1546 
1547         for (unsigned i = 0; i < NumParts; ++i) {
1548           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1549                                         VT, /*isfixed=*/true, 0, 0));
1550           OutVals.push_back(Parts[i]);
1551         }
1552       }
1553     }
1554   }
1555 
1556   // Push in swifterror virtual register as the last element of Outs. This makes
1557   // sure swifterror virtual register will be returned in the swifterror
1558   // physical register.
1559   const Function *F = I.getParent()->getParent();
1560   if (TLI.supportSwiftError() &&
1561       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1562     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1563     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1564     Flags.setSwiftError();
1565     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1566                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1567                                   true /*isfixed*/, 1 /*origidx*/,
1568                                   0 /*partOffs*/));
1569     // Create SDNode for the swifterror virtual register.
1570     OutVals.push_back(
1571         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1572                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1573                         EVT(TLI.getPointerTy(DL))));
1574   }
1575 
1576   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1577   CallingConv::ID CallConv =
1578     DAG.getMachineFunction().getFunction().getCallingConv();
1579   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1580       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1581 
1582   // Verify that the target's LowerReturn behaved as expected.
1583   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1584          "LowerReturn didn't return a valid chain!");
1585 
1586   // Update the DAG with the new chain value resulting from return lowering.
1587   DAG.setRoot(Chain);
1588 }
1589 
1590 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1591 /// created for it, emit nodes to copy the value into the virtual
1592 /// registers.
1593 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1594   // Skip empty types
1595   if (V->getType()->isEmptyTy())
1596     return;
1597 
1598   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1599   if (VMI != FuncInfo.ValueMap.end()) {
1600     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1601     CopyValueToVirtualRegister(V, VMI->second);
1602   }
1603 }
1604 
1605 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1606 /// the current basic block, add it to ValueMap now so that we'll get a
1607 /// CopyTo/FromReg.
1608 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1609   // No need to export constants.
1610   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1611 
1612   // Already exported?
1613   if (FuncInfo.isExportedInst(V)) return;
1614 
1615   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1616   CopyValueToVirtualRegister(V, Reg);
1617 }
1618 
1619 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1620                                                      const BasicBlock *FromBB) {
1621   // The operands of the setcc have to be in this block.  We don't know
1622   // how to export them from some other block.
1623   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1624     // Can export from current BB.
1625     if (VI->getParent() == FromBB)
1626       return true;
1627 
1628     // Is already exported, noop.
1629     return FuncInfo.isExportedInst(V);
1630   }
1631 
1632   // If this is an argument, we can export it if the BB is the entry block or
1633   // if it is already exported.
1634   if (isa<Argument>(V)) {
1635     if (FromBB == &FromBB->getParent()->getEntryBlock())
1636       return true;
1637 
1638     // Otherwise, can only export this if it is already exported.
1639     return FuncInfo.isExportedInst(V);
1640   }
1641 
1642   // Otherwise, constants can always be exported.
1643   return true;
1644 }
1645 
1646 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1647 BranchProbability
1648 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1649                                         const MachineBasicBlock *Dst) const {
1650   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1651   const BasicBlock *SrcBB = Src->getBasicBlock();
1652   const BasicBlock *DstBB = Dst->getBasicBlock();
1653   if (!BPI) {
1654     // If BPI is not available, set the default probability as 1 / N, where N is
1655     // the number of successors.
1656     auto SuccSize = std::max<uint32_t>(
1657         std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1);
1658     return BranchProbability(1, SuccSize);
1659   }
1660   return BPI->getEdgeProbability(SrcBB, DstBB);
1661 }
1662 
1663 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1664                                                MachineBasicBlock *Dst,
1665                                                BranchProbability Prob) {
1666   if (!FuncInfo.BPI)
1667     Src->addSuccessorWithoutProb(Dst);
1668   else {
1669     if (Prob.isUnknown())
1670       Prob = getEdgeProbability(Src, Dst);
1671     Src->addSuccessor(Dst, Prob);
1672   }
1673 }
1674 
1675 static bool InBlock(const Value *V, const BasicBlock *BB) {
1676   if (const Instruction *I = dyn_cast<Instruction>(V))
1677     return I->getParent() == BB;
1678   return true;
1679 }
1680 
1681 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1682 /// This function emits a branch and is used at the leaves of an OR or an
1683 /// AND operator tree.
1684 void
1685 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1686                                                   MachineBasicBlock *TBB,
1687                                                   MachineBasicBlock *FBB,
1688                                                   MachineBasicBlock *CurBB,
1689                                                   MachineBasicBlock *SwitchBB,
1690                                                   BranchProbability TProb,
1691                                                   BranchProbability FProb,
1692                                                   bool InvertCond) {
1693   const BasicBlock *BB = CurBB->getBasicBlock();
1694 
1695   // If the leaf of the tree is a comparison, merge the condition into
1696   // the caseblock.
1697   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1698     // The operands of the cmp have to be in this block.  We don't know
1699     // how to export them from some other block.  If this is the first block
1700     // of the sequence, no exporting is needed.
1701     if (CurBB == SwitchBB ||
1702         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1703          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1704       ISD::CondCode Condition;
1705       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1706         ICmpInst::Predicate Pred =
1707             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1708         Condition = getICmpCondCode(Pred);
1709       } else {
1710         const FCmpInst *FC = cast<FCmpInst>(Cond);
1711         FCmpInst::Predicate Pred =
1712             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1713         Condition = getFCmpCondCode(Pred);
1714         if (TM.Options.NoNaNsFPMath)
1715           Condition = getFCmpCodeWithoutNaN(Condition);
1716       }
1717 
1718       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1719                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1720       SwitchCases.push_back(CB);
1721       return;
1722     }
1723   }
1724 
1725   // Create a CaseBlock record representing this branch.
1726   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1727   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1728                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1729   SwitchCases.push_back(CB);
1730 }
1731 
1732 /// FindMergedConditions - If Cond is an expression like
1733 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1734                                                MachineBasicBlock *TBB,
1735                                                MachineBasicBlock *FBB,
1736                                                MachineBasicBlock *CurBB,
1737                                                MachineBasicBlock *SwitchBB,
1738                                                Instruction::BinaryOps Opc,
1739                                                BranchProbability TProb,
1740                                                BranchProbability FProb,
1741                                                bool InvertCond) {
1742   // Skip over not part of the tree and remember to invert op and operands at
1743   // next level.
1744   if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
1745     const Value *CondOp = BinaryOperator::getNotArgument(Cond);
1746     if (InBlock(CondOp, CurBB->getBasicBlock())) {
1747       FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1748                            !InvertCond);
1749       return;
1750     }
1751   }
1752 
1753   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1754   // Compute the effective opcode for Cond, taking into account whether it needs
1755   // to be inverted, e.g.
1756   //   and (not (or A, B)), C
1757   // gets lowered as
1758   //   and (and (not A, not B), C)
1759   unsigned BOpc = 0;
1760   if (BOp) {
1761     BOpc = BOp->getOpcode();
1762     if (InvertCond) {
1763       if (BOpc == Instruction::And)
1764         BOpc = Instruction::Or;
1765       else if (BOpc == Instruction::Or)
1766         BOpc = Instruction::And;
1767     }
1768   }
1769 
1770   // If this node is not part of the or/and tree, emit it as a branch.
1771   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1772       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
1773       BOp->getParent() != CurBB->getBasicBlock() ||
1774       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1775       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1776     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1777                                  TProb, FProb, InvertCond);
1778     return;
1779   }
1780 
1781   //  Create TmpBB after CurBB.
1782   MachineFunction::iterator BBI(CurBB);
1783   MachineFunction &MF = DAG.getMachineFunction();
1784   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1785   CurBB->getParent()->insert(++BBI, TmpBB);
1786 
1787   if (Opc == Instruction::Or) {
1788     // Codegen X | Y as:
1789     // BB1:
1790     //   jmp_if_X TBB
1791     //   jmp TmpBB
1792     // TmpBB:
1793     //   jmp_if_Y TBB
1794     //   jmp FBB
1795     //
1796 
1797     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1798     // The requirement is that
1799     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1800     //     = TrueProb for original BB.
1801     // Assuming the original probabilities are A and B, one choice is to set
1802     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1803     // A/(1+B) and 2B/(1+B). This choice assumes that
1804     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1805     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1806     // TmpBB, but the math is more complicated.
1807 
1808     auto NewTrueProb = TProb / 2;
1809     auto NewFalseProb = TProb / 2 + FProb;
1810     // Emit the LHS condition.
1811     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1812                          NewTrueProb, NewFalseProb, InvertCond);
1813 
1814     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1815     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1816     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1817     // Emit the RHS condition into TmpBB.
1818     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1819                          Probs[0], Probs[1], InvertCond);
1820   } else {
1821     assert(Opc == Instruction::And && "Unknown merge op!");
1822     // Codegen X & Y as:
1823     // BB1:
1824     //   jmp_if_X TmpBB
1825     //   jmp FBB
1826     // TmpBB:
1827     //   jmp_if_Y TBB
1828     //   jmp FBB
1829     //
1830     //  This requires creation of TmpBB after CurBB.
1831 
1832     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1833     // The requirement is that
1834     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1835     //     = FalseProb for original BB.
1836     // Assuming the original probabilities are A and B, one choice is to set
1837     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1838     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1839     // TrueProb for BB1 * FalseProb for TmpBB.
1840 
1841     auto NewTrueProb = TProb + FProb / 2;
1842     auto NewFalseProb = FProb / 2;
1843     // Emit the LHS condition.
1844     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1845                          NewTrueProb, NewFalseProb, InvertCond);
1846 
1847     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1848     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1849     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1850     // Emit the RHS condition into TmpBB.
1851     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1852                          Probs[0], Probs[1], InvertCond);
1853   }
1854 }
1855 
1856 /// If the set of cases should be emitted as a series of branches, return true.
1857 /// If we should emit this as a bunch of and/or'd together conditions, return
1858 /// false.
1859 bool
1860 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1861   if (Cases.size() != 2) return true;
1862 
1863   // If this is two comparisons of the same values or'd or and'd together, they
1864   // will get folded into a single comparison, so don't emit two blocks.
1865   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1866        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1867       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1868        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1869     return false;
1870   }
1871 
1872   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1873   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1874   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1875       Cases[0].CC == Cases[1].CC &&
1876       isa<Constant>(Cases[0].CmpRHS) &&
1877       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1878     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1879       return false;
1880     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1881       return false;
1882   }
1883 
1884   return true;
1885 }
1886 
1887 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1888   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1889 
1890   // Update machine-CFG edges.
1891   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1892 
1893   if (I.isUnconditional()) {
1894     // Update machine-CFG edges.
1895     BrMBB->addSuccessor(Succ0MBB);
1896 
1897     // If this is not a fall-through branch or optimizations are switched off,
1898     // emit the branch.
1899     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1900       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1901                               MVT::Other, getControlRoot(),
1902                               DAG.getBasicBlock(Succ0MBB)));
1903 
1904     return;
1905   }
1906 
1907   // If this condition is one of the special cases we handle, do special stuff
1908   // now.
1909   const Value *CondVal = I.getCondition();
1910   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1911 
1912   // If this is a series of conditions that are or'd or and'd together, emit
1913   // this as a sequence of branches instead of setcc's with and/or operations.
1914   // As long as jumps are not expensive, this should improve performance.
1915   // For example, instead of something like:
1916   //     cmp A, B
1917   //     C = seteq
1918   //     cmp D, E
1919   //     F = setle
1920   //     or C, F
1921   //     jnz foo
1922   // Emit:
1923   //     cmp A, B
1924   //     je foo
1925   //     cmp D, E
1926   //     jle foo
1927   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1928     Instruction::BinaryOps Opcode = BOp->getOpcode();
1929     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
1930         !I.getMetadata(LLVMContext::MD_unpredictable) &&
1931         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
1932       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1933                            Opcode,
1934                            getEdgeProbability(BrMBB, Succ0MBB),
1935                            getEdgeProbability(BrMBB, Succ1MBB),
1936                            /*InvertCond=*/false);
1937       // If the compares in later blocks need to use values not currently
1938       // exported from this block, export them now.  This block should always
1939       // be the first entry.
1940       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1941 
1942       // Allow some cases to be rejected.
1943       if (ShouldEmitAsBranches(SwitchCases)) {
1944         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1945           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1946           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1947         }
1948 
1949         // Emit the branch for this block.
1950         visitSwitchCase(SwitchCases[0], BrMBB);
1951         SwitchCases.erase(SwitchCases.begin());
1952         return;
1953       }
1954 
1955       // Okay, we decided not to do this, remove any inserted MBB's and clear
1956       // SwitchCases.
1957       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1958         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1959 
1960       SwitchCases.clear();
1961     }
1962   }
1963 
1964   // Create a CaseBlock record representing this branch.
1965   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1966                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
1967 
1968   // Use visitSwitchCase to actually insert the fast branch sequence for this
1969   // cond branch.
1970   visitSwitchCase(CB, BrMBB);
1971 }
1972 
1973 /// visitSwitchCase - Emits the necessary code to represent a single node in
1974 /// the binary search tree resulting from lowering a switch instruction.
1975 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1976                                           MachineBasicBlock *SwitchBB) {
1977   SDValue Cond;
1978   SDValue CondLHS = getValue(CB.CmpLHS);
1979   SDLoc dl = CB.DL;
1980 
1981   // Build the setcc now.
1982   if (!CB.CmpMHS) {
1983     // Fold "(X == true)" to X and "(X == false)" to !X to
1984     // handle common cases produced by branch lowering.
1985     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1986         CB.CC == ISD::SETEQ)
1987       Cond = CondLHS;
1988     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1989              CB.CC == ISD::SETEQ) {
1990       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
1991       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1992     } else
1993       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1994   } else {
1995     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1996 
1997     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1998     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1999 
2000     SDValue CmpOp = getValue(CB.CmpMHS);
2001     EVT VT = CmpOp.getValueType();
2002 
2003     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2004       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2005                           ISD::SETLE);
2006     } else {
2007       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2008                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2009       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2010                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2011     }
2012   }
2013 
2014   // Update successor info
2015   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2016   // TrueBB and FalseBB are always different unless the incoming IR is
2017   // degenerate. This only happens when running llc on weird IR.
2018   if (CB.TrueBB != CB.FalseBB)
2019     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2020   SwitchBB->normalizeSuccProbs();
2021 
2022   // If the lhs block is the next block, invert the condition so that we can
2023   // fall through to the lhs instead of the rhs block.
2024   if (CB.TrueBB == NextBlock(SwitchBB)) {
2025     std::swap(CB.TrueBB, CB.FalseBB);
2026     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2027     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2028   }
2029 
2030   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2031                                MVT::Other, getControlRoot(), Cond,
2032                                DAG.getBasicBlock(CB.TrueBB));
2033 
2034   // Insert the false branch. Do this even if it's a fall through branch,
2035   // this makes it easier to do DAG optimizations which require inverting
2036   // the branch condition.
2037   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2038                        DAG.getBasicBlock(CB.FalseBB));
2039 
2040   DAG.setRoot(BrCond);
2041 }
2042 
2043 /// visitJumpTable - Emit JumpTable node in the current MBB
2044 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2045   // Emit the code for the jump table
2046   assert(JT.Reg != -1U && "Should lower JT Header first!");
2047   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2048   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2049                                      JT.Reg, PTy);
2050   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2051   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2052                                     MVT::Other, Index.getValue(1),
2053                                     Table, Index);
2054   DAG.setRoot(BrJumpTable);
2055 }
2056 
2057 /// visitJumpTableHeader - This function emits necessary code to produce index
2058 /// in the JumpTable from switch case.
2059 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2060                                                JumpTableHeader &JTH,
2061                                                MachineBasicBlock *SwitchBB) {
2062   SDLoc dl = getCurSDLoc();
2063 
2064   // Subtract the lowest switch case value from the value being switched on and
2065   // conditional branch to default mbb if the result is greater than the
2066   // difference between smallest and largest cases.
2067   SDValue SwitchOp = getValue(JTH.SValue);
2068   EVT VT = SwitchOp.getValueType();
2069   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2070                             DAG.getConstant(JTH.First, dl, VT));
2071 
2072   // The SDNode we just created, which holds the value being switched on minus
2073   // the smallest case value, needs to be copied to a virtual register so it
2074   // can be used as an index into the jump table in a subsequent basic block.
2075   // This value may be smaller or larger than the target's pointer type, and
2076   // therefore require extension or truncating.
2077   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2078   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2079 
2080   unsigned JumpTableReg =
2081       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2082   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2083                                     JumpTableReg, SwitchOp);
2084   JT.Reg = JumpTableReg;
2085 
2086   // Emit the range check for the jump table, and branch to the default block
2087   // for the switch statement if the value being switched on exceeds the largest
2088   // case in the switch.
2089   SDValue CMP = DAG.getSetCC(
2090       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2091                                  Sub.getValueType()),
2092       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2093 
2094   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2095                                MVT::Other, CopyTo, CMP,
2096                                DAG.getBasicBlock(JT.Default));
2097 
2098   // Avoid emitting unnecessary branches to the next block.
2099   if (JT.MBB != NextBlock(SwitchBB))
2100     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2101                          DAG.getBasicBlock(JT.MBB));
2102 
2103   DAG.setRoot(BrCond);
2104 }
2105 
2106 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2107 /// variable if there exists one.
2108 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2109                                  SDValue &Chain) {
2110   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2111   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2112   MachineFunction &MF = DAG.getMachineFunction();
2113   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2114   MachineSDNode *Node =
2115       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2116   if (Global) {
2117     MachinePointerInfo MPInfo(Global);
2118     MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
2119     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2120                  MachineMemOperand::MODereferenceable;
2121     *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8,
2122                                        DAG.getEVTAlignment(PtrTy));
2123     Node->setMemRefs(MemRefs, MemRefs + 1);
2124   }
2125   return SDValue(Node, 0);
2126 }
2127 
2128 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2129 /// tail spliced into a stack protector check success bb.
2130 ///
2131 /// For a high level explanation of how this fits into the stack protector
2132 /// generation see the comment on the declaration of class
2133 /// StackProtectorDescriptor.
2134 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2135                                                   MachineBasicBlock *ParentBB) {
2136 
2137   // First create the loads to the guard/stack slot for the comparison.
2138   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2139   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2140 
2141   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2142   int FI = MFI.getStackProtectorIndex();
2143 
2144   SDValue Guard;
2145   SDLoc dl = getCurSDLoc();
2146   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2147   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2148   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2149 
2150   // Generate code to load the content of the guard slot.
2151   SDValue GuardVal = DAG.getLoad(
2152       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2153       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2154       MachineMemOperand::MOVolatile);
2155 
2156   if (TLI.useStackGuardXorFP())
2157     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2158 
2159   // Retrieve guard check function, nullptr if instrumentation is inlined.
2160   if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
2161     // The target provides a guard check function to validate the guard value.
2162     // Generate a call to that function with the content of the guard slot as
2163     // argument.
2164     auto *Fn = cast<Function>(GuardCheck);
2165     FunctionType *FnTy = Fn->getFunctionType();
2166     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2167 
2168     TargetLowering::ArgListTy Args;
2169     TargetLowering::ArgListEntry Entry;
2170     Entry.Node = GuardVal;
2171     Entry.Ty = FnTy->getParamType(0);
2172     if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
2173       Entry.IsInReg = true;
2174     Args.push_back(Entry);
2175 
2176     TargetLowering::CallLoweringInfo CLI(DAG);
2177     CLI.setDebugLoc(getCurSDLoc())
2178       .setChain(DAG.getEntryNode())
2179       .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
2180                  getValue(GuardCheck), std::move(Args));
2181 
2182     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2183     DAG.setRoot(Result.second);
2184     return;
2185   }
2186 
2187   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2188   // Otherwise, emit a volatile load to retrieve the stack guard value.
2189   SDValue Chain = DAG.getEntryNode();
2190   if (TLI.useLoadStackGuardNode()) {
2191     Guard = getLoadStackGuard(DAG, dl, Chain);
2192   } else {
2193     const Value *IRGuard = TLI.getSDagStackGuard(M);
2194     SDValue GuardPtr = getValue(IRGuard);
2195 
2196     Guard =
2197         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2198                     Align, MachineMemOperand::MOVolatile);
2199   }
2200 
2201   // Perform the comparison via a subtract/getsetcc.
2202   EVT VT = Guard.getValueType();
2203   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2204 
2205   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2206                                                         *DAG.getContext(),
2207                                                         Sub.getValueType()),
2208                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2209 
2210   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2211   // branch to failure MBB.
2212   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2213                                MVT::Other, GuardVal.getOperand(0),
2214                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2215   // Otherwise branch to success MBB.
2216   SDValue Br = DAG.getNode(ISD::BR, dl,
2217                            MVT::Other, BrCond,
2218                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2219 
2220   DAG.setRoot(Br);
2221 }
2222 
2223 /// Codegen the failure basic block for a stack protector check.
2224 ///
2225 /// A failure stack protector machine basic block consists simply of a call to
2226 /// __stack_chk_fail().
2227 ///
2228 /// For a high level explanation of how this fits into the stack protector
2229 /// generation see the comment on the declaration of class
2230 /// StackProtectorDescriptor.
2231 void
2232 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2233   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2234   SDValue Chain =
2235       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2236                       None, false, getCurSDLoc(), false, false).second;
2237   DAG.setRoot(Chain);
2238 }
2239 
2240 /// visitBitTestHeader - This function emits necessary code to produce value
2241 /// suitable for "bit tests"
2242 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2243                                              MachineBasicBlock *SwitchBB) {
2244   SDLoc dl = getCurSDLoc();
2245 
2246   // Subtract the minimum value
2247   SDValue SwitchOp = getValue(B.SValue);
2248   EVT VT = SwitchOp.getValueType();
2249   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2250                             DAG.getConstant(B.First, dl, VT));
2251 
2252   // Check range
2253   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2254   SDValue RangeCmp = DAG.getSetCC(
2255       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2256                                  Sub.getValueType()),
2257       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2258 
2259   // Determine the type of the test operands.
2260   bool UsePtrType = false;
2261   if (!TLI.isTypeLegal(VT))
2262     UsePtrType = true;
2263   else {
2264     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2265       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2266         // Switch table case range are encoded into series of masks.
2267         // Just use pointer type, it's guaranteed to fit.
2268         UsePtrType = true;
2269         break;
2270       }
2271   }
2272   if (UsePtrType) {
2273     VT = TLI.getPointerTy(DAG.getDataLayout());
2274     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2275   }
2276 
2277   B.RegVT = VT.getSimpleVT();
2278   B.Reg = FuncInfo.CreateReg(B.RegVT);
2279   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2280 
2281   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2282 
2283   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2284   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2285   SwitchBB->normalizeSuccProbs();
2286 
2287   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2288                                 MVT::Other, CopyTo, RangeCmp,
2289                                 DAG.getBasicBlock(B.Default));
2290 
2291   // Avoid emitting unnecessary branches to the next block.
2292   if (MBB != NextBlock(SwitchBB))
2293     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2294                           DAG.getBasicBlock(MBB));
2295 
2296   DAG.setRoot(BrRange);
2297 }
2298 
2299 /// visitBitTestCase - this function produces one "bit test"
2300 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2301                                            MachineBasicBlock* NextMBB,
2302                                            BranchProbability BranchProbToNext,
2303                                            unsigned Reg,
2304                                            BitTestCase &B,
2305                                            MachineBasicBlock *SwitchBB) {
2306   SDLoc dl = getCurSDLoc();
2307   MVT VT = BB.RegVT;
2308   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2309   SDValue Cmp;
2310   unsigned PopCount = countPopulation(B.Mask);
2311   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2312   if (PopCount == 1) {
2313     // Testing for a single bit; just compare the shift count with what it
2314     // would need to be to shift a 1 bit in that position.
2315     Cmp = DAG.getSetCC(
2316         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2317         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2318         ISD::SETEQ);
2319   } else if (PopCount == BB.Range) {
2320     // There is only one zero bit in the range, test for it directly.
2321     Cmp = DAG.getSetCC(
2322         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2323         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2324         ISD::SETNE);
2325   } else {
2326     // Make desired shift
2327     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2328                                     DAG.getConstant(1, dl, VT), ShiftOp);
2329 
2330     // Emit bit tests and jumps
2331     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2332                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2333     Cmp = DAG.getSetCC(
2334         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2335         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2336   }
2337 
2338   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2339   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2340   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2341   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2342   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2343   // one as they are relative probabilities (and thus work more like weights),
2344   // and hence we need to normalize them to let the sum of them become one.
2345   SwitchBB->normalizeSuccProbs();
2346 
2347   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2348                               MVT::Other, getControlRoot(),
2349                               Cmp, DAG.getBasicBlock(B.TargetBB));
2350 
2351   // Avoid emitting unnecessary branches to the next block.
2352   if (NextMBB != NextBlock(SwitchBB))
2353     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2354                         DAG.getBasicBlock(NextMBB));
2355 
2356   DAG.setRoot(BrAnd);
2357 }
2358 
2359 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2360   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2361 
2362   // Retrieve successors. Look through artificial IR level blocks like
2363   // catchswitch for successors.
2364   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2365   const BasicBlock *EHPadBB = I.getSuccessor(1);
2366 
2367   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2368   // have to do anything here to lower funclet bundles.
2369   assert(!I.hasOperandBundlesOtherThan(
2370              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2371          "Cannot lower invokes with arbitrary operand bundles yet!");
2372 
2373   const Value *Callee(I.getCalledValue());
2374   const Function *Fn = dyn_cast<Function>(Callee);
2375   if (isa<InlineAsm>(Callee))
2376     visitInlineAsm(&I);
2377   else if (Fn && Fn->isIntrinsic()) {
2378     switch (Fn->getIntrinsicID()) {
2379     default:
2380       llvm_unreachable("Cannot invoke this intrinsic");
2381     case Intrinsic::donothing:
2382       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2383       break;
2384     case Intrinsic::experimental_patchpoint_void:
2385     case Intrinsic::experimental_patchpoint_i64:
2386       visitPatchpoint(&I, EHPadBB);
2387       break;
2388     case Intrinsic::experimental_gc_statepoint:
2389       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2390       break;
2391     }
2392   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2393     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2394     // Eventually we will support lowering the @llvm.experimental.deoptimize
2395     // intrinsic, and right now there are no plans to support other intrinsics
2396     // with deopt state.
2397     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2398   } else {
2399     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2400   }
2401 
2402   // If the value of the invoke is used outside of its defining block, make it
2403   // available as a virtual register.
2404   // We already took care of the exported value for the statepoint instruction
2405   // during call to the LowerStatepoint.
2406   if (!isStatepoint(I)) {
2407     CopyToExportRegsIfNeeded(&I);
2408   }
2409 
2410   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2411   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2412   BranchProbability EHPadBBProb =
2413       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2414           : BranchProbability::getZero();
2415   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2416 
2417   // Update successor info.
2418   addSuccessorWithProb(InvokeMBB, Return);
2419   for (auto &UnwindDest : UnwindDests) {
2420     UnwindDest.first->setIsEHPad();
2421     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2422   }
2423   InvokeMBB->normalizeSuccProbs();
2424 
2425   // Drop into normal successor.
2426   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2427                           MVT::Other, getControlRoot(),
2428                           DAG.getBasicBlock(Return)));
2429 }
2430 
2431 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2432   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2433 }
2434 
2435 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2436   assert(FuncInfo.MBB->isEHPad() &&
2437          "Call to landingpad not in landing pad!");
2438 
2439   MachineBasicBlock *MBB = FuncInfo.MBB;
2440   addLandingPadInfo(LP, *MBB);
2441 
2442   // If there aren't registers to copy the values into (e.g., during SjLj
2443   // exceptions), then don't bother to create these DAG nodes.
2444   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2445   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2446   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2447       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2448     return;
2449 
2450   // If landingpad's return type is token type, we don't create DAG nodes
2451   // for its exception pointer and selector value. The extraction of exception
2452   // pointer or selector value from token type landingpads is not currently
2453   // supported.
2454   if (LP.getType()->isTokenTy())
2455     return;
2456 
2457   SmallVector<EVT, 2> ValueVTs;
2458   SDLoc dl = getCurSDLoc();
2459   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2460   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2461 
2462   // Get the two live-in registers as SDValues. The physregs have already been
2463   // copied into virtual registers.
2464   SDValue Ops[2];
2465   if (FuncInfo.ExceptionPointerVirtReg) {
2466     Ops[0] = DAG.getZExtOrTrunc(
2467         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2468                            FuncInfo.ExceptionPointerVirtReg,
2469                            TLI.getPointerTy(DAG.getDataLayout())),
2470         dl, ValueVTs[0]);
2471   } else {
2472     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2473   }
2474   Ops[1] = DAG.getZExtOrTrunc(
2475       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2476                          FuncInfo.ExceptionSelectorVirtReg,
2477                          TLI.getPointerTy(DAG.getDataLayout())),
2478       dl, ValueVTs[1]);
2479 
2480   // Merge into one.
2481   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2482                             DAG.getVTList(ValueVTs), Ops);
2483   setValue(&LP, Res);
2484 }
2485 
2486 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2487 #ifndef NDEBUG
2488   for (const CaseCluster &CC : Clusters)
2489     assert(CC.Low == CC.High && "Input clusters must be single-case");
2490 #endif
2491 
2492   std::sort(Clusters.begin(), Clusters.end(),
2493             [](const CaseCluster &a, const CaseCluster &b) {
2494     return a.Low->getValue().slt(b.Low->getValue());
2495   });
2496 
2497   // Merge adjacent clusters with the same destination.
2498   const unsigned N = Clusters.size();
2499   unsigned DstIndex = 0;
2500   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2501     CaseCluster &CC = Clusters[SrcIndex];
2502     const ConstantInt *CaseVal = CC.Low;
2503     MachineBasicBlock *Succ = CC.MBB;
2504 
2505     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2506         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2507       // If this case has the same successor and is a neighbour, merge it into
2508       // the previous cluster.
2509       Clusters[DstIndex - 1].High = CaseVal;
2510       Clusters[DstIndex - 1].Prob += CC.Prob;
2511     } else {
2512       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2513                    sizeof(Clusters[SrcIndex]));
2514     }
2515   }
2516   Clusters.resize(DstIndex);
2517 }
2518 
2519 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2520                                            MachineBasicBlock *Last) {
2521   // Update JTCases.
2522   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2523     if (JTCases[i].first.HeaderBB == First)
2524       JTCases[i].first.HeaderBB = Last;
2525 
2526   // Update BitTestCases.
2527   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2528     if (BitTestCases[i].Parent == First)
2529       BitTestCases[i].Parent = Last;
2530 }
2531 
2532 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2533   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2534 
2535   // Update machine-CFG edges with unique successors.
2536   SmallSet<BasicBlock*, 32> Done;
2537   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2538     BasicBlock *BB = I.getSuccessor(i);
2539     bool Inserted = Done.insert(BB).second;
2540     if (!Inserted)
2541         continue;
2542 
2543     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2544     addSuccessorWithProb(IndirectBrMBB, Succ);
2545   }
2546   IndirectBrMBB->normalizeSuccProbs();
2547 
2548   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2549                           MVT::Other, getControlRoot(),
2550                           getValue(I.getAddress())));
2551 }
2552 
2553 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2554   if (DAG.getTarget().Options.TrapUnreachable)
2555     DAG.setRoot(
2556         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2557 }
2558 
2559 void SelectionDAGBuilder::visitFSub(const User &I) {
2560   // -0.0 - X --> fneg
2561   Type *Ty = I.getType();
2562   if (isa<Constant>(I.getOperand(0)) &&
2563       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2564     SDValue Op2 = getValue(I.getOperand(1));
2565     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2566                              Op2.getValueType(), Op2));
2567     return;
2568   }
2569 
2570   visitBinary(I, ISD::FSUB);
2571 }
2572 
2573 /// Checks if the given instruction performs a vector reduction, in which case
2574 /// we have the freedom to alter the elements in the result as long as the
2575 /// reduction of them stays unchanged.
2576 static bool isVectorReductionOp(const User *I) {
2577   const Instruction *Inst = dyn_cast<Instruction>(I);
2578   if (!Inst || !Inst->getType()->isVectorTy())
2579     return false;
2580 
2581   auto OpCode = Inst->getOpcode();
2582   switch (OpCode) {
2583   case Instruction::Add:
2584   case Instruction::Mul:
2585   case Instruction::And:
2586   case Instruction::Or:
2587   case Instruction::Xor:
2588     break;
2589   case Instruction::FAdd:
2590   case Instruction::FMul:
2591     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2592       if (FPOp->getFastMathFlags().isFast())
2593         break;
2594     LLVM_FALLTHROUGH;
2595   default:
2596     return false;
2597   }
2598 
2599   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2600   unsigned ElemNumToReduce = ElemNum;
2601 
2602   // Do DFS search on the def-use chain from the given instruction. We only
2603   // allow four kinds of operations during the search until we reach the
2604   // instruction that extracts the first element from the vector:
2605   //
2606   //   1. The reduction operation of the same opcode as the given instruction.
2607   //
2608   //   2. PHI node.
2609   //
2610   //   3. ShuffleVector instruction together with a reduction operation that
2611   //      does a partial reduction.
2612   //
2613   //   4. ExtractElement that extracts the first element from the vector, and we
2614   //      stop searching the def-use chain here.
2615   //
2616   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2617   // from 1-3 to the stack to continue the DFS. The given instruction is not
2618   // a reduction operation if we meet any other instructions other than those
2619   // listed above.
2620 
2621   SmallVector<const User *, 16> UsersToVisit{Inst};
2622   SmallPtrSet<const User *, 16> Visited;
2623   bool ReduxExtracted = false;
2624 
2625   while (!UsersToVisit.empty()) {
2626     auto User = UsersToVisit.back();
2627     UsersToVisit.pop_back();
2628     if (!Visited.insert(User).second)
2629       continue;
2630 
2631     for (const auto &U : User->users()) {
2632       auto Inst = dyn_cast<Instruction>(U);
2633       if (!Inst)
2634         return false;
2635 
2636       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2637         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2638           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2639             return false;
2640         UsersToVisit.push_back(U);
2641       } else if (const ShuffleVectorInst *ShufInst =
2642                      dyn_cast<ShuffleVectorInst>(U)) {
2643         // Detect the following pattern: A ShuffleVector instruction together
2644         // with a reduction that do partial reduction on the first and second
2645         // ElemNumToReduce / 2 elements, and store the result in
2646         // ElemNumToReduce / 2 elements in another vector.
2647 
2648         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2649         if (ResultElements < ElemNum)
2650           return false;
2651 
2652         if (ElemNumToReduce == 1)
2653           return false;
2654         if (!isa<UndefValue>(U->getOperand(1)))
2655           return false;
2656         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2657           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2658             return false;
2659         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2660           if (ShufInst->getMaskValue(i) != -1)
2661             return false;
2662 
2663         // There is only one user of this ShuffleVector instruction, which
2664         // must be a reduction operation.
2665         if (!U->hasOneUse())
2666           return false;
2667 
2668         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2669         if (!U2 || U2->getOpcode() != OpCode)
2670           return false;
2671 
2672         // Check operands of the reduction operation.
2673         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2674             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2675           UsersToVisit.push_back(U2);
2676           ElemNumToReduce /= 2;
2677         } else
2678           return false;
2679       } else if (isa<ExtractElementInst>(U)) {
2680         // At this moment we should have reduced all elements in the vector.
2681         if (ElemNumToReduce != 1)
2682           return false;
2683 
2684         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2685         if (!Val || Val->getZExtValue() != 0)
2686           return false;
2687 
2688         ReduxExtracted = true;
2689       } else
2690         return false;
2691     }
2692   }
2693   return ReduxExtracted;
2694 }
2695 
2696 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2697   SDValue Op1 = getValue(I.getOperand(0));
2698   SDValue Op2 = getValue(I.getOperand(1));
2699 
2700   bool nuw = false;
2701   bool nsw = false;
2702   bool exact = false;
2703   bool vec_redux = false;
2704   FastMathFlags FMF;
2705 
2706   if (const OverflowingBinaryOperator *OFBinOp =
2707           dyn_cast<const OverflowingBinaryOperator>(&I)) {
2708     nuw = OFBinOp->hasNoUnsignedWrap();
2709     nsw = OFBinOp->hasNoSignedWrap();
2710   }
2711   if (const PossiblyExactOperator *ExactOp =
2712           dyn_cast<const PossiblyExactOperator>(&I))
2713     exact = ExactOp->isExact();
2714   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
2715     FMF = FPOp->getFastMathFlags();
2716 
2717   if (isVectorReductionOp(&I)) {
2718     vec_redux = true;
2719     DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2720   }
2721 
2722   SDNodeFlags Flags;
2723   Flags.setExact(exact);
2724   Flags.setNoSignedWrap(nsw);
2725   Flags.setNoUnsignedWrap(nuw);
2726   Flags.setVectorReduction(vec_redux);
2727   Flags.setAllowReciprocal(FMF.allowReciprocal());
2728   Flags.setAllowContract(FMF.allowContract());
2729   Flags.setNoInfs(FMF.noInfs());
2730   Flags.setNoNaNs(FMF.noNaNs());
2731   Flags.setNoSignedZeros(FMF.noSignedZeros());
2732   Flags.setUnsafeAlgebra(FMF.isFast());
2733 
2734   SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2735                                      Op1, Op2, Flags);
2736   setValue(&I, BinNodeValue);
2737 }
2738 
2739 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2740   SDValue Op1 = getValue(I.getOperand(0));
2741   SDValue Op2 = getValue(I.getOperand(1));
2742 
2743   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2744       Op2.getValueType(), DAG.getDataLayout());
2745 
2746   // Coerce the shift amount to the right type if we can.
2747   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2748     unsigned ShiftSize = ShiftTy.getSizeInBits();
2749     unsigned Op2Size = Op2.getValueSizeInBits();
2750     SDLoc DL = getCurSDLoc();
2751 
2752     // If the operand is smaller than the shift count type, promote it.
2753     if (ShiftSize > Op2Size)
2754       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2755 
2756     // If the operand is larger than the shift count type but the shift
2757     // count type has enough bits to represent any shift value, truncate
2758     // it now. This is a common case and it exposes the truncate to
2759     // optimization early.
2760     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2761       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2762     // Otherwise we'll need to temporarily settle for some other convenient
2763     // type.  Type legalization will make adjustments once the shiftee is split.
2764     else
2765       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2766   }
2767 
2768   bool nuw = false;
2769   bool nsw = false;
2770   bool exact = false;
2771 
2772   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2773 
2774     if (const OverflowingBinaryOperator *OFBinOp =
2775             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2776       nuw = OFBinOp->hasNoUnsignedWrap();
2777       nsw = OFBinOp->hasNoSignedWrap();
2778     }
2779     if (const PossiblyExactOperator *ExactOp =
2780             dyn_cast<const PossiblyExactOperator>(&I))
2781       exact = ExactOp->isExact();
2782   }
2783   SDNodeFlags Flags;
2784   Flags.setExact(exact);
2785   Flags.setNoSignedWrap(nsw);
2786   Flags.setNoUnsignedWrap(nuw);
2787   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2788                             Flags);
2789   setValue(&I, Res);
2790 }
2791 
2792 void SelectionDAGBuilder::visitSDiv(const User &I) {
2793   SDValue Op1 = getValue(I.getOperand(0));
2794   SDValue Op2 = getValue(I.getOperand(1));
2795 
2796   SDNodeFlags Flags;
2797   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2798                  cast<PossiblyExactOperator>(&I)->isExact());
2799   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2800                            Op2, Flags));
2801 }
2802 
2803 void SelectionDAGBuilder::visitICmp(const User &I) {
2804   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2805   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2806     predicate = IC->getPredicate();
2807   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2808     predicate = ICmpInst::Predicate(IC->getPredicate());
2809   SDValue Op1 = getValue(I.getOperand(0));
2810   SDValue Op2 = getValue(I.getOperand(1));
2811   ISD::CondCode Opcode = getICmpCondCode(predicate);
2812 
2813   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2814                                                         I.getType());
2815   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2816 }
2817 
2818 void SelectionDAGBuilder::visitFCmp(const User &I) {
2819   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2820   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2821     predicate = FC->getPredicate();
2822   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2823     predicate = FCmpInst::Predicate(FC->getPredicate());
2824   SDValue Op1 = getValue(I.getOperand(0));
2825   SDValue Op2 = getValue(I.getOperand(1));
2826   ISD::CondCode Condition = getFCmpCondCode(predicate);
2827 
2828   // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
2829   // FIXME: We should propagate the fast-math-flags to the DAG node itself for
2830   // further optimization, but currently FMF is only applicable to binary nodes.
2831   if (TM.Options.NoNaNsFPMath)
2832     Condition = getFCmpCodeWithoutNaN(Condition);
2833   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2834                                                         I.getType());
2835   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2836 }
2837 
2838 // Check if the condition of the select has one use or two users that are both
2839 // selects with the same condition.
2840 static bool hasOnlySelectUsers(const Value *Cond) {
2841   return llvm::all_of(Cond->users(), [](const Value *V) {
2842     return isa<SelectInst>(V);
2843   });
2844 }
2845 
2846 void SelectionDAGBuilder::visitSelect(const User &I) {
2847   SmallVector<EVT, 4> ValueVTs;
2848   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2849                   ValueVTs);
2850   unsigned NumValues = ValueVTs.size();
2851   if (NumValues == 0) return;
2852 
2853   SmallVector<SDValue, 4> Values(NumValues);
2854   SDValue Cond     = getValue(I.getOperand(0));
2855   SDValue LHSVal   = getValue(I.getOperand(1));
2856   SDValue RHSVal   = getValue(I.getOperand(2));
2857   auto BaseOps = {Cond};
2858   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2859     ISD::VSELECT : ISD::SELECT;
2860 
2861   // Min/max matching is only viable if all output VTs are the same.
2862   if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
2863     EVT VT = ValueVTs[0];
2864     LLVMContext &Ctx = *DAG.getContext();
2865     auto &TLI = DAG.getTargetLoweringInfo();
2866 
2867     // We care about the legality of the operation after it has been type
2868     // legalized.
2869     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2870            VT != TLI.getTypeToTransformTo(Ctx, VT))
2871       VT = TLI.getTypeToTransformTo(Ctx, VT);
2872 
2873     // If the vselect is legal, assume we want to leave this as a vector setcc +
2874     // vselect. Otherwise, if this is going to be scalarized, we want to see if
2875     // min/max is legal on the scalar type.
2876     bool UseScalarMinMax = VT.isVector() &&
2877       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2878 
2879     Value *LHS, *RHS;
2880     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2881     ISD::NodeType Opc = ISD::DELETED_NODE;
2882     switch (SPR.Flavor) {
2883     case SPF_UMAX:    Opc = ISD::UMAX; break;
2884     case SPF_UMIN:    Opc = ISD::UMIN; break;
2885     case SPF_SMAX:    Opc = ISD::SMAX; break;
2886     case SPF_SMIN:    Opc = ISD::SMIN; break;
2887     case SPF_FMINNUM:
2888       switch (SPR.NaNBehavior) {
2889       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2890       case SPNB_RETURNS_NAN:   Opc = ISD::FMINNAN; break;
2891       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2892       case SPNB_RETURNS_ANY: {
2893         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2894           Opc = ISD::FMINNUM;
2895         else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
2896           Opc = ISD::FMINNAN;
2897         else if (UseScalarMinMax)
2898           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2899             ISD::FMINNUM : ISD::FMINNAN;
2900         break;
2901       }
2902       }
2903       break;
2904     case SPF_FMAXNUM:
2905       switch (SPR.NaNBehavior) {
2906       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2907       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXNAN; break;
2908       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
2909       case SPNB_RETURNS_ANY:
2910 
2911         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
2912           Opc = ISD::FMAXNUM;
2913         else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
2914           Opc = ISD::FMAXNAN;
2915         else if (UseScalarMinMax)
2916           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
2917             ISD::FMAXNUM : ISD::FMAXNAN;
2918         break;
2919       }
2920       break;
2921     default: break;
2922     }
2923 
2924     if (Opc != ISD::DELETED_NODE &&
2925         (TLI.isOperationLegalOrCustom(Opc, VT) ||
2926          (UseScalarMinMax &&
2927           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
2928         // If the underlying comparison instruction is used by any other
2929         // instruction, the consumed instructions won't be destroyed, so it is
2930         // not profitable to convert to a min/max.
2931         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
2932       OpCode = Opc;
2933       LHSVal = getValue(LHS);
2934       RHSVal = getValue(RHS);
2935       BaseOps = {};
2936     }
2937   }
2938 
2939   for (unsigned i = 0; i != NumValues; ++i) {
2940     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
2941     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
2942     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
2943     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2944                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
2945                             Ops);
2946   }
2947 
2948   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2949                            DAG.getVTList(ValueVTs), Values));
2950 }
2951 
2952 void SelectionDAGBuilder::visitTrunc(const User &I) {
2953   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2954   SDValue N = getValue(I.getOperand(0));
2955   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2956                                                         I.getType());
2957   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2958 }
2959 
2960 void SelectionDAGBuilder::visitZExt(const User &I) {
2961   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2962   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2963   SDValue N = getValue(I.getOperand(0));
2964   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2965                                                         I.getType());
2966   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2967 }
2968 
2969 void SelectionDAGBuilder::visitSExt(const User &I) {
2970   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2971   // SExt also can't be a cast to bool for same reason. So, nothing much to do
2972   SDValue N = getValue(I.getOperand(0));
2973   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2974                                                         I.getType());
2975   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2976 }
2977 
2978 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2979   // FPTrunc is never a no-op cast, no need to check
2980   SDValue N = getValue(I.getOperand(0));
2981   SDLoc dl = getCurSDLoc();
2982   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2983   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2984   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
2985                            DAG.getTargetConstant(
2986                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
2987 }
2988 
2989 void SelectionDAGBuilder::visitFPExt(const User &I) {
2990   // FPExt is never a no-op cast, no need to check
2991   SDValue N = getValue(I.getOperand(0));
2992   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2993                                                         I.getType());
2994   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2995 }
2996 
2997 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2998   // FPToUI is never a no-op cast, no need to check
2999   SDValue N = getValue(I.getOperand(0));
3000   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3001                                                         I.getType());
3002   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3003 }
3004 
3005 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3006   // FPToSI is never a no-op cast, no need to check
3007   SDValue N = getValue(I.getOperand(0));
3008   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3009                                                         I.getType());
3010   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3011 }
3012 
3013 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3014   // UIToFP is never a no-op cast, no need to check
3015   SDValue N = getValue(I.getOperand(0));
3016   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3017                                                         I.getType());
3018   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3019 }
3020 
3021 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3022   // SIToFP is never a no-op cast, no need to check
3023   SDValue N = getValue(I.getOperand(0));
3024   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3025                                                         I.getType());
3026   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3027 }
3028 
3029 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3030   // What to do depends on the size of the integer and the size of the pointer.
3031   // We can either truncate, zero extend, or no-op, accordingly.
3032   SDValue N = getValue(I.getOperand(0));
3033   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3034                                                         I.getType());
3035   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3036 }
3037 
3038 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3039   // What to do depends on the size of the integer and the size of the pointer.
3040   // We can either truncate, zero extend, or no-op, accordingly.
3041   SDValue N = getValue(I.getOperand(0));
3042   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3043                                                         I.getType());
3044   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3045 }
3046 
3047 void SelectionDAGBuilder::visitBitCast(const User &I) {
3048   SDValue N = getValue(I.getOperand(0));
3049   SDLoc dl = getCurSDLoc();
3050   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3051                                                         I.getType());
3052 
3053   // BitCast assures us that source and destination are the same size so this is
3054   // either a BITCAST or a no-op.
3055   if (DestVT != N.getValueType())
3056     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3057                              DestVT, N)); // convert types.
3058   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3059   // might fold any kind of constant expression to an integer constant and that
3060   // is not what we are looking for. Only recognize a bitcast of a genuine
3061   // constant integer as an opaque constant.
3062   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3063     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3064                                  /*isOpaque*/true));
3065   else
3066     setValue(&I, N);            // noop cast.
3067 }
3068 
3069 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3070   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3071   const Value *SV = I.getOperand(0);
3072   SDValue N = getValue(SV);
3073   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3074 
3075   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3076   unsigned DestAS = I.getType()->getPointerAddressSpace();
3077 
3078   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3079     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3080 
3081   setValue(&I, N);
3082 }
3083 
3084 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3085   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3086   SDValue InVec = getValue(I.getOperand(0));
3087   SDValue InVal = getValue(I.getOperand(1));
3088   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3089                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3090   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3091                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3092                            InVec, InVal, InIdx));
3093 }
3094 
3095 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3096   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3097   SDValue InVec = getValue(I.getOperand(0));
3098   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3099                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3100   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3101                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3102                            InVec, InIdx));
3103 }
3104 
3105 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3106   SDValue Src1 = getValue(I.getOperand(0));
3107   SDValue Src2 = getValue(I.getOperand(1));
3108   SDLoc DL = getCurSDLoc();
3109 
3110   SmallVector<int, 8> Mask;
3111   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3112   unsigned MaskNumElts = Mask.size();
3113 
3114   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3115   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3116   EVT SrcVT = Src1.getValueType();
3117   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3118 
3119   if (SrcNumElts == MaskNumElts) {
3120     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3121     return;
3122   }
3123 
3124   // Normalize the shuffle vector since mask and vector length don't match.
3125   if (SrcNumElts < MaskNumElts) {
3126     // Mask is longer than the source vectors. We can use concatenate vector to
3127     // make the mask and vectors lengths match.
3128 
3129     if (MaskNumElts % SrcNumElts == 0) {
3130       // Mask length is a multiple of the source vector length.
3131       // Check if the shuffle is some kind of concatenation of the input
3132       // vectors.
3133       unsigned NumConcat = MaskNumElts / SrcNumElts;
3134       bool IsConcat = true;
3135       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3136       for (unsigned i = 0; i != MaskNumElts; ++i) {
3137         int Idx = Mask[i];
3138         if (Idx < 0)
3139           continue;
3140         // Ensure the indices in each SrcVT sized piece are sequential and that
3141         // the same source is used for the whole piece.
3142         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3143             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3144              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3145           IsConcat = false;
3146           break;
3147         }
3148         // Remember which source this index came from.
3149         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3150       }
3151 
3152       // The shuffle is concatenating multiple vectors together. Just emit
3153       // a CONCAT_VECTORS operation.
3154       if (IsConcat) {
3155         SmallVector<SDValue, 8> ConcatOps;
3156         for (auto Src : ConcatSrcs) {
3157           if (Src < 0)
3158             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3159           else if (Src == 0)
3160             ConcatOps.push_back(Src1);
3161           else
3162             ConcatOps.push_back(Src2);
3163         }
3164         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3165         return;
3166       }
3167     }
3168 
3169     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3170     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3171     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3172                                     PaddedMaskNumElts);
3173 
3174     // Pad both vectors with undefs to make them the same length as the mask.
3175     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3176 
3177     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3178     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3179     MOps1[0] = Src1;
3180     MOps2[0] = Src2;
3181 
3182     Src1 = Src1.isUndef()
3183                ? DAG.getUNDEF(PaddedVT)
3184                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3185     Src2 = Src2.isUndef()
3186                ? DAG.getUNDEF(PaddedVT)
3187                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3188 
3189     // Readjust mask for new input vector length.
3190     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3191     for (unsigned i = 0; i != MaskNumElts; ++i) {
3192       int Idx = Mask[i];
3193       if (Idx >= (int)SrcNumElts)
3194         Idx -= SrcNumElts - PaddedMaskNumElts;
3195       MappedOps[i] = Idx;
3196     }
3197 
3198     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3199 
3200     // If the concatenated vector was padded, extract a subvector with the
3201     // correct number of elements.
3202     if (MaskNumElts != PaddedMaskNumElts)
3203       Result = DAG.getNode(
3204           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3205           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3206 
3207     setValue(&I, Result);
3208     return;
3209   }
3210 
3211   if (SrcNumElts > MaskNumElts) {
3212     // Analyze the access pattern of the vector to see if we can extract
3213     // two subvectors and do the shuffle.
3214     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3215     bool CanExtract = true;
3216     for (int Idx : Mask) {
3217       unsigned Input = 0;
3218       if (Idx < 0)
3219         continue;
3220 
3221       if (Idx >= (int)SrcNumElts) {
3222         Input = 1;
3223         Idx -= SrcNumElts;
3224       }
3225 
3226       // If all the indices come from the same MaskNumElts sized portion of
3227       // the sources we can use extract. Also make sure the extract wouldn't
3228       // extract past the end of the source.
3229       int NewStartIdx = alignDown(Idx, MaskNumElts);
3230       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3231           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3232         CanExtract = false;
3233       // Make sure we always update StartIdx as we use it to track if all
3234       // elements are undef.
3235       StartIdx[Input] = NewStartIdx;
3236     }
3237 
3238     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3239       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3240       return;
3241     }
3242     if (CanExtract) {
3243       // Extract appropriate subvector and generate a vector shuffle
3244       for (unsigned Input = 0; Input < 2; ++Input) {
3245         SDValue &Src = Input == 0 ? Src1 : Src2;
3246         if (StartIdx[Input] < 0)
3247           Src = DAG.getUNDEF(VT);
3248         else {
3249           Src = DAG.getNode(
3250               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3251               DAG.getConstant(StartIdx[Input], DL,
3252                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3253         }
3254       }
3255 
3256       // Calculate new mask.
3257       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3258       for (int &Idx : MappedOps) {
3259         if (Idx >= (int)SrcNumElts)
3260           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3261         else if (Idx >= 0)
3262           Idx -= StartIdx[0];
3263       }
3264 
3265       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3266       return;
3267     }
3268   }
3269 
3270   // We can't use either concat vectors or extract subvectors so fall back to
3271   // replacing the shuffle with extract and build vector.
3272   // to insert and build vector.
3273   EVT EltVT = VT.getVectorElementType();
3274   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3275   SmallVector<SDValue,8> Ops;
3276   for (int Idx : Mask) {
3277     SDValue Res;
3278 
3279     if (Idx < 0) {
3280       Res = DAG.getUNDEF(EltVT);
3281     } else {
3282       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3283       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3284 
3285       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3286                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3287     }
3288 
3289     Ops.push_back(Res);
3290   }
3291 
3292   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3293 }
3294 
3295 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3296   ArrayRef<unsigned> Indices;
3297   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3298     Indices = IV->getIndices();
3299   else
3300     Indices = cast<ConstantExpr>(&I)->getIndices();
3301 
3302   const Value *Op0 = I.getOperand(0);
3303   const Value *Op1 = I.getOperand(1);
3304   Type *AggTy = I.getType();
3305   Type *ValTy = Op1->getType();
3306   bool IntoUndef = isa<UndefValue>(Op0);
3307   bool FromUndef = isa<UndefValue>(Op1);
3308 
3309   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3310 
3311   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3312   SmallVector<EVT, 4> AggValueVTs;
3313   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3314   SmallVector<EVT, 4> ValValueVTs;
3315   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3316 
3317   unsigned NumAggValues = AggValueVTs.size();
3318   unsigned NumValValues = ValValueVTs.size();
3319   SmallVector<SDValue, 4> Values(NumAggValues);
3320 
3321   // Ignore an insertvalue that produces an empty object
3322   if (!NumAggValues) {
3323     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3324     return;
3325   }
3326 
3327   SDValue Agg = getValue(Op0);
3328   unsigned i = 0;
3329   // Copy the beginning value(s) from the original aggregate.
3330   for (; i != LinearIndex; ++i)
3331     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3332                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3333   // Copy values from the inserted value(s).
3334   if (NumValValues) {
3335     SDValue Val = getValue(Op1);
3336     for (; i != LinearIndex + NumValValues; ++i)
3337       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3338                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3339   }
3340   // Copy remaining value(s) from the original aggregate.
3341   for (; i != NumAggValues; ++i)
3342     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3343                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3344 
3345   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3346                            DAG.getVTList(AggValueVTs), Values));
3347 }
3348 
3349 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3350   ArrayRef<unsigned> Indices;
3351   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3352     Indices = EV->getIndices();
3353   else
3354     Indices = cast<ConstantExpr>(&I)->getIndices();
3355 
3356   const Value *Op0 = I.getOperand(0);
3357   Type *AggTy = Op0->getType();
3358   Type *ValTy = I.getType();
3359   bool OutOfUndef = isa<UndefValue>(Op0);
3360 
3361   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3362 
3363   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3364   SmallVector<EVT, 4> ValValueVTs;
3365   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3366 
3367   unsigned NumValValues = ValValueVTs.size();
3368 
3369   // Ignore a extractvalue that produces an empty object
3370   if (!NumValValues) {
3371     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3372     return;
3373   }
3374 
3375   SmallVector<SDValue, 4> Values(NumValValues);
3376 
3377   SDValue Agg = getValue(Op0);
3378   // Copy out the selected value(s).
3379   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3380     Values[i - LinearIndex] =
3381       OutOfUndef ?
3382         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3383         SDValue(Agg.getNode(), Agg.getResNo() + i);
3384 
3385   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3386                            DAG.getVTList(ValValueVTs), Values));
3387 }
3388 
3389 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3390   Value *Op0 = I.getOperand(0);
3391   // Note that the pointer operand may be a vector of pointers. Take the scalar
3392   // element which holds a pointer.
3393   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3394   SDValue N = getValue(Op0);
3395   SDLoc dl = getCurSDLoc();
3396 
3397   // Normalize Vector GEP - all scalar operands should be converted to the
3398   // splat vector.
3399   unsigned VectorWidth = I.getType()->isVectorTy() ?
3400     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3401 
3402   if (VectorWidth && !N.getValueType().isVector()) {
3403     LLVMContext &Context = *DAG.getContext();
3404     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3405     N = DAG.getSplatBuildVector(VT, dl, N);
3406   }
3407 
3408   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3409        GTI != E; ++GTI) {
3410     const Value *Idx = GTI.getOperand();
3411     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3412       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3413       if (Field) {
3414         // N = N + Offset
3415         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3416 
3417         // In an inbounds GEP with an offset that is nonnegative even when
3418         // interpreted as signed, assume there is no unsigned overflow.
3419         SDNodeFlags Flags;
3420         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3421           Flags.setNoUnsignedWrap(true);
3422 
3423         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3424                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3425       }
3426     } else {
3427       MVT PtrTy =
3428           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS);
3429       unsigned PtrSize = PtrTy.getSizeInBits();
3430       APInt ElementSize(PtrSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3431 
3432       // If this is a scalar constant or a splat vector of constants,
3433       // handle it quickly.
3434       const auto *CI = dyn_cast<ConstantInt>(Idx);
3435       if (!CI && isa<ConstantDataVector>(Idx) &&
3436           cast<ConstantDataVector>(Idx)->getSplatValue())
3437         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3438 
3439       if (CI) {
3440         if (CI->isZero())
3441           continue;
3442         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
3443         LLVMContext &Context = *DAG.getContext();
3444         SDValue OffsVal = VectorWidth ?
3445           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, PtrTy, VectorWidth)) :
3446           DAG.getConstant(Offs, dl, PtrTy);
3447 
3448         // In an inbouds GEP with an offset that is nonnegative even when
3449         // interpreted as signed, assume there is no unsigned overflow.
3450         SDNodeFlags Flags;
3451         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3452           Flags.setNoUnsignedWrap(true);
3453 
3454         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3455         continue;
3456       }
3457 
3458       // N = N + Idx * ElementSize;
3459       SDValue IdxN = getValue(Idx);
3460 
3461       if (!IdxN.getValueType().isVector() && VectorWidth) {
3462         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3463         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3464       }
3465 
3466       // If the index is smaller or larger than intptr_t, truncate or extend
3467       // it.
3468       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3469 
3470       // If this is a multiply by a power of two, turn it into a shl
3471       // immediately.  This is a very common case.
3472       if (ElementSize != 1) {
3473         if (ElementSize.isPowerOf2()) {
3474           unsigned Amt = ElementSize.logBase2();
3475           IdxN = DAG.getNode(ISD::SHL, dl,
3476                              N.getValueType(), IdxN,
3477                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3478         } else {
3479           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3480           IdxN = DAG.getNode(ISD::MUL, dl,
3481                              N.getValueType(), IdxN, Scale);
3482         }
3483       }
3484 
3485       N = DAG.getNode(ISD::ADD, dl,
3486                       N.getValueType(), N, IdxN);
3487     }
3488   }
3489 
3490   setValue(&I, N);
3491 }
3492 
3493 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3494   // If this is a fixed sized alloca in the entry block of the function,
3495   // allocate it statically on the stack.
3496   if (FuncInfo.StaticAllocaMap.count(&I))
3497     return;   // getValue will auto-populate this.
3498 
3499   SDLoc dl = getCurSDLoc();
3500   Type *Ty = I.getAllocatedType();
3501   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3502   auto &DL = DAG.getDataLayout();
3503   uint64_t TySize = DL.getTypeAllocSize(Ty);
3504   unsigned Align =
3505       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3506 
3507   SDValue AllocSize = getValue(I.getArraySize());
3508 
3509   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3510   if (AllocSize.getValueType() != IntPtr)
3511     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3512 
3513   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3514                           AllocSize,
3515                           DAG.getConstant(TySize, dl, IntPtr));
3516 
3517   // Handle alignment.  If the requested alignment is less than or equal to
3518   // the stack alignment, ignore it.  If the size is greater than or equal to
3519   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3520   unsigned StackAlign =
3521       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3522   if (Align <= StackAlign)
3523     Align = 0;
3524 
3525   // Round the size of the allocation up to the stack alignment size
3526   // by add SA-1 to the size. This doesn't overflow because we're computing
3527   // an address inside an alloca.
3528   SDNodeFlags Flags;
3529   Flags.setNoUnsignedWrap(true);
3530   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3531                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3532 
3533   // Mask out the low bits for alignment purposes.
3534   AllocSize =
3535       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3536                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3537 
3538   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3539   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3540   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3541   setValue(&I, DSA);
3542   DAG.setRoot(DSA.getValue(1));
3543 
3544   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3545 }
3546 
3547 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3548   if (I.isAtomic())
3549     return visitAtomicLoad(I);
3550 
3551   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3552   const Value *SV = I.getOperand(0);
3553   if (TLI.supportSwiftError()) {
3554     // Swifterror values can come from either a function parameter with
3555     // swifterror attribute or an alloca with swifterror attribute.
3556     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3557       if (Arg->hasSwiftErrorAttr())
3558         return visitLoadFromSwiftError(I);
3559     }
3560 
3561     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3562       if (Alloca->isSwiftError())
3563         return visitLoadFromSwiftError(I);
3564     }
3565   }
3566 
3567   SDValue Ptr = getValue(SV);
3568 
3569   Type *Ty = I.getType();
3570 
3571   bool isVolatile = I.isVolatile();
3572   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3573   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3574   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3575   unsigned Alignment = I.getAlignment();
3576 
3577   AAMDNodes AAInfo;
3578   I.getAAMetadata(AAInfo);
3579   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3580 
3581   SmallVector<EVT, 4> ValueVTs;
3582   SmallVector<uint64_t, 4> Offsets;
3583   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3584   unsigned NumValues = ValueVTs.size();
3585   if (NumValues == 0)
3586     return;
3587 
3588   SDValue Root;
3589   bool ConstantMemory = false;
3590   if (isVolatile || NumValues > MaxParallelChains)
3591     // Serialize volatile loads with other side effects.
3592     Root = getRoot();
3593   else if (AA && AA->pointsToConstantMemory(MemoryLocation(
3594                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3595     // Do not serialize (non-volatile) loads of constant memory with anything.
3596     Root = DAG.getEntryNode();
3597     ConstantMemory = true;
3598   } else {
3599     // Do not serialize non-volatile loads against each other.
3600     Root = DAG.getRoot();
3601   }
3602 
3603   SDLoc dl = getCurSDLoc();
3604 
3605   if (isVolatile)
3606     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3607 
3608   // An aggregate load cannot wrap around the address space, so offsets to its
3609   // parts don't wrap either.
3610   SDNodeFlags Flags;
3611   Flags.setNoUnsignedWrap(true);
3612 
3613   SmallVector<SDValue, 4> Values(NumValues);
3614   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3615   EVT PtrVT = Ptr.getValueType();
3616   unsigned ChainI = 0;
3617   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3618     // Serializing loads here may result in excessive register pressure, and
3619     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3620     // could recover a bit by hoisting nodes upward in the chain by recognizing
3621     // they are side-effect free or do not alias. The optimizer should really
3622     // avoid this case by converting large object/array copies to llvm.memcpy
3623     // (MaxParallelChains should always remain as failsafe).
3624     if (ChainI == MaxParallelChains) {
3625       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3626       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3627                                   makeArrayRef(Chains.data(), ChainI));
3628       Root = Chain;
3629       ChainI = 0;
3630     }
3631     SDValue A = DAG.getNode(ISD::ADD, dl,
3632                             PtrVT, Ptr,
3633                             DAG.getConstant(Offsets[i], dl, PtrVT),
3634                             Flags);
3635     auto MMOFlags = MachineMemOperand::MONone;
3636     if (isVolatile)
3637       MMOFlags |= MachineMemOperand::MOVolatile;
3638     if (isNonTemporal)
3639       MMOFlags |= MachineMemOperand::MONonTemporal;
3640     if (isInvariant)
3641       MMOFlags |= MachineMemOperand::MOInvariant;
3642     if (isDereferenceable)
3643       MMOFlags |= MachineMemOperand::MODereferenceable;
3644     MMOFlags |= TLI.getMMOFlags(I);
3645 
3646     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3647                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3648                             MMOFlags, AAInfo, Ranges);
3649 
3650     Values[i] = L;
3651     Chains[ChainI] = L.getValue(1);
3652   }
3653 
3654   if (!ConstantMemory) {
3655     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3656                                 makeArrayRef(Chains.data(), ChainI));
3657     if (isVolatile)
3658       DAG.setRoot(Chain);
3659     else
3660       PendingLoads.push_back(Chain);
3661   }
3662 
3663   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3664                            DAG.getVTList(ValueVTs), Values));
3665 }
3666 
3667 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3668   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3669          "call visitStoreToSwiftError when backend supports swifterror");
3670 
3671   SmallVector<EVT, 4> ValueVTs;
3672   SmallVector<uint64_t, 4> Offsets;
3673   const Value *SrcV = I.getOperand(0);
3674   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3675                   SrcV->getType(), ValueVTs, &Offsets);
3676   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3677          "expect a single EVT for swifterror");
3678 
3679   SDValue Src = getValue(SrcV);
3680   // Create a virtual register, then update the virtual register.
3681   unsigned VReg; bool CreatedVReg;
3682   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3683   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3684   // Chain can be getRoot or getControlRoot.
3685   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3686                                       SDValue(Src.getNode(), Src.getResNo()));
3687   DAG.setRoot(CopyNode);
3688   if (CreatedVReg)
3689     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3690 }
3691 
3692 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3693   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3694          "call visitLoadFromSwiftError when backend supports swifterror");
3695 
3696   assert(!I.isVolatile() &&
3697          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3698          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3699          "Support volatile, non temporal, invariant for load_from_swift_error");
3700 
3701   const Value *SV = I.getOperand(0);
3702   Type *Ty = I.getType();
3703   AAMDNodes AAInfo;
3704   I.getAAMetadata(AAInfo);
3705   assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
3706              SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
3707          "load_from_swift_error should not be constant memory");
3708 
3709   SmallVector<EVT, 4> ValueVTs;
3710   SmallVector<uint64_t, 4> Offsets;
3711   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3712                   ValueVTs, &Offsets);
3713   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3714          "expect a single EVT for swifterror");
3715 
3716   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3717   SDValue L = DAG.getCopyFromReg(
3718       getRoot(), getCurSDLoc(),
3719       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3720       ValueVTs[0]);
3721 
3722   setValue(&I, L);
3723 }
3724 
3725 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3726   if (I.isAtomic())
3727     return visitAtomicStore(I);
3728 
3729   const Value *SrcV = I.getOperand(0);
3730   const Value *PtrV = I.getOperand(1);
3731 
3732   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3733   if (TLI.supportSwiftError()) {
3734     // Swifterror values can come from either a function parameter with
3735     // swifterror attribute or an alloca with swifterror attribute.
3736     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3737       if (Arg->hasSwiftErrorAttr())
3738         return visitStoreToSwiftError(I);
3739     }
3740 
3741     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3742       if (Alloca->isSwiftError())
3743         return visitStoreToSwiftError(I);
3744     }
3745   }
3746 
3747   SmallVector<EVT, 4> ValueVTs;
3748   SmallVector<uint64_t, 4> Offsets;
3749   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3750                   SrcV->getType(), ValueVTs, &Offsets);
3751   unsigned NumValues = ValueVTs.size();
3752   if (NumValues == 0)
3753     return;
3754 
3755   // Get the lowered operands. Note that we do this after
3756   // checking if NumResults is zero, because with zero results
3757   // the operands won't have values in the map.
3758   SDValue Src = getValue(SrcV);
3759   SDValue Ptr = getValue(PtrV);
3760 
3761   SDValue Root = getRoot();
3762   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3763   SDLoc dl = getCurSDLoc();
3764   EVT PtrVT = Ptr.getValueType();
3765   unsigned Alignment = I.getAlignment();
3766   AAMDNodes AAInfo;
3767   I.getAAMetadata(AAInfo);
3768 
3769   auto MMOFlags = MachineMemOperand::MONone;
3770   if (I.isVolatile())
3771     MMOFlags |= MachineMemOperand::MOVolatile;
3772   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3773     MMOFlags |= MachineMemOperand::MONonTemporal;
3774   MMOFlags |= TLI.getMMOFlags(I);
3775 
3776   // An aggregate load cannot wrap around the address space, so offsets to its
3777   // parts don't wrap either.
3778   SDNodeFlags Flags;
3779   Flags.setNoUnsignedWrap(true);
3780 
3781   unsigned ChainI = 0;
3782   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3783     // See visitLoad comments.
3784     if (ChainI == MaxParallelChains) {
3785       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3786                                   makeArrayRef(Chains.data(), ChainI));
3787       Root = Chain;
3788       ChainI = 0;
3789     }
3790     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3791                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
3792     SDValue St = DAG.getStore(
3793         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3794         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3795     Chains[ChainI] = St;
3796   }
3797 
3798   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3799                                   makeArrayRef(Chains.data(), ChainI));
3800   DAG.setRoot(StoreNode);
3801 }
3802 
3803 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3804                                            bool IsCompressing) {
3805   SDLoc sdl = getCurSDLoc();
3806 
3807   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3808                            unsigned& Alignment) {
3809     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3810     Src0 = I.getArgOperand(0);
3811     Ptr = I.getArgOperand(1);
3812     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3813     Mask = I.getArgOperand(3);
3814   };
3815   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3816                            unsigned& Alignment) {
3817     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3818     Src0 = I.getArgOperand(0);
3819     Ptr = I.getArgOperand(1);
3820     Mask = I.getArgOperand(2);
3821     Alignment = 0;
3822   };
3823 
3824   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3825   unsigned Alignment;
3826   if (IsCompressing)
3827     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3828   else
3829     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3830 
3831   SDValue Ptr = getValue(PtrOperand);
3832   SDValue Src0 = getValue(Src0Operand);
3833   SDValue Mask = getValue(MaskOperand);
3834 
3835   EVT VT = Src0.getValueType();
3836   if (!Alignment)
3837     Alignment = DAG.getEVTAlignment(VT);
3838 
3839   AAMDNodes AAInfo;
3840   I.getAAMetadata(AAInfo);
3841 
3842   MachineMemOperand *MMO =
3843     DAG.getMachineFunction().
3844     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3845                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3846                           Alignment, AAInfo);
3847   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3848                                          MMO, false /* Truncating */,
3849                                          IsCompressing);
3850   DAG.setRoot(StoreNode);
3851   setValue(&I, StoreNode);
3852 }
3853 
3854 // Get a uniform base for the Gather/Scatter intrinsic.
3855 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3856 // We try to represent it as a base pointer + vector of indices.
3857 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3858 // The first operand of the GEP may be a single pointer or a vector of pointers
3859 // Example:
3860 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3861 //  or
3862 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
3863 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3864 //
3865 // When the first GEP operand is a single pointer - it is the uniform base we
3866 // are looking for. If first operand of the GEP is a splat vector - we
3867 // extract the splat value and use it as a uniform base.
3868 // In all other cases the function returns 'false'.
3869 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
3870                            SDValue &Scale, SelectionDAGBuilder* SDB) {
3871   SelectionDAG& DAG = SDB->DAG;
3872   LLVMContext &Context = *DAG.getContext();
3873 
3874   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3875   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3876   if (!GEP)
3877     return false;
3878 
3879   const Value *GEPPtr = GEP->getPointerOperand();
3880   if (!GEPPtr->getType()->isVectorTy())
3881     Ptr = GEPPtr;
3882   else if (!(Ptr = getSplatValue(GEPPtr)))
3883     return false;
3884 
3885   unsigned FinalIndex = GEP->getNumOperands() - 1;
3886   Value *IndexVal = GEP->getOperand(FinalIndex);
3887 
3888   // Ensure all the other indices are 0.
3889   for (unsigned i = 1; i < FinalIndex; ++i) {
3890     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
3891     if (!C || !C->isZero())
3892       return false;
3893   }
3894 
3895   // The operands of the GEP may be defined in another basic block.
3896   // In this case we'll not find nodes for the operands.
3897   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3898     return false;
3899 
3900   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3901   const DataLayout &DL = DAG.getDataLayout();
3902   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
3903                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
3904   Base = SDB->getValue(Ptr);
3905   Index = SDB->getValue(IndexVal);
3906 
3907   if (!Index.getValueType().isVector()) {
3908     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
3909     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
3910     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
3911   }
3912   return true;
3913 }
3914 
3915 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
3916   SDLoc sdl = getCurSDLoc();
3917 
3918   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
3919   const Value *Ptr = I.getArgOperand(1);
3920   SDValue Src0 = getValue(I.getArgOperand(0));
3921   SDValue Mask = getValue(I.getArgOperand(3));
3922   EVT VT = Src0.getValueType();
3923   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3924   if (!Alignment)
3925     Alignment = DAG.getEVTAlignment(VT);
3926   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3927 
3928   AAMDNodes AAInfo;
3929   I.getAAMetadata(AAInfo);
3930 
3931   SDValue Base;
3932   SDValue Index;
3933   SDValue Scale;
3934   const Value *BasePtr = Ptr;
3935   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
3936 
3937   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
3938   MachineMemOperand *MMO = DAG.getMachineFunction().
3939     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
3940                          MachineMemOperand::MOStore,  VT.getStoreSize(),
3941                          Alignment, AAInfo);
3942   if (!UniformBase) {
3943     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3944     Index = getValue(Ptr);
3945     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3946   }
3947   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
3948   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
3949                                          Ops, MMO);
3950   DAG.setRoot(Scatter);
3951   setValue(&I, Scatter);
3952 }
3953 
3954 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
3955   SDLoc sdl = getCurSDLoc();
3956 
3957   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3958                            unsigned& Alignment) {
3959     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
3960     Ptr = I.getArgOperand(0);
3961     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
3962     Mask = I.getArgOperand(2);
3963     Src0 = I.getArgOperand(3);
3964   };
3965   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3966                            unsigned& Alignment) {
3967     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
3968     Ptr = I.getArgOperand(0);
3969     Alignment = 0;
3970     Mask = I.getArgOperand(1);
3971     Src0 = I.getArgOperand(2);
3972   };
3973 
3974   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3975   unsigned Alignment;
3976   if (IsExpanding)
3977     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3978   else
3979     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3980 
3981   SDValue Ptr = getValue(PtrOperand);
3982   SDValue Src0 = getValue(Src0Operand);
3983   SDValue Mask = getValue(MaskOperand);
3984 
3985   EVT VT = Src0.getValueType();
3986   if (!Alignment)
3987     Alignment = DAG.getEVTAlignment(VT);
3988 
3989   AAMDNodes AAInfo;
3990   I.getAAMetadata(AAInfo);
3991   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3992 
3993   // Do not serialize masked loads of constant memory with anything.
3994   bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
3995       PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
3996   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
3997 
3998   MachineMemOperand *MMO =
3999     DAG.getMachineFunction().
4000     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4001                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4002                           Alignment, AAInfo, Ranges);
4003 
4004   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4005                                    ISD::NON_EXTLOAD, IsExpanding);
4006   if (AddToChain) {
4007     SDValue OutChain = Load.getValue(1);
4008     DAG.setRoot(OutChain);
4009   }
4010   setValue(&I, Load);
4011 }
4012 
4013 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4014   SDLoc sdl = getCurSDLoc();
4015 
4016   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4017   const Value *Ptr = I.getArgOperand(0);
4018   SDValue Src0 = getValue(I.getArgOperand(3));
4019   SDValue Mask = getValue(I.getArgOperand(2));
4020 
4021   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4022   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4023   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4024   if (!Alignment)
4025     Alignment = DAG.getEVTAlignment(VT);
4026 
4027   AAMDNodes AAInfo;
4028   I.getAAMetadata(AAInfo);
4029   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4030 
4031   SDValue Root = DAG.getRoot();
4032   SDValue Base;
4033   SDValue Index;
4034   SDValue Scale;
4035   const Value *BasePtr = Ptr;
4036   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4037   bool ConstantMemory = false;
4038   if (UniformBase &&
4039       AA && AA->pointsToConstantMemory(MemoryLocation(
4040           BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
4041           AAInfo))) {
4042     // Do not serialize (non-volatile) loads of constant memory with anything.
4043     Root = DAG.getEntryNode();
4044     ConstantMemory = true;
4045   }
4046 
4047   MachineMemOperand *MMO =
4048     DAG.getMachineFunction().
4049     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4050                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4051                          Alignment, AAInfo, Ranges);
4052 
4053   if (!UniformBase) {
4054     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4055     Index = getValue(Ptr);
4056     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4057   }
4058   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4059   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4060                                        Ops, MMO);
4061 
4062   SDValue OutChain = Gather.getValue(1);
4063   if (!ConstantMemory)
4064     PendingLoads.push_back(OutChain);
4065   setValue(&I, Gather);
4066 }
4067 
4068 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4069   SDLoc dl = getCurSDLoc();
4070   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4071   AtomicOrdering FailureOrder = I.getFailureOrdering();
4072   SyncScope::ID SSID = I.getSyncScopeID();
4073 
4074   SDValue InChain = getRoot();
4075 
4076   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4077   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4078   SDValue L = DAG.getAtomicCmpSwap(
4079       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4080       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4081       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4082       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4083 
4084   SDValue OutChain = L.getValue(2);
4085 
4086   setValue(&I, L);
4087   DAG.setRoot(OutChain);
4088 }
4089 
4090 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4091   SDLoc dl = getCurSDLoc();
4092   ISD::NodeType NT;
4093   switch (I.getOperation()) {
4094   default: llvm_unreachable("Unknown atomicrmw operation");
4095   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4096   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4097   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4098   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4099   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4100   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4101   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4102   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4103   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4104   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4105   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4106   }
4107   AtomicOrdering Order = I.getOrdering();
4108   SyncScope::ID SSID = I.getSyncScopeID();
4109 
4110   SDValue InChain = getRoot();
4111 
4112   SDValue L =
4113     DAG.getAtomic(NT, dl,
4114                   getValue(I.getValOperand()).getSimpleValueType(),
4115                   InChain,
4116                   getValue(I.getPointerOperand()),
4117                   getValue(I.getValOperand()),
4118                   I.getPointerOperand(),
4119                   /* Alignment=*/ 0, Order, SSID);
4120 
4121   SDValue OutChain = L.getValue(1);
4122 
4123   setValue(&I, L);
4124   DAG.setRoot(OutChain);
4125 }
4126 
4127 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4128   SDLoc dl = getCurSDLoc();
4129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4130   SDValue Ops[3];
4131   Ops[0] = getRoot();
4132   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4133                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4134   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4135                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4136   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4137 }
4138 
4139 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4140   SDLoc dl = getCurSDLoc();
4141   AtomicOrdering Order = I.getOrdering();
4142   SyncScope::ID SSID = I.getSyncScopeID();
4143 
4144   SDValue InChain = getRoot();
4145 
4146   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4147   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4148 
4149   if (!TLI.supportsUnalignedAtomics() &&
4150       I.getAlignment() < VT.getStoreSize())
4151     report_fatal_error("Cannot generate unaligned atomic load");
4152 
4153   MachineMemOperand *MMO =
4154       DAG.getMachineFunction().
4155       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4156                            MachineMemOperand::MOVolatile |
4157                            MachineMemOperand::MOLoad,
4158                            VT.getStoreSize(),
4159                            I.getAlignment() ? I.getAlignment() :
4160                                               DAG.getEVTAlignment(VT),
4161                            AAMDNodes(), nullptr, SSID, Order);
4162 
4163   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4164   SDValue L =
4165       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4166                     getValue(I.getPointerOperand()), MMO);
4167 
4168   SDValue OutChain = L.getValue(1);
4169 
4170   setValue(&I, L);
4171   DAG.setRoot(OutChain);
4172 }
4173 
4174 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4175   SDLoc dl = getCurSDLoc();
4176 
4177   AtomicOrdering Order = I.getOrdering();
4178   SyncScope::ID SSID = I.getSyncScopeID();
4179 
4180   SDValue InChain = getRoot();
4181 
4182   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4183   EVT VT =
4184       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4185 
4186   if (I.getAlignment() < VT.getStoreSize())
4187     report_fatal_error("Cannot generate unaligned atomic store");
4188 
4189   SDValue OutChain =
4190     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4191                   InChain,
4192                   getValue(I.getPointerOperand()),
4193                   getValue(I.getValueOperand()),
4194                   I.getPointerOperand(), I.getAlignment(),
4195                   Order, SSID);
4196 
4197   DAG.setRoot(OutChain);
4198 }
4199 
4200 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4201 /// node.
4202 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4203                                                unsigned Intrinsic) {
4204   // Ignore the callsite's attributes. A specific call site may be marked with
4205   // readnone, but the lowering code will expect the chain based on the
4206   // definition.
4207   const Function *F = I.getCalledFunction();
4208   bool HasChain = !F->doesNotAccessMemory();
4209   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4210 
4211   // Build the operand list.
4212   SmallVector<SDValue, 8> Ops;
4213   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4214     if (OnlyLoad) {
4215       // We don't need to serialize loads against other loads.
4216       Ops.push_back(DAG.getRoot());
4217     } else {
4218       Ops.push_back(getRoot());
4219     }
4220   }
4221 
4222   // Info is set by getTgtMemInstrinsic
4223   TargetLowering::IntrinsicInfo Info;
4224   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4225   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4226                                                DAG.getMachineFunction(),
4227                                                Intrinsic);
4228 
4229   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4230   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4231       Info.opc == ISD::INTRINSIC_W_CHAIN)
4232     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4233                                         TLI.getPointerTy(DAG.getDataLayout())));
4234 
4235   // Add all operands of the call to the operand list.
4236   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4237     SDValue Op = getValue(I.getArgOperand(i));
4238     Ops.push_back(Op);
4239   }
4240 
4241   SmallVector<EVT, 4> ValueVTs;
4242   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4243 
4244   if (HasChain)
4245     ValueVTs.push_back(MVT::Other);
4246 
4247   SDVTList VTs = DAG.getVTList(ValueVTs);
4248 
4249   // Create the node.
4250   SDValue Result;
4251   if (IsTgtIntrinsic) {
4252     // This is target intrinsic that touches memory
4253     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4254       Ops, Info.memVT,
4255       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4256       Info.flags, Info.size);
4257   } else if (!HasChain) {
4258     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4259   } else if (!I.getType()->isVoidTy()) {
4260     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4261   } else {
4262     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4263   }
4264 
4265   if (HasChain) {
4266     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4267     if (OnlyLoad)
4268       PendingLoads.push_back(Chain);
4269     else
4270       DAG.setRoot(Chain);
4271   }
4272 
4273   if (!I.getType()->isVoidTy()) {
4274     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4275       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4276       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4277     } else
4278       Result = lowerRangeToAssertZExt(DAG, I, Result);
4279 
4280     setValue(&I, Result);
4281   }
4282 }
4283 
4284 /// GetSignificand - Get the significand and build it into a floating-point
4285 /// number with exponent of 1:
4286 ///
4287 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4288 ///
4289 /// where Op is the hexadecimal representation of floating point value.
4290 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4291   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4292                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4293   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4294                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4295   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4296 }
4297 
4298 /// GetExponent - Get the exponent:
4299 ///
4300 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4301 ///
4302 /// where Op is the hexadecimal representation of floating point value.
4303 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4304                            const TargetLowering &TLI, const SDLoc &dl) {
4305   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4306                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4307   SDValue t1 = DAG.getNode(
4308       ISD::SRL, dl, MVT::i32, t0,
4309       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4310   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4311                            DAG.getConstant(127, dl, MVT::i32));
4312   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4313 }
4314 
4315 /// getF32Constant - Get 32-bit floating point constant.
4316 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4317                               const SDLoc &dl) {
4318   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4319                            MVT::f32);
4320 }
4321 
4322 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4323                                        SelectionDAG &DAG) {
4324   // TODO: What fast-math-flags should be set on the floating-point nodes?
4325 
4326   //   IntegerPartOfX = ((int32_t)(t0);
4327   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4328 
4329   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4330   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4331   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4332 
4333   //   IntegerPartOfX <<= 23;
4334   IntegerPartOfX = DAG.getNode(
4335       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4336       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4337                                   DAG.getDataLayout())));
4338 
4339   SDValue TwoToFractionalPartOfX;
4340   if (LimitFloatPrecision <= 6) {
4341     // For floating-point precision of 6:
4342     //
4343     //   TwoToFractionalPartOfX =
4344     //     0.997535578f +
4345     //       (0.735607626f + 0.252464424f * x) * x;
4346     //
4347     // error 0.0144103317, which is 6 bits
4348     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4349                              getF32Constant(DAG, 0x3e814304, dl));
4350     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4351                              getF32Constant(DAG, 0x3f3c50c8, dl));
4352     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4353     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4354                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4355   } else if (LimitFloatPrecision <= 12) {
4356     // For floating-point precision of 12:
4357     //
4358     //   TwoToFractionalPartOfX =
4359     //     0.999892986f +
4360     //       (0.696457318f +
4361     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4362     //
4363     // error 0.000107046256, which is 13 to 14 bits
4364     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4365                              getF32Constant(DAG, 0x3da235e3, dl));
4366     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4367                              getF32Constant(DAG, 0x3e65b8f3, dl));
4368     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4369     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4370                              getF32Constant(DAG, 0x3f324b07, dl));
4371     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4372     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4373                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4374   } else { // LimitFloatPrecision <= 18
4375     // For floating-point precision of 18:
4376     //
4377     //   TwoToFractionalPartOfX =
4378     //     0.999999982f +
4379     //       (0.693148872f +
4380     //         (0.240227044f +
4381     //           (0.554906021e-1f +
4382     //             (0.961591928e-2f +
4383     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4384     // error 2.47208000*10^(-7), which is better than 18 bits
4385     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4386                              getF32Constant(DAG, 0x3924b03e, dl));
4387     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4388                              getF32Constant(DAG, 0x3ab24b87, dl));
4389     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4390     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4391                              getF32Constant(DAG, 0x3c1d8c17, dl));
4392     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4393     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4394                              getF32Constant(DAG, 0x3d634a1d, dl));
4395     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4396     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4397                              getF32Constant(DAG, 0x3e75fe14, dl));
4398     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4399     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4400                               getF32Constant(DAG, 0x3f317234, dl));
4401     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4402     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4403                                          getF32Constant(DAG, 0x3f800000, dl));
4404   }
4405 
4406   // Add the exponent into the result in integer domain.
4407   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4408   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4409                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4410 }
4411 
4412 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4413 /// limited-precision mode.
4414 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4415                          const TargetLowering &TLI) {
4416   if (Op.getValueType() == MVT::f32 &&
4417       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4418 
4419     // Put the exponent in the right bit position for later addition to the
4420     // final result:
4421     //
4422     //   #define LOG2OFe 1.4426950f
4423     //   t0 = Op * LOG2OFe
4424 
4425     // TODO: What fast-math-flags should be set here?
4426     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4427                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4428     return getLimitedPrecisionExp2(t0, dl, DAG);
4429   }
4430 
4431   // No special expansion.
4432   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4433 }
4434 
4435 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4436 /// limited-precision mode.
4437 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4438                          const TargetLowering &TLI) {
4439   // TODO: What fast-math-flags should be set on the floating-point nodes?
4440 
4441   if (Op.getValueType() == MVT::f32 &&
4442       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4443     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4444 
4445     // Scale the exponent by log(2) [0.69314718f].
4446     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4447     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4448                                         getF32Constant(DAG, 0x3f317218, dl));
4449 
4450     // Get the significand and build it into a floating-point number with
4451     // exponent of 1.
4452     SDValue X = GetSignificand(DAG, Op1, dl);
4453 
4454     SDValue LogOfMantissa;
4455     if (LimitFloatPrecision <= 6) {
4456       // For floating-point precision of 6:
4457       //
4458       //   LogofMantissa =
4459       //     -1.1609546f +
4460       //       (1.4034025f - 0.23903021f * x) * x;
4461       //
4462       // error 0.0034276066, which is better than 8 bits
4463       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4464                                getF32Constant(DAG, 0xbe74c456, dl));
4465       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4466                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4467       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4468       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4469                                   getF32Constant(DAG, 0x3f949a29, dl));
4470     } else if (LimitFloatPrecision <= 12) {
4471       // For floating-point precision of 12:
4472       //
4473       //   LogOfMantissa =
4474       //     -1.7417939f +
4475       //       (2.8212026f +
4476       //         (-1.4699568f +
4477       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4478       //
4479       // error 0.000061011436, which is 14 bits
4480       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4481                                getF32Constant(DAG, 0xbd67b6d6, dl));
4482       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4483                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4484       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4485       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4486                                getF32Constant(DAG, 0x3fbc278b, dl));
4487       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4488       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4489                                getF32Constant(DAG, 0x40348e95, dl));
4490       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4491       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4492                                   getF32Constant(DAG, 0x3fdef31a, dl));
4493     } else { // LimitFloatPrecision <= 18
4494       // For floating-point precision of 18:
4495       //
4496       //   LogOfMantissa =
4497       //     -2.1072184f +
4498       //       (4.2372794f +
4499       //         (-3.7029485f +
4500       //           (2.2781945f +
4501       //             (-0.87823314f +
4502       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4503       //
4504       // error 0.0000023660568, which is better than 18 bits
4505       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4506                                getF32Constant(DAG, 0xbc91e5ac, dl));
4507       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4508                                getF32Constant(DAG, 0x3e4350aa, dl));
4509       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4510       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4511                                getF32Constant(DAG, 0x3f60d3e3, dl));
4512       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4513       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4514                                getF32Constant(DAG, 0x4011cdf0, dl));
4515       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4516       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4517                                getF32Constant(DAG, 0x406cfd1c, dl));
4518       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4519       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4520                                getF32Constant(DAG, 0x408797cb, dl));
4521       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4522       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4523                                   getF32Constant(DAG, 0x4006dcab, dl));
4524     }
4525 
4526     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4527   }
4528 
4529   // No special expansion.
4530   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4531 }
4532 
4533 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4534 /// limited-precision mode.
4535 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4536                           const TargetLowering &TLI) {
4537   // TODO: What fast-math-flags should be set on the floating-point nodes?
4538 
4539   if (Op.getValueType() == MVT::f32 &&
4540       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4541     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4542 
4543     // Get the exponent.
4544     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4545 
4546     // Get the significand and build it into a floating-point number with
4547     // exponent of 1.
4548     SDValue X = GetSignificand(DAG, Op1, dl);
4549 
4550     // Different possible minimax approximations of significand in
4551     // floating-point for various degrees of accuracy over [1,2].
4552     SDValue Log2ofMantissa;
4553     if (LimitFloatPrecision <= 6) {
4554       // For floating-point precision of 6:
4555       //
4556       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4557       //
4558       // error 0.0049451742, which is more than 7 bits
4559       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4560                                getF32Constant(DAG, 0xbeb08fe0, dl));
4561       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4562                                getF32Constant(DAG, 0x40019463, dl));
4563       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4564       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4565                                    getF32Constant(DAG, 0x3fd6633d, dl));
4566     } else if (LimitFloatPrecision <= 12) {
4567       // For floating-point precision of 12:
4568       //
4569       //   Log2ofMantissa =
4570       //     -2.51285454f +
4571       //       (4.07009056f +
4572       //         (-2.12067489f +
4573       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4574       //
4575       // error 0.0000876136000, which is better than 13 bits
4576       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4577                                getF32Constant(DAG, 0xbda7262e, dl));
4578       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4579                                getF32Constant(DAG, 0x3f25280b, dl));
4580       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4581       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4582                                getF32Constant(DAG, 0x4007b923, dl));
4583       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4584       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4585                                getF32Constant(DAG, 0x40823e2f, dl));
4586       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4587       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4588                                    getF32Constant(DAG, 0x4020d29c, dl));
4589     } else { // LimitFloatPrecision <= 18
4590       // For floating-point precision of 18:
4591       //
4592       //   Log2ofMantissa =
4593       //     -3.0400495f +
4594       //       (6.1129976f +
4595       //         (-5.3420409f +
4596       //           (3.2865683f +
4597       //             (-1.2669343f +
4598       //               (0.27515199f -
4599       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4600       //
4601       // error 0.0000018516, which is better than 18 bits
4602       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4603                                getF32Constant(DAG, 0xbcd2769e, dl));
4604       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4605                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4606       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4607       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4608                                getF32Constant(DAG, 0x3fa22ae7, dl));
4609       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4610       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4611                                getF32Constant(DAG, 0x40525723, dl));
4612       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4613       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4614                                getF32Constant(DAG, 0x40aaf200, dl));
4615       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4616       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4617                                getF32Constant(DAG, 0x40c39dad, dl));
4618       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4619       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4620                                    getF32Constant(DAG, 0x4042902c, dl));
4621     }
4622 
4623     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4624   }
4625 
4626   // No special expansion.
4627   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4628 }
4629 
4630 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4631 /// limited-precision mode.
4632 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4633                            const TargetLowering &TLI) {
4634   // TODO: What fast-math-flags should be set on the floating-point nodes?
4635 
4636   if (Op.getValueType() == MVT::f32 &&
4637       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4638     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4639 
4640     // Scale the exponent by log10(2) [0.30102999f].
4641     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4642     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4643                                         getF32Constant(DAG, 0x3e9a209a, dl));
4644 
4645     // Get the significand and build it into a floating-point number with
4646     // exponent of 1.
4647     SDValue X = GetSignificand(DAG, Op1, dl);
4648 
4649     SDValue Log10ofMantissa;
4650     if (LimitFloatPrecision <= 6) {
4651       // For floating-point precision of 6:
4652       //
4653       //   Log10ofMantissa =
4654       //     -0.50419619f +
4655       //       (0.60948995f - 0.10380950f * x) * x;
4656       //
4657       // error 0.0014886165, which is 6 bits
4658       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4659                                getF32Constant(DAG, 0xbdd49a13, dl));
4660       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4661                                getF32Constant(DAG, 0x3f1c0789, dl));
4662       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4663       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4664                                     getF32Constant(DAG, 0x3f011300, dl));
4665     } else if (LimitFloatPrecision <= 12) {
4666       // For floating-point precision of 12:
4667       //
4668       //   Log10ofMantissa =
4669       //     -0.64831180f +
4670       //       (0.91751397f +
4671       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4672       //
4673       // error 0.00019228036, which is better than 12 bits
4674       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4675                                getF32Constant(DAG, 0x3d431f31, dl));
4676       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4677                                getF32Constant(DAG, 0x3ea21fb2, dl));
4678       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4679       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4680                                getF32Constant(DAG, 0x3f6ae232, dl));
4681       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4682       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4683                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4684     } else { // LimitFloatPrecision <= 18
4685       // For floating-point precision of 18:
4686       //
4687       //   Log10ofMantissa =
4688       //     -0.84299375f +
4689       //       (1.5327582f +
4690       //         (-1.0688956f +
4691       //           (0.49102474f +
4692       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4693       //
4694       // error 0.0000037995730, which is better than 18 bits
4695       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4696                                getF32Constant(DAG, 0x3c5d51ce, dl));
4697       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4698                                getF32Constant(DAG, 0x3e00685a, dl));
4699       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4700       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4701                                getF32Constant(DAG, 0x3efb6798, dl));
4702       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4703       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4704                                getF32Constant(DAG, 0x3f88d192, dl));
4705       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4706       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4707                                getF32Constant(DAG, 0x3fc4316c, dl));
4708       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4709       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4710                                     getF32Constant(DAG, 0x3f57ce70, dl));
4711     }
4712 
4713     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4714   }
4715 
4716   // No special expansion.
4717   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4718 }
4719 
4720 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4721 /// limited-precision mode.
4722 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4723                           const TargetLowering &TLI) {
4724   if (Op.getValueType() == MVT::f32 &&
4725       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4726     return getLimitedPrecisionExp2(Op, dl, DAG);
4727 
4728   // No special expansion.
4729   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4730 }
4731 
4732 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4733 /// limited-precision mode with x == 10.0f.
4734 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4735                          SelectionDAG &DAG, const TargetLowering &TLI) {
4736   bool IsExp10 = false;
4737   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4738       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4739     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4740       APFloat Ten(10.0f);
4741       IsExp10 = LHSC->isExactlyValue(Ten);
4742     }
4743   }
4744 
4745   // TODO: What fast-math-flags should be set on the FMUL node?
4746   if (IsExp10) {
4747     // Put the exponent in the right bit position for later addition to the
4748     // final result:
4749     //
4750     //   #define LOG2OF10 3.3219281f
4751     //   t0 = Op * LOG2OF10;
4752     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4753                              getF32Constant(DAG, 0x40549a78, dl));
4754     return getLimitedPrecisionExp2(t0, dl, DAG);
4755   }
4756 
4757   // No special expansion.
4758   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4759 }
4760 
4761 /// ExpandPowI - Expand a llvm.powi intrinsic.
4762 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4763                           SelectionDAG &DAG) {
4764   // If RHS is a constant, we can expand this out to a multiplication tree,
4765   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4766   // optimizing for size, we only want to do this if the expansion would produce
4767   // a small number of multiplies, otherwise we do the full expansion.
4768   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4769     // Get the exponent as a positive value.
4770     unsigned Val = RHSC->getSExtValue();
4771     if ((int)Val < 0) Val = -Val;
4772 
4773     // powi(x, 0) -> 1.0
4774     if (Val == 0)
4775       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4776 
4777     const Function &F = DAG.getMachineFunction().getFunction();
4778     if (!F.optForSize() ||
4779         // If optimizing for size, don't insert too many multiplies.
4780         // This inserts up to 5 multiplies.
4781         countPopulation(Val) + Log2_32(Val) < 7) {
4782       // We use the simple binary decomposition method to generate the multiply
4783       // sequence.  There are more optimal ways to do this (for example,
4784       // powi(x,15) generates one more multiply than it should), but this has
4785       // the benefit of being both really simple and much better than a libcall.
4786       SDValue Res;  // Logically starts equal to 1.0
4787       SDValue CurSquare = LHS;
4788       // TODO: Intrinsics should have fast-math-flags that propagate to these
4789       // nodes.
4790       while (Val) {
4791         if (Val & 1) {
4792           if (Res.getNode())
4793             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4794           else
4795             Res = CurSquare;  // 1.0*CurSquare.
4796         }
4797 
4798         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4799                                 CurSquare, CurSquare);
4800         Val >>= 1;
4801       }
4802 
4803       // If the original was negative, invert the result, producing 1/(x*x*x).
4804       if (RHSC->getSExtValue() < 0)
4805         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4806                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4807       return Res;
4808     }
4809   }
4810 
4811   // Otherwise, expand to a libcall.
4812   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4813 }
4814 
4815 // getUnderlyingArgReg - Find underlying register used for a truncated or
4816 // bitcasted argument.
4817 static unsigned getUnderlyingArgReg(const SDValue &N) {
4818   switch (N.getOpcode()) {
4819   case ISD::CopyFromReg:
4820     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4821   case ISD::BITCAST:
4822   case ISD::AssertZext:
4823   case ISD::AssertSext:
4824   case ISD::TRUNCATE:
4825     return getUnderlyingArgReg(N.getOperand(0));
4826   default:
4827     return 0;
4828   }
4829 }
4830 
4831 /// If the DbgValueInst is a dbg_value of a function argument, create the
4832 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
4833 /// instruction selection, they will be inserted to the entry BB.
4834 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4835     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4836     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
4837   const Argument *Arg = dyn_cast<Argument>(V);
4838   if (!Arg)
4839     return false;
4840 
4841   MachineFunction &MF = DAG.getMachineFunction();
4842   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4843 
4844   bool IsIndirect = false;
4845   Optional<MachineOperand> Op;
4846   // Some arguments' frame index is recorded during argument lowering.
4847   int FI = FuncInfo.getArgumentFrameIndex(Arg);
4848   if (FI != std::numeric_limits<int>::max())
4849     Op = MachineOperand::CreateFI(FI);
4850 
4851   if (!Op && N.getNode()) {
4852     unsigned Reg = getUnderlyingArgReg(N);
4853     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4854       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4855       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4856       if (PR)
4857         Reg = PR;
4858     }
4859     if (Reg) {
4860       Op = MachineOperand::CreateReg(Reg, false);
4861       IsIndirect = IsDbgDeclare;
4862     }
4863   }
4864 
4865   if (!Op && N.getNode())
4866     // Check if frame index is available.
4867     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4868       if (FrameIndexSDNode *FINode =
4869           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4870         Op = MachineOperand::CreateFI(FINode->getIndex());
4871 
4872   if (!Op) {
4873     // Check if ValueMap has reg number.
4874     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4875     if (VMI != FuncInfo.ValueMap.end()) {
4876       const auto &TLI = DAG.getTargetLoweringInfo();
4877       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
4878                        V->getType(), isABIRegCopy(V));
4879       unsigned NumRegs =
4880           std::accumulate(RFV.RegCount.begin(), RFV.RegCount.end(), 0);
4881       if (NumRegs > 1) {
4882         unsigned I = 0;
4883         unsigned Offset = 0;
4884         auto RegisterVT = RFV.RegVTs.begin();
4885         for (auto RegCount : RFV.RegCount) {
4886           unsigned RegisterSize = (RegisterVT++)->getSizeInBits();
4887           for (unsigned E = I + RegCount; I != E; ++I) {
4888             // The vregs are guaranteed to be allocated in sequence.
4889             Op = MachineOperand::CreateReg(VMI->second + I, false);
4890             auto FragmentExpr = DIExpression::createFragmentExpression(
4891                 Expr, Offset, RegisterSize);
4892             if (!FragmentExpr)
4893               continue;
4894             FuncInfo.ArgDbgValues.push_back(
4895                 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
4896                         Op->getReg(), Variable, *FragmentExpr));
4897             Offset += RegisterSize;
4898           }
4899         }
4900         return true;
4901       }
4902       Op = MachineOperand::CreateReg(VMI->second, false);
4903       IsIndirect = IsDbgDeclare;
4904     }
4905   }
4906 
4907   if (!Op)
4908     return false;
4909 
4910   assert(Variable->isValidLocationForIntrinsic(DL) &&
4911          "Expected inlined-at fields to agree");
4912   if (Op->isReg())
4913     FuncInfo.ArgDbgValues.push_back(
4914         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4915                 Op->getReg(), Variable, Expr));
4916   else
4917     FuncInfo.ArgDbgValues.push_back(
4918         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
4919             .add(*Op)
4920             .addImm(0)
4921             .addMetadata(Variable)
4922             .addMetadata(Expr));
4923 
4924   return true;
4925 }
4926 
4927 /// Return the appropriate SDDbgValue based on N.
4928 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
4929                                              DILocalVariable *Variable,
4930                                              DIExpression *Expr,
4931                                              const DebugLoc &dl,
4932                                              unsigned DbgSDNodeOrder) {
4933   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
4934     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
4935     // stack slot locations as such instead of as indirectly addressed
4936     // locations.
4937     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), dl,
4938                                      DbgSDNodeOrder);
4939   }
4940   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, dl,
4941                          DbgSDNodeOrder);
4942 }
4943 
4944 // VisualStudio defines setjmp as _setjmp
4945 #if defined(_MSC_VER) && defined(setjmp) && \
4946                          !defined(setjmp_undefined_for_msvc)
4947 #  pragma push_macro("setjmp")
4948 #  undef setjmp
4949 #  define setjmp_undefined_for_msvc
4950 #endif
4951 
4952 /// Lower the call to the specified intrinsic function. If we want to emit this
4953 /// as a call to a named external function, return the name. Otherwise, lower it
4954 /// and return null.
4955 const char *
4956 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4957   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4958   SDLoc sdl = getCurSDLoc();
4959   DebugLoc dl = getCurDebugLoc();
4960   SDValue Res;
4961 
4962   switch (Intrinsic) {
4963   default:
4964     // By default, turn this into a target intrinsic node.
4965     visitTargetIntrinsic(I, Intrinsic);
4966     return nullptr;
4967   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
4968   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
4969   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
4970   case Intrinsic::returnaddress:
4971     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
4972                              TLI.getPointerTy(DAG.getDataLayout()),
4973                              getValue(I.getArgOperand(0))));
4974     return nullptr;
4975   case Intrinsic::addressofreturnaddress:
4976     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
4977                              TLI.getPointerTy(DAG.getDataLayout())));
4978     return nullptr;
4979   case Intrinsic::frameaddress:
4980     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
4981                              TLI.getPointerTy(DAG.getDataLayout()),
4982                              getValue(I.getArgOperand(0))));
4983     return nullptr;
4984   case Intrinsic::read_register: {
4985     Value *Reg = I.getArgOperand(0);
4986     SDValue Chain = getRoot();
4987     SDValue RegName =
4988         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4989     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4990     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
4991       DAG.getVTList(VT, MVT::Other), Chain, RegName);
4992     setValue(&I, Res);
4993     DAG.setRoot(Res.getValue(1));
4994     return nullptr;
4995   }
4996   case Intrinsic::write_register: {
4997     Value *Reg = I.getArgOperand(0);
4998     Value *RegValue = I.getArgOperand(1);
4999     SDValue Chain = getRoot();
5000     SDValue RegName =
5001         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5002     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5003                             RegName, getValue(RegValue)));
5004     return nullptr;
5005   }
5006   case Intrinsic::setjmp:
5007     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5008   case Intrinsic::longjmp:
5009     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5010   case Intrinsic::memcpy: {
5011     SDValue Op1 = getValue(I.getArgOperand(0));
5012     SDValue Op2 = getValue(I.getArgOperand(1));
5013     SDValue Op3 = getValue(I.getArgOperand(2));
5014     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
5015     if (!Align)
5016       Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5017     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
5018     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5019     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5020                                false, isTC,
5021                                MachinePointerInfo(I.getArgOperand(0)),
5022                                MachinePointerInfo(I.getArgOperand(1)));
5023     updateDAGForMaybeTailCall(MC);
5024     return nullptr;
5025   }
5026   case Intrinsic::memset: {
5027     SDValue Op1 = getValue(I.getArgOperand(0));
5028     SDValue Op2 = getValue(I.getArgOperand(1));
5029     SDValue Op3 = getValue(I.getArgOperand(2));
5030     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
5031     if (!Align)
5032       Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
5033     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
5034     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5035     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5036                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5037     updateDAGForMaybeTailCall(MS);
5038     return nullptr;
5039   }
5040   case Intrinsic::memmove: {
5041     SDValue Op1 = getValue(I.getArgOperand(0));
5042     SDValue Op2 = getValue(I.getArgOperand(1));
5043     SDValue Op3 = getValue(I.getArgOperand(2));
5044     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
5045     if (!Align)
5046       Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
5047     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
5048     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5049     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5050                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5051                                 MachinePointerInfo(I.getArgOperand(1)));
5052     updateDAGForMaybeTailCall(MM);
5053     return nullptr;
5054   }
5055   case Intrinsic::memcpy_element_unordered_atomic: {
5056     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5057     SDValue Dst = getValue(MI.getRawDest());
5058     SDValue Src = getValue(MI.getRawSource());
5059     SDValue Length = getValue(MI.getLength());
5060 
5061     // Emit a library call.
5062     TargetLowering::ArgListTy Args;
5063     TargetLowering::ArgListEntry Entry;
5064     Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
5065     Entry.Node = Dst;
5066     Args.push_back(Entry);
5067 
5068     Entry.Node = Src;
5069     Args.push_back(Entry);
5070 
5071     Entry.Ty = MI.getLength()->getType();
5072     Entry.Node = Length;
5073     Args.push_back(Entry);
5074 
5075     uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
5076     RTLIB::Libcall LibraryCall =
5077         RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
5078     if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
5079       report_fatal_error("Unsupported element size");
5080 
5081     TargetLowering::CallLoweringInfo CLI(DAG);
5082     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5083         TLI.getLibcallCallingConv(LibraryCall),
5084         Type::getVoidTy(*DAG.getContext()),
5085         DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
5086                               TLI.getPointerTy(DAG.getDataLayout())),
5087         std::move(Args));
5088 
5089     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
5090     DAG.setRoot(CallResult.second);
5091     return nullptr;
5092   }
5093   case Intrinsic::memmove_element_unordered_atomic: {
5094     auto &MI = cast<AtomicMemMoveInst>(I);
5095     SDValue Dst = getValue(MI.getRawDest());
5096     SDValue Src = getValue(MI.getRawSource());
5097     SDValue Length = getValue(MI.getLength());
5098 
5099     // Emit a library call.
5100     TargetLowering::ArgListTy Args;
5101     TargetLowering::ArgListEntry Entry;
5102     Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
5103     Entry.Node = Dst;
5104     Args.push_back(Entry);
5105 
5106     Entry.Node = Src;
5107     Args.push_back(Entry);
5108 
5109     Entry.Ty = MI.getLength()->getType();
5110     Entry.Node = Length;
5111     Args.push_back(Entry);
5112 
5113     uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
5114     RTLIB::Libcall LibraryCall =
5115         RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
5116     if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
5117       report_fatal_error("Unsupported element size");
5118 
5119     TargetLowering::CallLoweringInfo CLI(DAG);
5120     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5121         TLI.getLibcallCallingConv(LibraryCall),
5122         Type::getVoidTy(*DAG.getContext()),
5123         DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
5124                               TLI.getPointerTy(DAG.getDataLayout())),
5125         std::move(Args));
5126 
5127     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
5128     DAG.setRoot(CallResult.second);
5129     return nullptr;
5130   }
5131   case Intrinsic::memset_element_unordered_atomic: {
5132     auto &MI = cast<AtomicMemSetInst>(I);
5133     SDValue Dst = getValue(MI.getRawDest());
5134     SDValue Val = getValue(MI.getValue());
5135     SDValue Length = getValue(MI.getLength());
5136 
5137     // Emit a library call.
5138     TargetLowering::ArgListTy Args;
5139     TargetLowering::ArgListEntry Entry;
5140     Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
5141     Entry.Node = Dst;
5142     Args.push_back(Entry);
5143 
5144     Entry.Ty = Type::getInt8Ty(*DAG.getContext());
5145     Entry.Node = Val;
5146     Args.push_back(Entry);
5147 
5148     Entry.Ty = MI.getLength()->getType();
5149     Entry.Node = Length;
5150     Args.push_back(Entry);
5151 
5152     uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
5153     RTLIB::Libcall LibraryCall =
5154         RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
5155     if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
5156       report_fatal_error("Unsupported element size");
5157 
5158     TargetLowering::CallLoweringInfo CLI(DAG);
5159     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5160         TLI.getLibcallCallingConv(LibraryCall),
5161         Type::getVoidTy(*DAG.getContext()),
5162         DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
5163                               TLI.getPointerTy(DAG.getDataLayout())),
5164         std::move(Args));
5165 
5166     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
5167     DAG.setRoot(CallResult.second);
5168     return nullptr;
5169   }
5170   case Intrinsic::dbg_addr:
5171   case Intrinsic::dbg_declare: {
5172     const DbgInfoIntrinsic &DI = cast<DbgInfoIntrinsic>(I);
5173     DILocalVariable *Variable = DI.getVariable();
5174     DIExpression *Expression = DI.getExpression();
5175     assert(Variable && "Missing variable");
5176 
5177     // Check if address has undef value.
5178     const Value *Address = DI.getVariableLocation();
5179     if (!Address || isa<UndefValue>(Address) ||
5180         (Address->use_empty() && !isa<Argument>(Address))) {
5181       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5182       return nullptr;
5183     }
5184 
5185     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5186 
5187     // Check if this variable can be described by a frame index, typically
5188     // either as a static alloca or a byval parameter.
5189     int FI = std::numeric_limits<int>::max();
5190     if (const auto *AI =
5191             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5192       if (AI->isStaticAlloca()) {
5193         auto I = FuncInfo.StaticAllocaMap.find(AI);
5194         if (I != FuncInfo.StaticAllocaMap.end())
5195           FI = I->second;
5196       }
5197     } else if (const auto *Arg = dyn_cast<Argument>(
5198                    Address->stripInBoundsConstantOffsets())) {
5199       FI = FuncInfo.getArgumentFrameIndex(Arg);
5200     }
5201 
5202     // llvm.dbg.addr is control dependent and always generates indirect
5203     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5204     // the MachineFunction variable table.
5205     if (FI != std::numeric_limits<int>::max()) {
5206       if (Intrinsic == Intrinsic::dbg_addr)
5207         DAG.AddDbgValue(DAG.getFrameIndexDbgValue(Variable, Expression, FI, dl,
5208                                                   SDNodeOrder),
5209                         getRoot().getNode(), isParameter);
5210       return nullptr;
5211     }
5212 
5213     SDValue &N = NodeMap[Address];
5214     if (!N.getNode() && isa<Argument>(Address))
5215       // Check unused arguments map.
5216       N = UnusedArgNodeMap[Address];
5217     SDDbgValue *SDV;
5218     if (N.getNode()) {
5219       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5220         Address = BCI->getOperand(0);
5221       // Parameters are handled specially.
5222       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5223       if (isParameter && FINode) {
5224         // Byval parameter. We have a frame index at this point.
5225         SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
5226                                         FINode->getIndex(), dl, SDNodeOrder);
5227       } else if (isa<Argument>(Address)) {
5228         // Address is an argument, so try to emit its dbg value using
5229         // virtual register info from the FuncInfo.ValueMap.
5230         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5231         return nullptr;
5232       } else {
5233         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5234                               true, dl, SDNodeOrder);
5235       }
5236       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5237     } else {
5238       // If Address is an argument then try to emit its dbg value using
5239       // virtual register info from the FuncInfo.ValueMap.
5240       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5241                                     N)) {
5242         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5243       }
5244     }
5245     return nullptr;
5246   }
5247   case Intrinsic::dbg_value: {
5248     const DbgValueInst &DI = cast<DbgValueInst>(I);
5249     assert(DI.getVariable() && "Missing variable");
5250 
5251     DILocalVariable *Variable = DI.getVariable();
5252     DIExpression *Expression = DI.getExpression();
5253     const Value *V = DI.getValue();
5254     if (!V)
5255       return nullptr;
5256 
5257     SDDbgValue *SDV;
5258     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
5259       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5260       DAG.AddDbgValue(SDV, nullptr, false);
5261       return nullptr;
5262     }
5263 
5264     // Do not use getValue() in here; we don't want to generate code at
5265     // this point if it hasn't been done yet.
5266     SDValue N = NodeMap[V];
5267     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5268       N = UnusedArgNodeMap[V];
5269     if (N.getNode()) {
5270       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5271         return nullptr;
5272       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5273       DAG.AddDbgValue(SDV, N.getNode(), false);
5274       return nullptr;
5275     }
5276 
5277     if (!V->use_empty() ) {
5278       // Do not call getValue(V) yet, as we don't want to generate code.
5279       // Remember it for later.
5280       DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
5281       DanglingDebugInfoMap[V] = DDI;
5282       return nullptr;
5283     }
5284 
5285     DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5286     DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5287     return nullptr;
5288   }
5289 
5290   case Intrinsic::eh_typeid_for: {
5291     // Find the type id for the given typeinfo.
5292     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5293     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5294     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5295     setValue(&I, Res);
5296     return nullptr;
5297   }
5298 
5299   case Intrinsic::eh_return_i32:
5300   case Intrinsic::eh_return_i64:
5301     DAG.getMachineFunction().setCallsEHReturn(true);
5302     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5303                             MVT::Other,
5304                             getControlRoot(),
5305                             getValue(I.getArgOperand(0)),
5306                             getValue(I.getArgOperand(1))));
5307     return nullptr;
5308   case Intrinsic::eh_unwind_init:
5309     DAG.getMachineFunction().setCallsUnwindInit(true);
5310     return nullptr;
5311   case Intrinsic::eh_dwarf_cfa:
5312     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5313                              TLI.getPointerTy(DAG.getDataLayout()),
5314                              getValue(I.getArgOperand(0))));
5315     return nullptr;
5316   case Intrinsic::eh_sjlj_callsite: {
5317     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5318     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5319     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5320     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5321 
5322     MMI.setCurrentCallSite(CI->getZExtValue());
5323     return nullptr;
5324   }
5325   case Intrinsic::eh_sjlj_functioncontext: {
5326     // Get and store the index of the function context.
5327     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5328     AllocaInst *FnCtx =
5329       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5330     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5331     MFI.setFunctionContextIndex(FI);
5332     return nullptr;
5333   }
5334   case Intrinsic::eh_sjlj_setjmp: {
5335     SDValue Ops[2];
5336     Ops[0] = getRoot();
5337     Ops[1] = getValue(I.getArgOperand(0));
5338     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5339                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5340     setValue(&I, Op.getValue(0));
5341     DAG.setRoot(Op.getValue(1));
5342     return nullptr;
5343   }
5344   case Intrinsic::eh_sjlj_longjmp:
5345     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5346                             getRoot(), getValue(I.getArgOperand(0))));
5347     return nullptr;
5348   case Intrinsic::eh_sjlj_setup_dispatch:
5349     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5350                             getRoot()));
5351     return nullptr;
5352   case Intrinsic::masked_gather:
5353     visitMaskedGather(I);
5354     return nullptr;
5355   case Intrinsic::masked_load:
5356     visitMaskedLoad(I);
5357     return nullptr;
5358   case Intrinsic::masked_scatter:
5359     visitMaskedScatter(I);
5360     return nullptr;
5361   case Intrinsic::masked_store:
5362     visitMaskedStore(I);
5363     return nullptr;
5364   case Intrinsic::masked_expandload:
5365     visitMaskedLoad(I, true /* IsExpanding */);
5366     return nullptr;
5367   case Intrinsic::masked_compressstore:
5368     visitMaskedStore(I, true /* IsCompressing */);
5369     return nullptr;
5370   case Intrinsic::x86_mmx_pslli_w:
5371   case Intrinsic::x86_mmx_pslli_d:
5372   case Intrinsic::x86_mmx_pslli_q:
5373   case Intrinsic::x86_mmx_psrli_w:
5374   case Intrinsic::x86_mmx_psrli_d:
5375   case Intrinsic::x86_mmx_psrli_q:
5376   case Intrinsic::x86_mmx_psrai_w:
5377   case Intrinsic::x86_mmx_psrai_d: {
5378     SDValue ShAmt = getValue(I.getArgOperand(1));
5379     if (isa<ConstantSDNode>(ShAmt)) {
5380       visitTargetIntrinsic(I, Intrinsic);
5381       return nullptr;
5382     }
5383     unsigned NewIntrinsic = 0;
5384     EVT ShAmtVT = MVT::v2i32;
5385     switch (Intrinsic) {
5386     case Intrinsic::x86_mmx_pslli_w:
5387       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5388       break;
5389     case Intrinsic::x86_mmx_pslli_d:
5390       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5391       break;
5392     case Intrinsic::x86_mmx_pslli_q:
5393       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5394       break;
5395     case Intrinsic::x86_mmx_psrli_w:
5396       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5397       break;
5398     case Intrinsic::x86_mmx_psrli_d:
5399       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5400       break;
5401     case Intrinsic::x86_mmx_psrli_q:
5402       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5403       break;
5404     case Intrinsic::x86_mmx_psrai_w:
5405       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5406       break;
5407     case Intrinsic::x86_mmx_psrai_d:
5408       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5409       break;
5410     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5411     }
5412 
5413     // The vector shift intrinsics with scalars uses 32b shift amounts but
5414     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5415     // to be zero.
5416     // We must do this early because v2i32 is not a legal type.
5417     SDValue ShOps[2];
5418     ShOps[0] = ShAmt;
5419     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5420     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5421     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5422     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5423     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5424                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5425                        getValue(I.getArgOperand(0)), ShAmt);
5426     setValue(&I, Res);
5427     return nullptr;
5428   }
5429   case Intrinsic::powi:
5430     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5431                             getValue(I.getArgOperand(1)), DAG));
5432     return nullptr;
5433   case Intrinsic::log:
5434     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5435     return nullptr;
5436   case Intrinsic::log2:
5437     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5438     return nullptr;
5439   case Intrinsic::log10:
5440     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5441     return nullptr;
5442   case Intrinsic::exp:
5443     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5444     return nullptr;
5445   case Intrinsic::exp2:
5446     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5447     return nullptr;
5448   case Intrinsic::pow:
5449     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5450                            getValue(I.getArgOperand(1)), DAG, TLI));
5451     return nullptr;
5452   case Intrinsic::sqrt:
5453   case Intrinsic::fabs:
5454   case Intrinsic::sin:
5455   case Intrinsic::cos:
5456   case Intrinsic::floor:
5457   case Intrinsic::ceil:
5458   case Intrinsic::trunc:
5459   case Intrinsic::rint:
5460   case Intrinsic::nearbyint:
5461   case Intrinsic::round:
5462   case Intrinsic::canonicalize: {
5463     unsigned Opcode;
5464     switch (Intrinsic) {
5465     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5466     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5467     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5468     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5469     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5470     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5471     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5472     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5473     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5474     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5475     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5476     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5477     }
5478 
5479     setValue(&I, DAG.getNode(Opcode, sdl,
5480                              getValue(I.getArgOperand(0)).getValueType(),
5481                              getValue(I.getArgOperand(0))));
5482     return nullptr;
5483   }
5484   case Intrinsic::minnum: {
5485     auto VT = getValue(I.getArgOperand(0)).getValueType();
5486     unsigned Opc =
5487         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
5488             ? ISD::FMINNAN
5489             : ISD::FMINNUM;
5490     setValue(&I, DAG.getNode(Opc, sdl, VT,
5491                              getValue(I.getArgOperand(0)),
5492                              getValue(I.getArgOperand(1))));
5493     return nullptr;
5494   }
5495   case Intrinsic::maxnum: {
5496     auto VT = getValue(I.getArgOperand(0)).getValueType();
5497     unsigned Opc =
5498         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
5499             ? ISD::FMAXNAN
5500             : ISD::FMAXNUM;
5501     setValue(&I, DAG.getNode(Opc, sdl, VT,
5502                              getValue(I.getArgOperand(0)),
5503                              getValue(I.getArgOperand(1))));
5504     return nullptr;
5505   }
5506   case Intrinsic::copysign:
5507     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5508                              getValue(I.getArgOperand(0)).getValueType(),
5509                              getValue(I.getArgOperand(0)),
5510                              getValue(I.getArgOperand(1))));
5511     return nullptr;
5512   case Intrinsic::fma:
5513     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5514                              getValue(I.getArgOperand(0)).getValueType(),
5515                              getValue(I.getArgOperand(0)),
5516                              getValue(I.getArgOperand(1)),
5517                              getValue(I.getArgOperand(2))));
5518     return nullptr;
5519   case Intrinsic::experimental_constrained_fadd:
5520   case Intrinsic::experimental_constrained_fsub:
5521   case Intrinsic::experimental_constrained_fmul:
5522   case Intrinsic::experimental_constrained_fdiv:
5523   case Intrinsic::experimental_constrained_frem:
5524   case Intrinsic::experimental_constrained_fma:
5525   case Intrinsic::experimental_constrained_sqrt:
5526   case Intrinsic::experimental_constrained_pow:
5527   case Intrinsic::experimental_constrained_powi:
5528   case Intrinsic::experimental_constrained_sin:
5529   case Intrinsic::experimental_constrained_cos:
5530   case Intrinsic::experimental_constrained_exp:
5531   case Intrinsic::experimental_constrained_exp2:
5532   case Intrinsic::experimental_constrained_log:
5533   case Intrinsic::experimental_constrained_log10:
5534   case Intrinsic::experimental_constrained_log2:
5535   case Intrinsic::experimental_constrained_rint:
5536   case Intrinsic::experimental_constrained_nearbyint:
5537     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5538     return nullptr;
5539   case Intrinsic::fmuladd: {
5540     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5541     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5542         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5543       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5544                                getValue(I.getArgOperand(0)).getValueType(),
5545                                getValue(I.getArgOperand(0)),
5546                                getValue(I.getArgOperand(1)),
5547                                getValue(I.getArgOperand(2))));
5548     } else {
5549       // TODO: Intrinsic calls should have fast-math-flags.
5550       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5551                                 getValue(I.getArgOperand(0)).getValueType(),
5552                                 getValue(I.getArgOperand(0)),
5553                                 getValue(I.getArgOperand(1)));
5554       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5555                                 getValue(I.getArgOperand(0)).getValueType(),
5556                                 Mul,
5557                                 getValue(I.getArgOperand(2)));
5558       setValue(&I, Add);
5559     }
5560     return nullptr;
5561   }
5562   case Intrinsic::convert_to_fp16:
5563     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5564                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5565                                          getValue(I.getArgOperand(0)),
5566                                          DAG.getTargetConstant(0, sdl,
5567                                                                MVT::i32))));
5568     return nullptr;
5569   case Intrinsic::convert_from_fp16:
5570     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5571                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5572                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5573                                          getValue(I.getArgOperand(0)))));
5574     return nullptr;
5575   case Intrinsic::pcmarker: {
5576     SDValue Tmp = getValue(I.getArgOperand(0));
5577     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5578     return nullptr;
5579   }
5580   case Intrinsic::readcyclecounter: {
5581     SDValue Op = getRoot();
5582     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5583                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5584     setValue(&I, Res);
5585     DAG.setRoot(Res.getValue(1));
5586     return nullptr;
5587   }
5588   case Intrinsic::bitreverse:
5589     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5590                              getValue(I.getArgOperand(0)).getValueType(),
5591                              getValue(I.getArgOperand(0))));
5592     return nullptr;
5593   case Intrinsic::bswap:
5594     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5595                              getValue(I.getArgOperand(0)).getValueType(),
5596                              getValue(I.getArgOperand(0))));
5597     return nullptr;
5598   case Intrinsic::cttz: {
5599     SDValue Arg = getValue(I.getArgOperand(0));
5600     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5601     EVT Ty = Arg.getValueType();
5602     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5603                              sdl, Ty, Arg));
5604     return nullptr;
5605   }
5606   case Intrinsic::ctlz: {
5607     SDValue Arg = getValue(I.getArgOperand(0));
5608     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5609     EVT Ty = Arg.getValueType();
5610     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5611                              sdl, Ty, Arg));
5612     return nullptr;
5613   }
5614   case Intrinsic::ctpop: {
5615     SDValue Arg = getValue(I.getArgOperand(0));
5616     EVT Ty = Arg.getValueType();
5617     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5618     return nullptr;
5619   }
5620   case Intrinsic::stacksave: {
5621     SDValue Op = getRoot();
5622     Res = DAG.getNode(
5623         ISD::STACKSAVE, sdl,
5624         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5625     setValue(&I, Res);
5626     DAG.setRoot(Res.getValue(1));
5627     return nullptr;
5628   }
5629   case Intrinsic::stackrestore:
5630     Res = getValue(I.getArgOperand(0));
5631     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5632     return nullptr;
5633   case Intrinsic::get_dynamic_area_offset: {
5634     SDValue Op = getRoot();
5635     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5636     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5637     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5638     // target.
5639     if (PtrTy != ResTy)
5640       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5641                          " intrinsic!");
5642     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5643                       Op);
5644     DAG.setRoot(Op);
5645     setValue(&I, Res);
5646     return nullptr;
5647   }
5648   case Intrinsic::stackguard: {
5649     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5650     MachineFunction &MF = DAG.getMachineFunction();
5651     const Module &M = *MF.getFunction().getParent();
5652     SDValue Chain = getRoot();
5653     if (TLI.useLoadStackGuardNode()) {
5654       Res = getLoadStackGuard(DAG, sdl, Chain);
5655     } else {
5656       const Value *Global = TLI.getSDagStackGuard(M);
5657       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5658       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5659                         MachinePointerInfo(Global, 0), Align,
5660                         MachineMemOperand::MOVolatile);
5661     }
5662     if (TLI.useStackGuardXorFP())
5663       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
5664     DAG.setRoot(Chain);
5665     setValue(&I, Res);
5666     return nullptr;
5667   }
5668   case Intrinsic::stackprotector: {
5669     // Emit code into the DAG to store the stack guard onto the stack.
5670     MachineFunction &MF = DAG.getMachineFunction();
5671     MachineFrameInfo &MFI = MF.getFrameInfo();
5672     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5673     SDValue Src, Chain = getRoot();
5674 
5675     if (TLI.useLoadStackGuardNode())
5676       Src = getLoadStackGuard(DAG, sdl, Chain);
5677     else
5678       Src = getValue(I.getArgOperand(0));   // The guard's value.
5679 
5680     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5681 
5682     int FI = FuncInfo.StaticAllocaMap[Slot];
5683     MFI.setStackProtectorIndex(FI);
5684 
5685     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5686 
5687     // Store the stack protector onto the stack.
5688     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5689                                                  DAG.getMachineFunction(), FI),
5690                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5691     setValue(&I, Res);
5692     DAG.setRoot(Res);
5693     return nullptr;
5694   }
5695   case Intrinsic::objectsize: {
5696     // If we don't know by now, we're never going to know.
5697     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5698 
5699     assert(CI && "Non-constant type in __builtin_object_size?");
5700 
5701     SDValue Arg = getValue(I.getCalledValue());
5702     EVT Ty = Arg.getValueType();
5703 
5704     if (CI->isZero())
5705       Res = DAG.getConstant(-1ULL, sdl, Ty);
5706     else
5707       Res = DAG.getConstant(0, sdl, Ty);
5708 
5709     setValue(&I, Res);
5710     return nullptr;
5711   }
5712   case Intrinsic::annotation:
5713   case Intrinsic::ptr_annotation:
5714   case Intrinsic::invariant_group_barrier:
5715     // Drop the intrinsic, but forward the value
5716     setValue(&I, getValue(I.getOperand(0)));
5717     return nullptr;
5718   case Intrinsic::assume:
5719   case Intrinsic::var_annotation:
5720   case Intrinsic::sideeffect:
5721     // Discard annotate attributes, assumptions, and artificial side-effects.
5722     return nullptr;
5723 
5724   case Intrinsic::codeview_annotation: {
5725     // Emit a label associated with this metadata.
5726     MachineFunction &MF = DAG.getMachineFunction();
5727     MCSymbol *Label =
5728         MF.getMMI().getContext().createTempSymbol("annotation", true);
5729     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
5730     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
5731     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
5732     DAG.setRoot(Res);
5733     return nullptr;
5734   }
5735 
5736   case Intrinsic::init_trampoline: {
5737     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5738 
5739     SDValue Ops[6];
5740     Ops[0] = getRoot();
5741     Ops[1] = getValue(I.getArgOperand(0));
5742     Ops[2] = getValue(I.getArgOperand(1));
5743     Ops[3] = getValue(I.getArgOperand(2));
5744     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5745     Ops[5] = DAG.getSrcValue(F);
5746 
5747     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5748 
5749     DAG.setRoot(Res);
5750     return nullptr;
5751   }
5752   case Intrinsic::adjust_trampoline:
5753     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5754                              TLI.getPointerTy(DAG.getDataLayout()),
5755                              getValue(I.getArgOperand(0))));
5756     return nullptr;
5757   case Intrinsic::gcroot: {
5758     assert(DAG.getMachineFunction().getFunction().hasGC() &&
5759            "only valid in functions with gc specified, enforced by Verifier");
5760     assert(GFI && "implied by previous");
5761     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5762     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5763 
5764     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5765     GFI->addStackRoot(FI->getIndex(), TypeMap);
5766     return nullptr;
5767   }
5768   case Intrinsic::gcread:
5769   case Intrinsic::gcwrite:
5770     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5771   case Intrinsic::flt_rounds:
5772     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5773     return nullptr;
5774 
5775   case Intrinsic::expect:
5776     // Just replace __builtin_expect(exp, c) with EXP.
5777     setValue(&I, getValue(I.getArgOperand(0)));
5778     return nullptr;
5779 
5780   case Intrinsic::debugtrap:
5781   case Intrinsic::trap: {
5782     StringRef TrapFuncName =
5783         I.getAttributes()
5784             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
5785             .getValueAsString();
5786     if (TrapFuncName.empty()) {
5787       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5788         ISD::TRAP : ISD::DEBUGTRAP;
5789       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5790       return nullptr;
5791     }
5792     TargetLowering::ArgListTy Args;
5793 
5794     TargetLowering::CallLoweringInfo CLI(DAG);
5795     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5796         CallingConv::C, I.getType(),
5797         DAG.getExternalSymbol(TrapFuncName.data(),
5798                               TLI.getPointerTy(DAG.getDataLayout())),
5799         std::move(Args));
5800 
5801     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5802     DAG.setRoot(Result.second);
5803     return nullptr;
5804   }
5805 
5806   case Intrinsic::uadd_with_overflow:
5807   case Intrinsic::sadd_with_overflow:
5808   case Intrinsic::usub_with_overflow:
5809   case Intrinsic::ssub_with_overflow:
5810   case Intrinsic::umul_with_overflow:
5811   case Intrinsic::smul_with_overflow: {
5812     ISD::NodeType Op;
5813     switch (Intrinsic) {
5814     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5815     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5816     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5817     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5818     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5819     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5820     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5821     }
5822     SDValue Op1 = getValue(I.getArgOperand(0));
5823     SDValue Op2 = getValue(I.getArgOperand(1));
5824 
5825     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5826     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5827     return nullptr;
5828   }
5829   case Intrinsic::prefetch: {
5830     SDValue Ops[5];
5831     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5832     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
5833     Ops[0] = DAG.getRoot();
5834     Ops[1] = getValue(I.getArgOperand(0));
5835     Ops[2] = getValue(I.getArgOperand(1));
5836     Ops[3] = getValue(I.getArgOperand(2));
5837     Ops[4] = getValue(I.getArgOperand(3));
5838     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5839                                              DAG.getVTList(MVT::Other), Ops,
5840                                              EVT::getIntegerVT(*Context, 8),
5841                                              MachinePointerInfo(I.getArgOperand(0)),
5842                                              0, /* align */
5843                                              Flags);
5844 
5845     // Chain the prefetch in parallell with any pending loads, to stay out of
5846     // the way of later optimizations.
5847     PendingLoads.push_back(Result);
5848     Result = getRoot();
5849     DAG.setRoot(Result);
5850     return nullptr;
5851   }
5852   case Intrinsic::lifetime_start:
5853   case Intrinsic::lifetime_end: {
5854     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5855     // Stack coloring is not enabled in O0, discard region information.
5856     if (TM.getOptLevel() == CodeGenOpt::None)
5857       return nullptr;
5858 
5859     SmallVector<Value *, 4> Allocas;
5860     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
5861 
5862     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5863            E = Allocas.end(); Object != E; ++Object) {
5864       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5865 
5866       // Could not find an Alloca.
5867       if (!LifetimeObject)
5868         continue;
5869 
5870       // First check that the Alloca is static, otherwise it won't have a
5871       // valid frame index.
5872       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5873       if (SI == FuncInfo.StaticAllocaMap.end())
5874         return nullptr;
5875 
5876       int FI = SI->second;
5877 
5878       SDValue Ops[2];
5879       Ops[0] = getRoot();
5880       Ops[1] =
5881           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
5882       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5883 
5884       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5885       DAG.setRoot(Res);
5886     }
5887     return nullptr;
5888   }
5889   case Intrinsic::invariant_start:
5890     // Discard region information.
5891     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
5892     return nullptr;
5893   case Intrinsic::invariant_end:
5894     // Discard region information.
5895     return nullptr;
5896   case Intrinsic::clear_cache:
5897     return TLI.getClearCacheBuiltinName();
5898   case Intrinsic::donothing:
5899     // ignore
5900     return nullptr;
5901   case Intrinsic::experimental_stackmap:
5902     visitStackmap(I);
5903     return nullptr;
5904   case Intrinsic::experimental_patchpoint_void:
5905   case Intrinsic::experimental_patchpoint_i64:
5906     visitPatchpoint(&I);
5907     return nullptr;
5908   case Intrinsic::experimental_gc_statepoint:
5909     LowerStatepoint(ImmutableStatepoint(&I));
5910     return nullptr;
5911   case Intrinsic::experimental_gc_result:
5912     visitGCResult(cast<GCResultInst>(I));
5913     return nullptr;
5914   case Intrinsic::experimental_gc_relocate:
5915     visitGCRelocate(cast<GCRelocateInst>(I));
5916     return nullptr;
5917   case Intrinsic::instrprof_increment:
5918     llvm_unreachable("instrprof failed to lower an increment");
5919   case Intrinsic::instrprof_value_profile:
5920     llvm_unreachable("instrprof failed to lower a value profiling call");
5921   case Intrinsic::localescape: {
5922     MachineFunction &MF = DAG.getMachineFunction();
5923     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5924 
5925     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
5926     // is the same on all targets.
5927     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
5928       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
5929       if (isa<ConstantPointerNull>(Arg))
5930         continue; // Skip null pointers. They represent a hole in index space.
5931       AllocaInst *Slot = cast<AllocaInst>(Arg);
5932       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
5933              "can only escape static allocas");
5934       int FI = FuncInfo.StaticAllocaMap[Slot];
5935       MCSymbol *FrameAllocSym =
5936           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5937               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
5938       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
5939               TII->get(TargetOpcode::LOCAL_ESCAPE))
5940           .addSym(FrameAllocSym)
5941           .addFrameIndex(FI);
5942     }
5943 
5944     return nullptr;
5945   }
5946 
5947   case Intrinsic::localrecover: {
5948     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
5949     MachineFunction &MF = DAG.getMachineFunction();
5950     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
5951 
5952     // Get the symbol that defines the frame offset.
5953     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
5954     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
5955     unsigned IdxVal =
5956         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
5957     MCSymbol *FrameAllocSym =
5958         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5959             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
5960 
5961     // Create a MCSymbol for the label to avoid any target lowering
5962     // that would make this PC relative.
5963     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
5964     SDValue OffsetVal =
5965         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
5966 
5967     // Add the offset to the FP.
5968     Value *FP = I.getArgOperand(1);
5969     SDValue FPVal = getValue(FP);
5970     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
5971     setValue(&I, Add);
5972 
5973     return nullptr;
5974   }
5975 
5976   case Intrinsic::eh_exceptionpointer:
5977   case Intrinsic::eh_exceptioncode: {
5978     // Get the exception pointer vreg, copy from it, and resize it to fit.
5979     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
5980     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
5981     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
5982     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
5983     SDValue N =
5984         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
5985     if (Intrinsic == Intrinsic::eh_exceptioncode)
5986       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
5987     setValue(&I, N);
5988     return nullptr;
5989   }
5990   case Intrinsic::xray_customevent: {
5991     // Here we want to make sure that the intrinsic behaves as if it has a
5992     // specific calling convention, and only for x86_64.
5993     // FIXME: Support other platforms later.
5994     const auto &Triple = DAG.getTarget().getTargetTriple();
5995     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
5996       return nullptr;
5997 
5998     SDLoc DL = getCurSDLoc();
5999     SmallVector<SDValue, 8> Ops;
6000 
6001     // We want to say that we always want the arguments in registers.
6002     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6003     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6004     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6005     SDValue Chain = getRoot();
6006     Ops.push_back(LogEntryVal);
6007     Ops.push_back(StrSizeVal);
6008     Ops.push_back(Chain);
6009 
6010     // We need to enforce the calling convention for the callsite, so that
6011     // argument ordering is enforced correctly, and that register allocation can
6012     // see that some registers may be assumed clobbered and have to preserve
6013     // them across calls to the intrinsic.
6014     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6015                                            DL, NodeTys, Ops);
6016     SDValue patchableNode = SDValue(MN, 0);
6017     DAG.setRoot(patchableNode);
6018     setValue(&I, patchableNode);
6019     return nullptr;
6020   }
6021   case Intrinsic::experimental_deoptimize:
6022     LowerDeoptimizeCall(&I);
6023     return nullptr;
6024 
6025   case Intrinsic::experimental_vector_reduce_fadd:
6026   case Intrinsic::experimental_vector_reduce_fmul:
6027   case Intrinsic::experimental_vector_reduce_add:
6028   case Intrinsic::experimental_vector_reduce_mul:
6029   case Intrinsic::experimental_vector_reduce_and:
6030   case Intrinsic::experimental_vector_reduce_or:
6031   case Intrinsic::experimental_vector_reduce_xor:
6032   case Intrinsic::experimental_vector_reduce_smax:
6033   case Intrinsic::experimental_vector_reduce_smin:
6034   case Intrinsic::experimental_vector_reduce_umax:
6035   case Intrinsic::experimental_vector_reduce_umin:
6036   case Intrinsic::experimental_vector_reduce_fmax:
6037   case Intrinsic::experimental_vector_reduce_fmin:
6038     visitVectorReduce(I, Intrinsic);
6039     return nullptr;
6040   }
6041 }
6042 
6043 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6044     const ConstrainedFPIntrinsic &FPI) {
6045   SDLoc sdl = getCurSDLoc();
6046   unsigned Opcode;
6047   switch (FPI.getIntrinsicID()) {
6048   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6049   case Intrinsic::experimental_constrained_fadd:
6050     Opcode = ISD::STRICT_FADD;
6051     break;
6052   case Intrinsic::experimental_constrained_fsub:
6053     Opcode = ISD::STRICT_FSUB;
6054     break;
6055   case Intrinsic::experimental_constrained_fmul:
6056     Opcode = ISD::STRICT_FMUL;
6057     break;
6058   case Intrinsic::experimental_constrained_fdiv:
6059     Opcode = ISD::STRICT_FDIV;
6060     break;
6061   case Intrinsic::experimental_constrained_frem:
6062     Opcode = ISD::STRICT_FREM;
6063     break;
6064   case Intrinsic::experimental_constrained_fma:
6065     Opcode = ISD::STRICT_FMA;
6066     break;
6067   case Intrinsic::experimental_constrained_sqrt:
6068     Opcode = ISD::STRICT_FSQRT;
6069     break;
6070   case Intrinsic::experimental_constrained_pow:
6071     Opcode = ISD::STRICT_FPOW;
6072     break;
6073   case Intrinsic::experimental_constrained_powi:
6074     Opcode = ISD::STRICT_FPOWI;
6075     break;
6076   case Intrinsic::experimental_constrained_sin:
6077     Opcode = ISD::STRICT_FSIN;
6078     break;
6079   case Intrinsic::experimental_constrained_cos:
6080     Opcode = ISD::STRICT_FCOS;
6081     break;
6082   case Intrinsic::experimental_constrained_exp:
6083     Opcode = ISD::STRICT_FEXP;
6084     break;
6085   case Intrinsic::experimental_constrained_exp2:
6086     Opcode = ISD::STRICT_FEXP2;
6087     break;
6088   case Intrinsic::experimental_constrained_log:
6089     Opcode = ISD::STRICT_FLOG;
6090     break;
6091   case Intrinsic::experimental_constrained_log10:
6092     Opcode = ISD::STRICT_FLOG10;
6093     break;
6094   case Intrinsic::experimental_constrained_log2:
6095     Opcode = ISD::STRICT_FLOG2;
6096     break;
6097   case Intrinsic::experimental_constrained_rint:
6098     Opcode = ISD::STRICT_FRINT;
6099     break;
6100   case Intrinsic::experimental_constrained_nearbyint:
6101     Opcode = ISD::STRICT_FNEARBYINT;
6102     break;
6103   }
6104   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6105   SDValue Chain = getRoot();
6106   SmallVector<EVT, 4> ValueVTs;
6107   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6108   ValueVTs.push_back(MVT::Other); // Out chain
6109 
6110   SDVTList VTs = DAG.getVTList(ValueVTs);
6111   SDValue Result;
6112   if (FPI.isUnaryOp())
6113     Result = DAG.getNode(Opcode, sdl, VTs,
6114                          { Chain, getValue(FPI.getArgOperand(0)) });
6115   else if (FPI.isTernaryOp())
6116     Result = DAG.getNode(Opcode, sdl, VTs,
6117                          { Chain, getValue(FPI.getArgOperand(0)),
6118                                   getValue(FPI.getArgOperand(1)),
6119                                   getValue(FPI.getArgOperand(2)) });
6120   else
6121     Result = DAG.getNode(Opcode, sdl, VTs,
6122                          { Chain, getValue(FPI.getArgOperand(0)),
6123                            getValue(FPI.getArgOperand(1))  });
6124 
6125   assert(Result.getNode()->getNumValues() == 2);
6126   SDValue OutChain = Result.getValue(1);
6127   DAG.setRoot(OutChain);
6128   SDValue FPResult = Result.getValue(0);
6129   setValue(&FPI, FPResult);
6130 }
6131 
6132 std::pair<SDValue, SDValue>
6133 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6134                                     const BasicBlock *EHPadBB) {
6135   MachineFunction &MF = DAG.getMachineFunction();
6136   MachineModuleInfo &MMI = MF.getMMI();
6137   MCSymbol *BeginLabel = nullptr;
6138 
6139   if (EHPadBB) {
6140     // Insert a label before the invoke call to mark the try range.  This can be
6141     // used to detect deletion of the invoke via the MachineModuleInfo.
6142     BeginLabel = MMI.getContext().createTempSymbol();
6143 
6144     // For SjLj, keep track of which landing pads go with which invokes
6145     // so as to maintain the ordering of pads in the LSDA.
6146     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6147     if (CallSiteIndex) {
6148       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6149       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6150 
6151       // Now that the call site is handled, stop tracking it.
6152       MMI.setCurrentCallSite(0);
6153     }
6154 
6155     // Both PendingLoads and PendingExports must be flushed here;
6156     // this call might not return.
6157     (void)getRoot();
6158     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6159 
6160     CLI.setChain(getRoot());
6161   }
6162   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6163   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6164 
6165   assert((CLI.IsTailCall || Result.second.getNode()) &&
6166          "Non-null chain expected with non-tail call!");
6167   assert((Result.second.getNode() || !Result.first.getNode()) &&
6168          "Null value expected with tail call!");
6169 
6170   if (!Result.second.getNode()) {
6171     // As a special case, a null chain means that a tail call has been emitted
6172     // and the DAG root is already updated.
6173     HasTailCall = true;
6174 
6175     // Since there's no actual continuation from this block, nothing can be
6176     // relying on us setting vregs for them.
6177     PendingExports.clear();
6178   } else {
6179     DAG.setRoot(Result.second);
6180   }
6181 
6182   if (EHPadBB) {
6183     // Insert a label at the end of the invoke call to mark the try range.  This
6184     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6185     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6186     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6187 
6188     // Inform MachineModuleInfo of range.
6189     if (MF.hasEHFunclets()) {
6190       assert(CLI.CS);
6191       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6192       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6193                                 BeginLabel, EndLabel);
6194     } else {
6195       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6196     }
6197   }
6198 
6199   return Result;
6200 }
6201 
6202 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6203                                       bool isTailCall,
6204                                       const BasicBlock *EHPadBB) {
6205   auto &DL = DAG.getDataLayout();
6206   FunctionType *FTy = CS.getFunctionType();
6207   Type *RetTy = CS.getType();
6208 
6209   TargetLowering::ArgListTy Args;
6210   Args.reserve(CS.arg_size());
6211 
6212   const Value *SwiftErrorVal = nullptr;
6213   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6214 
6215   // We can't tail call inside a function with a swifterror argument. Lowering
6216   // does not support this yet. It would have to move into the swifterror
6217   // register before the call.
6218   auto *Caller = CS.getInstruction()->getParent()->getParent();
6219   if (TLI.supportSwiftError() &&
6220       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6221     isTailCall = false;
6222 
6223   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6224        i != e; ++i) {
6225     TargetLowering::ArgListEntry Entry;
6226     const Value *V = *i;
6227 
6228     // Skip empty types
6229     if (V->getType()->isEmptyTy())
6230       continue;
6231 
6232     SDValue ArgNode = getValue(V);
6233     Entry.Node = ArgNode; Entry.Ty = V->getType();
6234 
6235     Entry.setAttributes(&CS, i - CS.arg_begin());
6236 
6237     // Use swifterror virtual register as input to the call.
6238     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6239       SwiftErrorVal = V;
6240       // We find the virtual register for the actual swifterror argument.
6241       // Instead of using the Value, we use the virtual register instead.
6242       Entry.Node = DAG.getRegister(FuncInfo
6243                                        .getOrCreateSwiftErrorVRegUseAt(
6244                                            CS.getInstruction(), FuncInfo.MBB, V)
6245                                        .first,
6246                                    EVT(TLI.getPointerTy(DL)));
6247     }
6248 
6249     Args.push_back(Entry);
6250 
6251     // If we have an explicit sret argument that is an Instruction, (i.e., it
6252     // might point to function-local memory), we can't meaningfully tail-call.
6253     if (Entry.IsSRet && isa<Instruction>(V))
6254       isTailCall = false;
6255   }
6256 
6257   // Check if target-independent constraints permit a tail call here.
6258   // Target-dependent constraints are checked within TLI->LowerCallTo.
6259   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6260     isTailCall = false;
6261 
6262   // Disable tail calls if there is an swifterror argument. Targets have not
6263   // been updated to support tail calls.
6264   if (TLI.supportSwiftError() && SwiftErrorVal)
6265     isTailCall = false;
6266 
6267   TargetLowering::CallLoweringInfo CLI(DAG);
6268   CLI.setDebugLoc(getCurSDLoc())
6269       .setChain(getRoot())
6270       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6271       .setTailCall(isTailCall)
6272       .setConvergent(CS.isConvergent());
6273   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6274 
6275   if (Result.first.getNode()) {
6276     const Instruction *Inst = CS.getInstruction();
6277     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6278     setValue(Inst, Result.first);
6279   }
6280 
6281   // The last element of CLI.InVals has the SDValue for swifterror return.
6282   // Here we copy it to a virtual register and update SwiftErrorMap for
6283   // book-keeping.
6284   if (SwiftErrorVal && TLI.supportSwiftError()) {
6285     // Get the last element of InVals.
6286     SDValue Src = CLI.InVals.back();
6287     unsigned VReg; bool CreatedVReg;
6288     std::tie(VReg, CreatedVReg) =
6289         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6290     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6291     // We update the virtual register for the actual swifterror argument.
6292     if (CreatedVReg)
6293       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6294     DAG.setRoot(CopyNode);
6295   }
6296 }
6297 
6298 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6299                              SelectionDAGBuilder &Builder) {
6300   // Check to see if this load can be trivially constant folded, e.g. if the
6301   // input is from a string literal.
6302   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6303     // Cast pointer to the type we really want to load.
6304     Type *LoadTy =
6305         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6306     if (LoadVT.isVector())
6307       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6308 
6309     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6310                                          PointerType::getUnqual(LoadTy));
6311 
6312     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6313             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6314       return Builder.getValue(LoadCst);
6315   }
6316 
6317   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6318   // still constant memory, the input chain can be the entry node.
6319   SDValue Root;
6320   bool ConstantMemory = false;
6321 
6322   // Do not serialize (non-volatile) loads of constant memory with anything.
6323   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6324     Root = Builder.DAG.getEntryNode();
6325     ConstantMemory = true;
6326   } else {
6327     // Do not serialize non-volatile loads against each other.
6328     Root = Builder.DAG.getRoot();
6329   }
6330 
6331   SDValue Ptr = Builder.getValue(PtrVal);
6332   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6333                                         Ptr, MachinePointerInfo(PtrVal),
6334                                         /* Alignment = */ 1);
6335 
6336   if (!ConstantMemory)
6337     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6338   return LoadVal;
6339 }
6340 
6341 /// Record the value for an instruction that produces an integer result,
6342 /// converting the type where necessary.
6343 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6344                                                   SDValue Value,
6345                                                   bool IsSigned) {
6346   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6347                                                     I.getType(), true);
6348   if (IsSigned)
6349     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6350   else
6351     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6352   setValue(&I, Value);
6353 }
6354 
6355 /// See if we can lower a memcmp call into an optimized form. If so, return
6356 /// true and lower it. Otherwise return false, and it will be lowered like a
6357 /// normal call.
6358 /// The caller already checked that \p I calls the appropriate LibFunc with a
6359 /// correct prototype.
6360 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6361   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6362   const Value *Size = I.getArgOperand(2);
6363   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6364   if (CSize && CSize->getZExtValue() == 0) {
6365     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6366                                                           I.getType(), true);
6367     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6368     return true;
6369   }
6370 
6371   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6372   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6373       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6374       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6375   if (Res.first.getNode()) {
6376     processIntegerCallValue(I, Res.first, true);
6377     PendingLoads.push_back(Res.second);
6378     return true;
6379   }
6380 
6381   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6382   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6383   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6384     return false;
6385 
6386   // If the target has a fast compare for the given size, it will return a
6387   // preferred load type for that size. Require that the load VT is legal and
6388   // that the target supports unaligned loads of that type. Otherwise, return
6389   // INVALID.
6390   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6391     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6392     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6393     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6394       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6395       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6396       // TODO: Check alignment of src and dest ptrs.
6397       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6398       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6399       if (!TLI.isTypeLegal(LVT) ||
6400           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6401           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6402         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6403     }
6404 
6405     return LVT;
6406   };
6407 
6408   // This turns into unaligned loads. We only do this if the target natively
6409   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6410   // we'll only produce a small number of byte loads.
6411   MVT LoadVT;
6412   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6413   switch (NumBitsToCompare) {
6414   default:
6415     return false;
6416   case 16:
6417     LoadVT = MVT::i16;
6418     break;
6419   case 32:
6420     LoadVT = MVT::i32;
6421     break;
6422   case 64:
6423   case 128:
6424   case 256:
6425     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6426     break;
6427   }
6428 
6429   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6430     return false;
6431 
6432   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6433   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6434 
6435   // Bitcast to a wide integer type if the loads are vectors.
6436   if (LoadVT.isVector()) {
6437     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6438     LoadL = DAG.getBitcast(CmpVT, LoadL);
6439     LoadR = DAG.getBitcast(CmpVT, LoadR);
6440   }
6441 
6442   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6443   processIntegerCallValue(I, Cmp, false);
6444   return true;
6445 }
6446 
6447 /// See if we can lower a memchr call into an optimized form. If so, return
6448 /// true and lower it. Otherwise return false, and it will be lowered like a
6449 /// normal call.
6450 /// The caller already checked that \p I calls the appropriate LibFunc with a
6451 /// correct prototype.
6452 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6453   const Value *Src = I.getArgOperand(0);
6454   const Value *Char = I.getArgOperand(1);
6455   const Value *Length = I.getArgOperand(2);
6456 
6457   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6458   std::pair<SDValue, SDValue> Res =
6459     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6460                                 getValue(Src), getValue(Char), getValue(Length),
6461                                 MachinePointerInfo(Src));
6462   if (Res.first.getNode()) {
6463     setValue(&I, Res.first);
6464     PendingLoads.push_back(Res.second);
6465     return true;
6466   }
6467 
6468   return false;
6469 }
6470 
6471 /// See if we can lower a mempcpy call into an optimized form. If so, return
6472 /// true and lower it. Otherwise return false, and it will be lowered like a
6473 /// normal call.
6474 /// The caller already checked that \p I calls the appropriate LibFunc with a
6475 /// correct prototype.
6476 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6477   SDValue Dst = getValue(I.getArgOperand(0));
6478   SDValue Src = getValue(I.getArgOperand(1));
6479   SDValue Size = getValue(I.getArgOperand(2));
6480 
6481   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6482   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6483   unsigned Align = std::min(DstAlign, SrcAlign);
6484   if (Align == 0) // Alignment of one or both could not be inferred.
6485     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6486 
6487   bool isVol = false;
6488   SDLoc sdl = getCurSDLoc();
6489 
6490   // In the mempcpy context we need to pass in a false value for isTailCall
6491   // because the return pointer needs to be adjusted by the size of
6492   // the copied memory.
6493   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6494                              false, /*isTailCall=*/false,
6495                              MachinePointerInfo(I.getArgOperand(0)),
6496                              MachinePointerInfo(I.getArgOperand(1)));
6497   assert(MC.getNode() != nullptr &&
6498          "** memcpy should not be lowered as TailCall in mempcpy context **");
6499   DAG.setRoot(MC);
6500 
6501   // Check if Size needs to be truncated or extended.
6502   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6503 
6504   // Adjust return pointer to point just past the last dst byte.
6505   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6506                                     Dst, Size);
6507   setValue(&I, DstPlusSize);
6508   return true;
6509 }
6510 
6511 /// See if we can lower a strcpy call into an optimized form.  If so, return
6512 /// true and lower it, otherwise return false and it will be lowered like a
6513 /// normal call.
6514 /// The caller already checked that \p I calls the appropriate LibFunc with a
6515 /// correct prototype.
6516 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6517   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6518 
6519   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6520   std::pair<SDValue, SDValue> Res =
6521     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6522                                 getValue(Arg0), getValue(Arg1),
6523                                 MachinePointerInfo(Arg0),
6524                                 MachinePointerInfo(Arg1), isStpcpy);
6525   if (Res.first.getNode()) {
6526     setValue(&I, Res.first);
6527     DAG.setRoot(Res.second);
6528     return true;
6529   }
6530 
6531   return false;
6532 }
6533 
6534 /// See if we can lower a strcmp call into an optimized form.  If so, return
6535 /// true and lower it, otherwise return false and it will be lowered like a
6536 /// normal call.
6537 /// The caller already checked that \p I calls the appropriate LibFunc with a
6538 /// correct prototype.
6539 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6540   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6541 
6542   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6543   std::pair<SDValue, SDValue> Res =
6544     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6545                                 getValue(Arg0), getValue(Arg1),
6546                                 MachinePointerInfo(Arg0),
6547                                 MachinePointerInfo(Arg1));
6548   if (Res.first.getNode()) {
6549     processIntegerCallValue(I, Res.first, true);
6550     PendingLoads.push_back(Res.second);
6551     return true;
6552   }
6553 
6554   return false;
6555 }
6556 
6557 /// See if we can lower a strlen call into an optimized form.  If so, return
6558 /// true and lower it, otherwise return false and it will be lowered like a
6559 /// normal call.
6560 /// The caller already checked that \p I calls the appropriate LibFunc with a
6561 /// correct prototype.
6562 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6563   const Value *Arg0 = I.getArgOperand(0);
6564 
6565   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6566   std::pair<SDValue, SDValue> Res =
6567     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6568                                 getValue(Arg0), MachinePointerInfo(Arg0));
6569   if (Res.first.getNode()) {
6570     processIntegerCallValue(I, Res.first, false);
6571     PendingLoads.push_back(Res.second);
6572     return true;
6573   }
6574 
6575   return false;
6576 }
6577 
6578 /// See if we can lower a strnlen call into an optimized form.  If so, return
6579 /// true and lower it, otherwise return false and it will be lowered like a
6580 /// normal call.
6581 /// The caller already checked that \p I calls the appropriate LibFunc with a
6582 /// correct prototype.
6583 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6584   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6585 
6586   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6587   std::pair<SDValue, SDValue> Res =
6588     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6589                                  getValue(Arg0), getValue(Arg1),
6590                                  MachinePointerInfo(Arg0));
6591   if (Res.first.getNode()) {
6592     processIntegerCallValue(I, Res.first, false);
6593     PendingLoads.push_back(Res.second);
6594     return true;
6595   }
6596 
6597   return false;
6598 }
6599 
6600 /// See if we can lower a unary floating-point operation into an SDNode with
6601 /// the specified Opcode.  If so, return true and lower it, otherwise return
6602 /// false and it will be lowered like a normal call.
6603 /// The caller already checked that \p I calls the appropriate LibFunc with a
6604 /// correct prototype.
6605 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6606                                               unsigned Opcode) {
6607   // We already checked this call's prototype; verify it doesn't modify errno.
6608   if (!I.onlyReadsMemory())
6609     return false;
6610 
6611   SDValue Tmp = getValue(I.getArgOperand(0));
6612   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6613   return true;
6614 }
6615 
6616 /// See if we can lower a binary floating-point operation into an SDNode with
6617 /// the specified Opcode. If so, return true and lower it. Otherwise return
6618 /// false, and it will be lowered like a normal call.
6619 /// The caller already checked that \p I calls the appropriate LibFunc with a
6620 /// correct prototype.
6621 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6622                                                unsigned Opcode) {
6623   // We already checked this call's prototype; verify it doesn't modify errno.
6624   if (!I.onlyReadsMemory())
6625     return false;
6626 
6627   SDValue Tmp0 = getValue(I.getArgOperand(0));
6628   SDValue Tmp1 = getValue(I.getArgOperand(1));
6629   EVT VT = Tmp0.getValueType();
6630   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6631   return true;
6632 }
6633 
6634 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6635   // Handle inline assembly differently.
6636   if (isa<InlineAsm>(I.getCalledValue())) {
6637     visitInlineAsm(&I);
6638     return;
6639   }
6640 
6641   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6642   computeUsesVAFloatArgument(I, MMI);
6643 
6644   const char *RenameFn = nullptr;
6645   if (Function *F = I.getCalledFunction()) {
6646     if (F->isDeclaration()) {
6647       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
6648         if (unsigned IID = II->getIntrinsicID(F)) {
6649           RenameFn = visitIntrinsicCall(I, IID);
6650           if (!RenameFn)
6651             return;
6652         }
6653       }
6654       if (Intrinsic::ID IID = F->getIntrinsicID()) {
6655         RenameFn = visitIntrinsicCall(I, IID);
6656         if (!RenameFn)
6657           return;
6658       }
6659     }
6660 
6661     // Check for well-known libc/libm calls.  If the function is internal, it
6662     // can't be a library call.  Don't do the check if marked as nobuiltin for
6663     // some reason or the call site requires strict floating point semantics.
6664     LibFunc Func;
6665     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
6666         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
6667         LibInfo->hasOptimizedCodeGen(Func)) {
6668       switch (Func) {
6669       default: break;
6670       case LibFunc_copysign:
6671       case LibFunc_copysignf:
6672       case LibFunc_copysignl:
6673         // We already checked this call's prototype; verify it doesn't modify
6674         // errno.
6675         if (I.onlyReadsMemory()) {
6676           SDValue LHS = getValue(I.getArgOperand(0));
6677           SDValue RHS = getValue(I.getArgOperand(1));
6678           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6679                                    LHS.getValueType(), LHS, RHS));
6680           return;
6681         }
6682         break;
6683       case LibFunc_fabs:
6684       case LibFunc_fabsf:
6685       case LibFunc_fabsl:
6686         if (visitUnaryFloatCall(I, ISD::FABS))
6687           return;
6688         break;
6689       case LibFunc_fmin:
6690       case LibFunc_fminf:
6691       case LibFunc_fminl:
6692         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6693           return;
6694         break;
6695       case LibFunc_fmax:
6696       case LibFunc_fmaxf:
6697       case LibFunc_fmaxl:
6698         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6699           return;
6700         break;
6701       case LibFunc_sin:
6702       case LibFunc_sinf:
6703       case LibFunc_sinl:
6704         if (visitUnaryFloatCall(I, ISD::FSIN))
6705           return;
6706         break;
6707       case LibFunc_cos:
6708       case LibFunc_cosf:
6709       case LibFunc_cosl:
6710         if (visitUnaryFloatCall(I, ISD::FCOS))
6711           return;
6712         break;
6713       case LibFunc_sqrt:
6714       case LibFunc_sqrtf:
6715       case LibFunc_sqrtl:
6716       case LibFunc_sqrt_finite:
6717       case LibFunc_sqrtf_finite:
6718       case LibFunc_sqrtl_finite:
6719         if (visitUnaryFloatCall(I, ISD::FSQRT))
6720           return;
6721         break;
6722       case LibFunc_floor:
6723       case LibFunc_floorf:
6724       case LibFunc_floorl:
6725         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6726           return;
6727         break;
6728       case LibFunc_nearbyint:
6729       case LibFunc_nearbyintf:
6730       case LibFunc_nearbyintl:
6731         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6732           return;
6733         break;
6734       case LibFunc_ceil:
6735       case LibFunc_ceilf:
6736       case LibFunc_ceill:
6737         if (visitUnaryFloatCall(I, ISD::FCEIL))
6738           return;
6739         break;
6740       case LibFunc_rint:
6741       case LibFunc_rintf:
6742       case LibFunc_rintl:
6743         if (visitUnaryFloatCall(I, ISD::FRINT))
6744           return;
6745         break;
6746       case LibFunc_round:
6747       case LibFunc_roundf:
6748       case LibFunc_roundl:
6749         if (visitUnaryFloatCall(I, ISD::FROUND))
6750           return;
6751         break;
6752       case LibFunc_trunc:
6753       case LibFunc_truncf:
6754       case LibFunc_truncl:
6755         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6756           return;
6757         break;
6758       case LibFunc_log2:
6759       case LibFunc_log2f:
6760       case LibFunc_log2l:
6761         if (visitUnaryFloatCall(I, ISD::FLOG2))
6762           return;
6763         break;
6764       case LibFunc_exp2:
6765       case LibFunc_exp2f:
6766       case LibFunc_exp2l:
6767         if (visitUnaryFloatCall(I, ISD::FEXP2))
6768           return;
6769         break;
6770       case LibFunc_memcmp:
6771         if (visitMemCmpCall(I))
6772           return;
6773         break;
6774       case LibFunc_mempcpy:
6775         if (visitMemPCpyCall(I))
6776           return;
6777         break;
6778       case LibFunc_memchr:
6779         if (visitMemChrCall(I))
6780           return;
6781         break;
6782       case LibFunc_strcpy:
6783         if (visitStrCpyCall(I, false))
6784           return;
6785         break;
6786       case LibFunc_stpcpy:
6787         if (visitStrCpyCall(I, true))
6788           return;
6789         break;
6790       case LibFunc_strcmp:
6791         if (visitStrCmpCall(I))
6792           return;
6793         break;
6794       case LibFunc_strlen:
6795         if (visitStrLenCall(I))
6796           return;
6797         break;
6798       case LibFunc_strnlen:
6799         if (visitStrNLenCall(I))
6800           return;
6801         break;
6802       }
6803     }
6804   }
6805 
6806   SDValue Callee;
6807   if (!RenameFn)
6808     Callee = getValue(I.getCalledValue());
6809   else
6810     Callee = DAG.getExternalSymbol(
6811         RenameFn,
6812         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6813 
6814   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
6815   // have to do anything here to lower funclet bundles.
6816   assert(!I.hasOperandBundlesOtherThan(
6817              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
6818          "Cannot lower calls with arbitrary operand bundles!");
6819 
6820   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
6821     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
6822   else
6823     // Check if we can potentially perform a tail call. More detailed checking
6824     // is be done within LowerCallTo, after more information about the call is
6825     // known.
6826     LowerCallTo(&I, Callee, I.isTailCall());
6827 }
6828 
6829 namespace {
6830 
6831 /// AsmOperandInfo - This contains information for each constraint that we are
6832 /// lowering.
6833 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6834 public:
6835   /// CallOperand - If this is the result output operand or a clobber
6836   /// this is null, otherwise it is the incoming operand to the CallInst.
6837   /// This gets modified as the asm is processed.
6838   SDValue CallOperand;
6839 
6840   /// AssignedRegs - If this is a register or register class operand, this
6841   /// contains the set of register corresponding to the operand.
6842   RegsForValue AssignedRegs;
6843 
6844   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6845     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
6846   }
6847 
6848   /// Whether or not this operand accesses memory
6849   bool hasMemory(const TargetLowering &TLI) const {
6850     // Indirect operand accesses access memory.
6851     if (isIndirect)
6852       return true;
6853 
6854     for (const auto &Code : Codes)
6855       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
6856         return true;
6857 
6858     return false;
6859   }
6860 
6861   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6862   /// corresponds to.  If there is no Value* for this operand, it returns
6863   /// MVT::Other.
6864   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
6865                            const DataLayout &DL) const {
6866     if (!CallOperandVal) return MVT::Other;
6867 
6868     if (isa<BasicBlock>(CallOperandVal))
6869       return TLI.getPointerTy(DL);
6870 
6871     llvm::Type *OpTy = CallOperandVal->getType();
6872 
6873     // FIXME: code duplicated from TargetLowering::ParseConstraints().
6874     // If this is an indirect operand, the operand is a pointer to the
6875     // accessed type.
6876     if (isIndirect) {
6877       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6878       if (!PtrTy)
6879         report_fatal_error("Indirect operand for inline asm not a pointer!");
6880       OpTy = PtrTy->getElementType();
6881     }
6882 
6883     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6884     if (StructType *STy = dyn_cast<StructType>(OpTy))
6885       if (STy->getNumElements() == 1)
6886         OpTy = STy->getElementType(0);
6887 
6888     // If OpTy is not a single value, it may be a struct/union that we
6889     // can tile with integers.
6890     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6891       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6892       switch (BitSize) {
6893       default: break;
6894       case 1:
6895       case 8:
6896       case 16:
6897       case 32:
6898       case 64:
6899       case 128:
6900         OpTy = IntegerType::get(Context, BitSize);
6901         break;
6902       }
6903     }
6904 
6905     return TLI.getValueType(DL, OpTy, true);
6906   }
6907 };
6908 
6909 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
6910 
6911 } // end anonymous namespace
6912 
6913 /// Make sure that the output operand \p OpInfo and its corresponding input
6914 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
6915 /// out).
6916 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
6917                                SDISelAsmOperandInfo &MatchingOpInfo,
6918                                SelectionDAG &DAG) {
6919   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
6920     return;
6921 
6922   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
6923   const auto &TLI = DAG.getTargetLoweringInfo();
6924 
6925   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6926       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6927                                        OpInfo.ConstraintVT);
6928   std::pair<unsigned, const TargetRegisterClass *> InputRC =
6929       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
6930                                        MatchingOpInfo.ConstraintVT);
6931   if ((OpInfo.ConstraintVT.isInteger() !=
6932        MatchingOpInfo.ConstraintVT.isInteger()) ||
6933       (MatchRC.second != InputRC.second)) {
6934     // FIXME: error out in a more elegant fashion
6935     report_fatal_error("Unsupported asm: input constraint"
6936                        " with a matching output constraint of"
6937                        " incompatible type!");
6938   }
6939   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
6940 }
6941 
6942 /// Get a direct memory input to behave well as an indirect operand.
6943 /// This may introduce stores, hence the need for a \p Chain.
6944 /// \return The (possibly updated) chain.
6945 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
6946                                         SDISelAsmOperandInfo &OpInfo,
6947                                         SelectionDAG &DAG) {
6948   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6949 
6950   // If we don't have an indirect input, put it in the constpool if we can,
6951   // otherwise spill it to a stack slot.
6952   // TODO: This isn't quite right. We need to handle these according to
6953   // the addressing mode that the constraint wants. Also, this may take
6954   // an additional register for the computation and we don't want that
6955   // either.
6956 
6957   // If the operand is a float, integer, or vector constant, spill to a
6958   // constant pool entry to get its address.
6959   const Value *OpVal = OpInfo.CallOperandVal;
6960   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6961       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6962     OpInfo.CallOperand = DAG.getConstantPool(
6963         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
6964     return Chain;
6965   }
6966 
6967   // Otherwise, create a stack slot and emit a store to it before the asm.
6968   Type *Ty = OpVal->getType();
6969   auto &DL = DAG.getDataLayout();
6970   uint64_t TySize = DL.getTypeAllocSize(Ty);
6971   unsigned Align = DL.getPrefTypeAlignment(Ty);
6972   MachineFunction &MF = DAG.getMachineFunction();
6973   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
6974   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
6975   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
6976                        MachinePointerInfo::getFixedStack(MF, SSFI));
6977   OpInfo.CallOperand = StackSlot;
6978 
6979   return Chain;
6980 }
6981 
6982 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6983 /// specified operand.  We prefer to assign virtual registers, to allow the
6984 /// register allocator to handle the assignment process.  However, if the asm
6985 /// uses features that we can't model on machineinstrs, we have SDISel do the
6986 /// allocation.  This produces generally horrible, but correct, code.
6987 ///
6988 ///   OpInfo describes the operand.
6989 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
6990                                  const SDLoc &DL,
6991                                  SDISelAsmOperandInfo &OpInfo) {
6992   LLVMContext &Context = *DAG.getContext();
6993 
6994   MachineFunction &MF = DAG.getMachineFunction();
6995   SmallVector<unsigned, 4> Regs;
6996   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
6997 
6998   // If this is a constraint for a single physreg, or a constraint for a
6999   // register class, find it.
7000   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
7001       TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode,
7002                                        OpInfo.ConstraintVT);
7003 
7004   unsigned NumRegs = 1;
7005   if (OpInfo.ConstraintVT != MVT::Other) {
7006     // If this is a FP input in an integer register (or visa versa) insert a bit
7007     // cast of the input value.  More generally, handle any case where the input
7008     // value disagrees with the register class we plan to stick this in.
7009     if (OpInfo.Type == InlineAsm::isInput && PhysReg.second &&
7010         !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
7011       // Try to convert to the first EVT that the reg class contains.  If the
7012       // types are identical size, use a bitcast to convert (e.g. two differing
7013       // vector types).
7014       MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
7015       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
7016         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
7017                                          RegVT, OpInfo.CallOperand);
7018         OpInfo.ConstraintVT = RegVT;
7019       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7020         // If the input is a FP value and we want it in FP registers, do a
7021         // bitcast to the corresponding integer type.  This turns an f64 value
7022         // into i64, which can be passed with two i32 values on a 32-bit
7023         // machine.
7024         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7025         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
7026                                          RegVT, OpInfo.CallOperand);
7027         OpInfo.ConstraintVT = RegVT;
7028       }
7029     }
7030 
7031     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7032   }
7033 
7034   MVT RegVT;
7035   EVT ValueVT = OpInfo.ConstraintVT;
7036 
7037   // If this is a constraint for a specific physical register, like {r17},
7038   // assign it now.
7039   if (unsigned AssignedReg = PhysReg.first) {
7040     const TargetRegisterClass *RC = PhysReg.second;
7041     if (OpInfo.ConstraintVT == MVT::Other)
7042       ValueVT = *TRI.legalclasstypes_begin(*RC);
7043 
7044     // Get the actual register value type.  This is important, because the user
7045     // may have asked for (e.g.) the AX register in i32 type.  We need to
7046     // remember that AX is actually i16 to get the right extension.
7047     RegVT = *TRI.legalclasstypes_begin(*RC);
7048 
7049     // This is a explicit reference to a physical register.
7050     Regs.push_back(AssignedReg);
7051 
7052     // If this is an expanded reference, add the rest of the regs to Regs.
7053     if (NumRegs != 1) {
7054       TargetRegisterClass::iterator I = RC->begin();
7055       for (; *I != AssignedReg; ++I)
7056         assert(I != RC->end() && "Didn't find reg!");
7057 
7058       // Already added the first reg.
7059       --NumRegs; ++I;
7060       for (; NumRegs; --NumRegs, ++I) {
7061         assert(I != RC->end() && "Ran out of registers to allocate!");
7062         Regs.push_back(*I);
7063       }
7064     }
7065 
7066     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7067     return;
7068   }
7069 
7070   // Otherwise, if this was a reference to an LLVM register class, create vregs
7071   // for this reference.
7072   if (const TargetRegisterClass *RC = PhysReg.second) {
7073     RegVT = *TRI.legalclasstypes_begin(*RC);
7074     if (OpInfo.ConstraintVT == MVT::Other)
7075       ValueVT = RegVT;
7076 
7077     // Create the appropriate number of virtual registers.
7078     MachineRegisterInfo &RegInfo = MF.getRegInfo();
7079     for (; NumRegs; --NumRegs)
7080       Regs.push_back(RegInfo.createVirtualRegister(RC));
7081 
7082     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7083     return;
7084   }
7085 
7086   // Otherwise, we couldn't allocate enough registers for this.
7087 }
7088 
7089 static unsigned
7090 findMatchingInlineAsmOperand(unsigned OperandNo,
7091                              const std::vector<SDValue> &AsmNodeOperands) {
7092   // Scan until we find the definition we already emitted of this operand.
7093   unsigned CurOp = InlineAsm::Op_FirstOperand;
7094   for (; OperandNo; --OperandNo) {
7095     // Advance to the next operand.
7096     unsigned OpFlag =
7097         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7098     assert((InlineAsm::isRegDefKind(OpFlag) ||
7099             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7100             InlineAsm::isMemKind(OpFlag)) &&
7101            "Skipped past definitions?");
7102     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7103   }
7104   return CurOp;
7105 }
7106 
7107 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
7108 /// \return true if it has succeeded, false otherwise
7109 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
7110                               MVT RegVT, SelectionDAG &DAG) {
7111   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7112   MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
7113   for (unsigned i = 0, e = NumRegs; i != e; ++i) {
7114     if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
7115       Regs.push_back(RegInfo.createVirtualRegister(RC));
7116     else
7117       return false;
7118   }
7119   return true;
7120 }
7121 
7122 namespace {
7123 
7124 class ExtraFlags {
7125   unsigned Flags = 0;
7126 
7127 public:
7128   explicit ExtraFlags(ImmutableCallSite CS) {
7129     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7130     if (IA->hasSideEffects())
7131       Flags |= InlineAsm::Extra_HasSideEffects;
7132     if (IA->isAlignStack())
7133       Flags |= InlineAsm::Extra_IsAlignStack;
7134     if (CS.isConvergent())
7135       Flags |= InlineAsm::Extra_IsConvergent;
7136     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7137   }
7138 
7139   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7140     // Ideally, we would only check against memory constraints.  However, the
7141     // meaning of an Other constraint can be target-specific and we can't easily
7142     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7143     // for Other constraints as well.
7144     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7145         OpInfo.ConstraintType == TargetLowering::C_Other) {
7146       if (OpInfo.Type == InlineAsm::isInput)
7147         Flags |= InlineAsm::Extra_MayLoad;
7148       else if (OpInfo.Type == InlineAsm::isOutput)
7149         Flags |= InlineAsm::Extra_MayStore;
7150       else if (OpInfo.Type == InlineAsm::isClobber)
7151         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7152     }
7153   }
7154 
7155   unsigned get() const { return Flags; }
7156 };
7157 
7158 } // end anonymous namespace
7159 
7160 /// visitInlineAsm - Handle a call to an InlineAsm object.
7161 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7162   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7163 
7164   /// ConstraintOperands - Information about all of the constraints.
7165   SDISelAsmOperandInfoVector ConstraintOperands;
7166 
7167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7168   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7169       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7170 
7171   bool hasMemory = false;
7172 
7173   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7174   ExtraFlags ExtraInfo(CS);
7175 
7176   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7177   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7178   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
7179     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
7180     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7181 
7182     MVT OpVT = MVT::Other;
7183 
7184     // Compute the value type for each operand.
7185     if (OpInfo.Type == InlineAsm::isInput ||
7186         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7187       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7188 
7189       // Process the call argument. BasicBlocks are labels, currently appearing
7190       // only in asm's.
7191       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7192         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7193       } else {
7194         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7195       }
7196 
7197       OpVT =
7198           OpInfo
7199               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7200               .getSimpleVT();
7201     }
7202 
7203     if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7204       // The return value of the call is this value.  As such, there is no
7205       // corresponding argument.
7206       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7207       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7208         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
7209                                       STy->getElementType(ResNo));
7210       } else {
7211         assert(ResNo == 0 && "Asm only has one result!");
7212         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7213       }
7214       ++ResNo;
7215     }
7216 
7217     OpInfo.ConstraintVT = OpVT;
7218 
7219     if (!hasMemory)
7220       hasMemory = OpInfo.hasMemory(TLI);
7221 
7222     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7223     // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
7224     auto TargetConstraint = TargetConstraints[i];
7225 
7226     // Compute the constraint code and ConstraintType to use.
7227     TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
7228 
7229     ExtraInfo.update(TargetConstraint);
7230   }
7231 
7232   SDValue Chain, Flag;
7233 
7234   // We won't need to flush pending loads if this asm doesn't touch
7235   // memory and is nonvolatile.
7236   if (hasMemory || IA->hasSideEffects())
7237     Chain = getRoot();
7238   else
7239     Chain = DAG.getRoot();
7240 
7241   // Second pass over the constraints: compute which constraint option to use
7242   // and assign registers to constraints that want a specific physreg.
7243   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7244     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7245 
7246     // If this is an output operand with a matching input operand, look up the
7247     // matching input. If their types mismatch, e.g. one is an integer, the
7248     // other is floating point, or their sizes are different, flag it as an
7249     // error.
7250     if (OpInfo.hasMatchingInput()) {
7251       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7252       patchMatchingInput(OpInfo, Input, DAG);
7253     }
7254 
7255     // Compute the constraint code and ConstraintType to use.
7256     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7257 
7258     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7259         OpInfo.Type == InlineAsm::isClobber)
7260       continue;
7261 
7262     // If this is a memory input, and if the operand is not indirect, do what we
7263     // need to to provide an address for the memory input.
7264     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7265         !OpInfo.isIndirect) {
7266       assert((OpInfo.isMultipleAlternative ||
7267               (OpInfo.Type == InlineAsm::isInput)) &&
7268              "Can only indirectify direct input operands!");
7269 
7270       // Memory operands really want the address of the value.
7271       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7272 
7273       // There is no longer a Value* corresponding to this operand.
7274       OpInfo.CallOperandVal = nullptr;
7275 
7276       // It is now an indirect operand.
7277       OpInfo.isIndirect = true;
7278     }
7279 
7280     // If this constraint is for a specific register, allocate it before
7281     // anything else.
7282     if (OpInfo.ConstraintType == TargetLowering::C_Register)
7283       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7284   }
7285 
7286   // Third pass - Loop over all of the operands, assigning virtual or physregs
7287   // to register class operands.
7288   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7289     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7290 
7291     // C_Register operands have already been allocated, Other/Memory don't need
7292     // to be.
7293     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
7294       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7295   }
7296 
7297   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7298   std::vector<SDValue> AsmNodeOperands;
7299   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7300   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7301       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7302 
7303   // If we have a !srcloc metadata node associated with it, we want to attach
7304   // this to the ultimately generated inline asm machineinstr.  To do this, we
7305   // pass in the third operand as this (potentially null) inline asm MDNode.
7306   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7307   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7308 
7309   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7310   // bits as operand 3.
7311   AsmNodeOperands.push_back(DAG.getTargetConstant(
7312       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7313 
7314   // Loop over all of the inputs, copying the operand values into the
7315   // appropriate registers and processing the output regs.
7316   RegsForValue RetValRegs;
7317 
7318   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
7319   std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
7320 
7321   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7322     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7323 
7324     switch (OpInfo.Type) {
7325     case InlineAsm::isOutput:
7326       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
7327           OpInfo.ConstraintType != TargetLowering::C_Register) {
7328         // Memory output, or 'other' output (e.g. 'X' constraint).
7329         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
7330 
7331         unsigned ConstraintID =
7332             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7333         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7334                "Failed to convert memory constraint code to constraint id.");
7335 
7336         // Add information to the INLINEASM node to know about this output.
7337         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7338         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7339         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7340                                                         MVT::i32));
7341         AsmNodeOperands.push_back(OpInfo.CallOperand);
7342         break;
7343       }
7344 
7345       // Otherwise, this is a register or register class output.
7346 
7347       // Copy the output from the appropriate register.  Find a register that
7348       // we can use.
7349       if (OpInfo.AssignedRegs.Regs.empty()) {
7350         emitInlineAsmError(
7351             CS, "couldn't allocate output register for constraint '" +
7352                     Twine(OpInfo.ConstraintCode) + "'");
7353         return;
7354       }
7355 
7356       // If this is an indirect operand, store through the pointer after the
7357       // asm.
7358       if (OpInfo.isIndirect) {
7359         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
7360                                                       OpInfo.CallOperandVal));
7361       } else {
7362         // This is the result value of the call.
7363         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7364         // Concatenate this output onto the outputs list.
7365         RetValRegs.append(OpInfo.AssignedRegs);
7366       }
7367 
7368       // Add information to the INLINEASM node to know that this register is
7369       // set.
7370       OpInfo.AssignedRegs
7371           .AddInlineAsmOperands(OpInfo.isEarlyClobber
7372                                     ? InlineAsm::Kind_RegDefEarlyClobber
7373                                     : InlineAsm::Kind_RegDef,
7374                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7375       break;
7376 
7377     case InlineAsm::isInput: {
7378       SDValue InOperandVal = OpInfo.CallOperand;
7379 
7380       if (OpInfo.isMatchingInputConstraint()) {
7381         // If this is required to match an output register we have already set,
7382         // just use its register.
7383         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7384                                                   AsmNodeOperands);
7385         unsigned OpFlag =
7386           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7387         if (InlineAsm::isRegDefKind(OpFlag) ||
7388             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7389           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7390           if (OpInfo.isIndirect) {
7391             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7392             emitInlineAsmError(CS, "inline asm not supported yet:"
7393                                    " don't know how to handle tied "
7394                                    "indirect register inputs");
7395             return;
7396           }
7397 
7398           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7399           SmallVector<unsigned, 4> Regs;
7400 
7401           if (!createVirtualRegs(Regs,
7402                                  InlineAsm::getNumOperandRegisters(OpFlag),
7403                                  RegVT, DAG)) {
7404             emitInlineAsmError(CS, "inline asm error: This value type register "
7405                                    "class is not natively supported!");
7406             return;
7407           }
7408 
7409           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7410 
7411           SDLoc dl = getCurSDLoc();
7412           // Use the produced MatchedRegs object to
7413           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7414                                     CS.getInstruction());
7415           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7416                                            true, OpInfo.getMatchedOperand(), dl,
7417                                            DAG, AsmNodeOperands);
7418           break;
7419         }
7420 
7421         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7422         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7423                "Unexpected number of operands");
7424         // Add information to the INLINEASM node to know about this input.
7425         // See InlineAsm.h isUseOperandTiedToDef.
7426         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7427         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7428                                                     OpInfo.getMatchedOperand());
7429         AsmNodeOperands.push_back(DAG.getTargetConstant(
7430             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7431         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7432         break;
7433       }
7434 
7435       // Treat indirect 'X' constraint as memory.
7436       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7437           OpInfo.isIndirect)
7438         OpInfo.ConstraintType = TargetLowering::C_Memory;
7439 
7440       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7441         std::vector<SDValue> Ops;
7442         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7443                                           Ops, DAG);
7444         if (Ops.empty()) {
7445           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7446                                      Twine(OpInfo.ConstraintCode) + "'");
7447           return;
7448         }
7449 
7450         // Add information to the INLINEASM node to know about this input.
7451         unsigned ResOpType =
7452           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7453         AsmNodeOperands.push_back(DAG.getTargetConstant(
7454             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7455         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7456         break;
7457       }
7458 
7459       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7460         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7461         assert(InOperandVal.getValueType() ==
7462                    TLI.getPointerTy(DAG.getDataLayout()) &&
7463                "Memory operands expect pointer values");
7464 
7465         unsigned ConstraintID =
7466             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7467         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7468                "Failed to convert memory constraint code to constraint id.");
7469 
7470         // Add information to the INLINEASM node to know about this input.
7471         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7472         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7473         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7474                                                         getCurSDLoc(),
7475                                                         MVT::i32));
7476         AsmNodeOperands.push_back(InOperandVal);
7477         break;
7478       }
7479 
7480       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7481               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7482              "Unknown constraint type!");
7483 
7484       // TODO: Support this.
7485       if (OpInfo.isIndirect) {
7486         emitInlineAsmError(
7487             CS, "Don't know how to handle indirect register inputs yet "
7488                 "for constraint '" +
7489                     Twine(OpInfo.ConstraintCode) + "'");
7490         return;
7491       }
7492 
7493       // Copy the input into the appropriate registers.
7494       if (OpInfo.AssignedRegs.Regs.empty()) {
7495         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7496                                    Twine(OpInfo.ConstraintCode) + "'");
7497         return;
7498       }
7499 
7500       SDLoc dl = getCurSDLoc();
7501 
7502       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7503                                         Chain, &Flag, CS.getInstruction());
7504 
7505       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7506                                                dl, DAG, AsmNodeOperands);
7507       break;
7508     }
7509     case InlineAsm::isClobber:
7510       // Add the clobbered value to the operand list, so that the register
7511       // allocator is aware that the physreg got clobbered.
7512       if (!OpInfo.AssignedRegs.Regs.empty())
7513         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7514                                                  false, 0, getCurSDLoc(), DAG,
7515                                                  AsmNodeOperands);
7516       break;
7517     }
7518   }
7519 
7520   // Finish up input operands.  Set the input chain and add the flag last.
7521   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7522   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7523 
7524   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7525                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7526   Flag = Chain.getValue(1);
7527 
7528   // If this asm returns a register value, copy the result from that register
7529   // and set it as the value of the call.
7530   if (!RetValRegs.Regs.empty()) {
7531     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7532                                              Chain, &Flag, CS.getInstruction());
7533 
7534     // FIXME: Why don't we do this for inline asms with MRVs?
7535     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
7536       EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7537 
7538       // If any of the results of the inline asm is a vector, it may have the
7539       // wrong width/num elts.  This can happen for register classes that can
7540       // contain multiple different value types.  The preg or vreg allocated may
7541       // not have the same VT as was expected.  Convert it to the right type
7542       // with bit_convert.
7543       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
7544         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
7545                           ResultType, Val);
7546 
7547       } else if (ResultType != Val.getValueType() &&
7548                  ResultType.isInteger() && Val.getValueType().isInteger()) {
7549         // If a result value was tied to an input value, the computed result may
7550         // have a wider width than the expected result.  Extract the relevant
7551         // portion.
7552         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
7553       }
7554 
7555       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
7556     }
7557 
7558     setValue(CS.getInstruction(), Val);
7559     // Don't need to use this as a chain in this case.
7560     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
7561       return;
7562   }
7563 
7564   std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
7565 
7566   // Process indirect outputs, first output all of the flagged copies out of
7567   // physregs.
7568   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
7569     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
7570     const Value *Ptr = IndirectStoresToEmit[i].second;
7571     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7572                                              Chain, &Flag, IA);
7573     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
7574   }
7575 
7576   // Emit the non-flagged stores from the physregs.
7577   SmallVector<SDValue, 8> OutChains;
7578   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
7579     SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
7580                                getValue(StoresToEmit[i].second),
7581                                MachinePointerInfo(StoresToEmit[i].second));
7582     OutChains.push_back(Val);
7583   }
7584 
7585   if (!OutChains.empty())
7586     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7587 
7588   DAG.setRoot(Chain);
7589 }
7590 
7591 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7592                                              const Twine &Message) {
7593   LLVMContext &Ctx = *DAG.getContext();
7594   Ctx.emitError(CS.getInstruction(), Message);
7595 
7596   // Make sure we leave the DAG in a valid state
7597   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7598   auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7599   setValue(CS.getInstruction(), DAG.getUNDEF(VT));
7600 }
7601 
7602 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
7603   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
7604                           MVT::Other, getRoot(),
7605                           getValue(I.getArgOperand(0)),
7606                           DAG.getSrcValue(I.getArgOperand(0))));
7607 }
7608 
7609 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
7610   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7611   const DataLayout &DL = DAG.getDataLayout();
7612   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7613                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
7614                            DAG.getSrcValue(I.getOperand(0)),
7615                            DL.getABITypeAlignment(I.getType()));
7616   setValue(&I, V);
7617   DAG.setRoot(V.getValue(1));
7618 }
7619 
7620 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
7621   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
7622                           MVT::Other, getRoot(),
7623                           getValue(I.getArgOperand(0)),
7624                           DAG.getSrcValue(I.getArgOperand(0))));
7625 }
7626 
7627 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
7628   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
7629                           MVT::Other, getRoot(),
7630                           getValue(I.getArgOperand(0)),
7631                           getValue(I.getArgOperand(1)),
7632                           DAG.getSrcValue(I.getArgOperand(0)),
7633                           DAG.getSrcValue(I.getArgOperand(1))));
7634 }
7635 
7636 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
7637                                                     const Instruction &I,
7638                                                     SDValue Op) {
7639   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
7640   if (!Range)
7641     return Op;
7642 
7643   ConstantRange CR = getConstantRangeFromMetadata(*Range);
7644   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
7645     return Op;
7646 
7647   APInt Lo = CR.getUnsignedMin();
7648   if (!Lo.isMinValue())
7649     return Op;
7650 
7651   APInt Hi = CR.getUnsignedMax();
7652   unsigned Bits = Hi.getActiveBits();
7653 
7654   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7655 
7656   SDLoc SL = getCurSDLoc();
7657 
7658   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
7659                              DAG.getValueType(SmallVT));
7660   unsigned NumVals = Op.getNode()->getNumValues();
7661   if (NumVals == 1)
7662     return ZExt;
7663 
7664   SmallVector<SDValue, 4> Ops;
7665 
7666   Ops.push_back(ZExt);
7667   for (unsigned I = 1; I != NumVals; ++I)
7668     Ops.push_back(Op.getValue(I));
7669 
7670   return DAG.getMergeValues(Ops, SL);
7671 }
7672 
7673 /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of
7674 /// the call being lowered.
7675 ///
7676 /// This is a helper for lowering intrinsics that follow a target calling
7677 /// convention or require stack pointer adjustment. Only a subset of the
7678 /// intrinsic's operands need to participate in the calling convention.
7679 void SelectionDAGBuilder::populateCallLoweringInfo(
7680     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
7681     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
7682     bool IsPatchPoint) {
7683   TargetLowering::ArgListTy Args;
7684   Args.reserve(NumArgs);
7685 
7686   // Populate the argument list.
7687   // Attributes for args start at offset 1, after the return attribute.
7688   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
7689        ArgI != ArgE; ++ArgI) {
7690     const Value *V = CS->getOperand(ArgI);
7691 
7692     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
7693 
7694     TargetLowering::ArgListEntry Entry;
7695     Entry.Node = getValue(V);
7696     Entry.Ty = V->getType();
7697     Entry.setAttributes(&CS, ArgIdx);
7698     Args.push_back(Entry);
7699   }
7700 
7701   CLI.setDebugLoc(getCurSDLoc())
7702       .setChain(getRoot())
7703       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
7704       .setDiscardResult(CS->use_empty())
7705       .setIsPatchPoint(IsPatchPoint);
7706 }
7707 
7708 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
7709 /// or patchpoint target node's operand list.
7710 ///
7711 /// Constants are converted to TargetConstants purely as an optimization to
7712 /// avoid constant materialization and register allocation.
7713 ///
7714 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
7715 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
7716 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
7717 /// address materialization and register allocation, but may also be required
7718 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
7719 /// alloca in the entry block, then the runtime may assume that the alloca's
7720 /// StackMap location can be read immediately after compilation and that the
7721 /// location is valid at any point during execution (this is similar to the
7722 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
7723 /// only available in a register, then the runtime would need to trap when
7724 /// execution reaches the StackMap in order to read the alloca's location.
7725 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
7726                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
7727                                 SelectionDAGBuilder &Builder) {
7728   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
7729     SDValue OpVal = Builder.getValue(CS.getArgument(i));
7730     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
7731       Ops.push_back(
7732         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
7733       Ops.push_back(
7734         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
7735     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
7736       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
7737       Ops.push_back(Builder.DAG.getTargetFrameIndex(
7738           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
7739     } else
7740       Ops.push_back(OpVal);
7741   }
7742 }
7743 
7744 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
7745 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7746   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7747   //                                  [live variables...])
7748 
7749   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
7750 
7751   SDValue Chain, InFlag, Callee, NullPtr;
7752   SmallVector<SDValue, 32> Ops;
7753 
7754   SDLoc DL = getCurSDLoc();
7755   Callee = getValue(CI.getCalledValue());
7756   NullPtr = DAG.getIntPtrConstant(0, DL, true);
7757 
7758   // The stackmap intrinsic only records the live variables (the arguemnts
7759   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7760   // intrinsic, this won't be lowered to a function call. This means we don't
7761   // have to worry about calling conventions and target specific lowering code.
7762   // Instead we perform the call lowering right here.
7763   //
7764   // chain, flag = CALLSEQ_START(chain, 0, 0)
7765   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7766   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7767   //
7768   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
7769   InFlag = Chain.getValue(1);
7770 
7771   // Add the <id> and <numBytes> constants.
7772   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7773   Ops.push_back(DAG.getTargetConstant(
7774                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
7775   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7776   Ops.push_back(DAG.getTargetConstant(
7777                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
7778                   MVT::i32));
7779 
7780   // Push live variables for the stack map.
7781   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
7782 
7783   // We are not pushing any register mask info here on the operands list,
7784   // because the stackmap doesn't clobber anything.
7785 
7786   // Push the chain and the glue flag.
7787   Ops.push_back(Chain);
7788   Ops.push_back(InFlag);
7789 
7790   // Create the STACKMAP node.
7791   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7792   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7793   Chain = SDValue(SM, 0);
7794   InFlag = Chain.getValue(1);
7795 
7796   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7797 
7798   // Stackmaps don't generate values, so nothing goes into the NodeMap.
7799 
7800   // Set the root to the target-lowered call chain.
7801   DAG.setRoot(Chain);
7802 
7803   // Inform the Frame Information that we have a stackmap in this function.
7804   FuncInfo.MF->getFrameInfo().setHasStackMap();
7805 }
7806 
7807 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
7808 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7809                                           const BasicBlock *EHPadBB) {
7810   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7811   //                                                 i32 <numBytes>,
7812   //                                                 i8* <target>,
7813   //                                                 i32 <numArgs>,
7814   //                                                 [Args...],
7815   //                                                 [live variables...])
7816 
7817   CallingConv::ID CC = CS.getCallingConv();
7818   bool IsAnyRegCC = CC == CallingConv::AnyReg;
7819   bool HasDef = !CS->getType()->isVoidTy();
7820   SDLoc dl = getCurSDLoc();
7821   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
7822 
7823   // Handle immediate and symbolic callees.
7824   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
7825     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
7826                                    /*isTarget=*/true);
7827   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
7828     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
7829                                          SDLoc(SymbolicCallee),
7830                                          SymbolicCallee->getValueType(0));
7831 
7832   // Get the real number of arguments participating in the call <numArgs>
7833   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7834   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7835 
7836   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7837   // Intrinsics include all meta-operands up to but not including CC.
7838   unsigned NumMetaOpers = PatchPointOpers::CCPos;
7839   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
7840          "Not enough arguments provided to the patchpoint intrinsic");
7841 
7842   // For AnyRegCC the arguments are lowered later on manually.
7843   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7844   Type *ReturnTy =
7845     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
7846 
7847   TargetLowering::CallLoweringInfo CLI(DAG);
7848   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
7849                            true);
7850   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7851 
7852   SDNode *CallEnd = Result.second.getNode();
7853   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7854     CallEnd = CallEnd->getOperand(0).getNode();
7855 
7856   /// Get a call instruction from the call sequence chain.
7857   /// Tail calls are not allowed.
7858   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7859          "Expected a callseq node.");
7860   SDNode *Call = CallEnd->getOperand(0).getNode();
7861   bool HasGlue = Call->getGluedNode();
7862 
7863   // Replace the target specific call node with the patchable intrinsic.
7864   SmallVector<SDValue, 8> Ops;
7865 
7866   // Add the <id> and <numBytes> constants.
7867   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
7868   Ops.push_back(DAG.getTargetConstant(
7869                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
7870   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
7871   Ops.push_back(DAG.getTargetConstant(
7872                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
7873                   MVT::i32));
7874 
7875   // Add the callee.
7876   Ops.push_back(Callee);
7877 
7878   // Adjust <numArgs> to account for any arguments that have been passed on the
7879   // stack instead.
7880   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7881   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7882   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
7883   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
7884 
7885   // Add the calling convention
7886   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
7887 
7888   // Add the arguments we omitted previously. The register allocator should
7889   // place these in any free register.
7890   if (IsAnyRegCC)
7891     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
7892       Ops.push_back(getValue(CS.getArgument(i)));
7893 
7894   // Push the arguments from the call instruction up to the register mask.
7895   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
7896   Ops.append(Call->op_begin() + 2, e);
7897 
7898   // Push live variables for the stack map.
7899   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
7900 
7901   // Push the register mask info.
7902   if (HasGlue)
7903     Ops.push_back(*(Call->op_end()-2));
7904   else
7905     Ops.push_back(*(Call->op_end()-1));
7906 
7907   // Push the chain (this is originally the first operand of the call, but
7908   // becomes now the last or second to last operand).
7909   Ops.push_back(*(Call->op_begin()));
7910 
7911   // Push the glue flag (last operand).
7912   if (HasGlue)
7913     Ops.push_back(*(Call->op_end()-1));
7914 
7915   SDVTList NodeTys;
7916   if (IsAnyRegCC && HasDef) {
7917     // Create the return types based on the intrinsic definition
7918     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7919     SmallVector<EVT, 3> ValueVTs;
7920     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7921     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
7922 
7923     // There is always a chain and a glue type at the end
7924     ValueVTs.push_back(MVT::Other);
7925     ValueVTs.push_back(MVT::Glue);
7926     NodeTys = DAG.getVTList(ValueVTs);
7927   } else
7928     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7929 
7930   // Replace the target specific call node with a PATCHPOINT node.
7931   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7932                                          dl, NodeTys, Ops);
7933 
7934   // Update the NodeMap.
7935   if (HasDef) {
7936     if (IsAnyRegCC)
7937       setValue(CS.getInstruction(), SDValue(MN, 0));
7938     else
7939       setValue(CS.getInstruction(), Result.first);
7940   }
7941 
7942   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7943   // call sequence. Furthermore the location of the chain and glue can change
7944   // when the AnyReg calling convention is used and the intrinsic returns a
7945   // value.
7946   if (IsAnyRegCC && HasDef) {
7947     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7948     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7949     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7950   } else
7951     DAG.ReplaceAllUsesWith(Call, MN);
7952   DAG.DeleteNode(Call);
7953 
7954   // Inform the Frame Information that we have a patchpoint in this function.
7955   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
7956 }
7957 
7958 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
7959                                             unsigned Intrinsic) {
7960   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7961   SDValue Op1 = getValue(I.getArgOperand(0));
7962   SDValue Op2;
7963   if (I.getNumArgOperands() > 1)
7964     Op2 = getValue(I.getArgOperand(1));
7965   SDLoc dl = getCurSDLoc();
7966   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7967   SDValue Res;
7968   FastMathFlags FMF;
7969   if (isa<FPMathOperator>(I))
7970     FMF = I.getFastMathFlags();
7971   SDNodeFlags SDFlags;
7972   SDFlags.setNoNaNs(FMF.noNaNs());
7973 
7974   switch (Intrinsic) {
7975   case Intrinsic::experimental_vector_reduce_fadd:
7976     if (FMF.isFast())
7977       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
7978     else
7979       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
7980     break;
7981   case Intrinsic::experimental_vector_reduce_fmul:
7982     if (FMF.isFast())
7983       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
7984     else
7985       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
7986     break;
7987   case Intrinsic::experimental_vector_reduce_add:
7988     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
7989     break;
7990   case Intrinsic::experimental_vector_reduce_mul:
7991     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
7992     break;
7993   case Intrinsic::experimental_vector_reduce_and:
7994     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
7995     break;
7996   case Intrinsic::experimental_vector_reduce_or:
7997     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
7998     break;
7999   case Intrinsic::experimental_vector_reduce_xor:
8000     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8001     break;
8002   case Intrinsic::experimental_vector_reduce_smax:
8003     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8004     break;
8005   case Intrinsic::experimental_vector_reduce_smin:
8006     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8007     break;
8008   case Intrinsic::experimental_vector_reduce_umax:
8009     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8010     break;
8011   case Intrinsic::experimental_vector_reduce_umin:
8012     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8013     break;
8014   case Intrinsic::experimental_vector_reduce_fmax:
8015     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
8016     break;
8017   case Intrinsic::experimental_vector_reduce_fmin:
8018     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
8019     break;
8020   default:
8021     llvm_unreachable("Unhandled vector reduce intrinsic");
8022   }
8023   setValue(&I, Res);
8024 }
8025 
8026 /// Returns an AttributeList representing the attributes applied to the return
8027 /// value of the given call.
8028 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8029   SmallVector<Attribute::AttrKind, 2> Attrs;
8030   if (CLI.RetSExt)
8031     Attrs.push_back(Attribute::SExt);
8032   if (CLI.RetZExt)
8033     Attrs.push_back(Attribute::ZExt);
8034   if (CLI.IsInReg)
8035     Attrs.push_back(Attribute::InReg);
8036 
8037   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8038                             Attrs);
8039 }
8040 
8041 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8042 /// implementation, which just calls LowerCall.
8043 /// FIXME: When all targets are
8044 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8045 std::pair<SDValue, SDValue>
8046 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8047   // Handle the incoming return values from the call.
8048   CLI.Ins.clear();
8049   Type *OrigRetTy = CLI.RetTy;
8050   SmallVector<EVT, 4> RetTys;
8051   SmallVector<uint64_t, 4> Offsets;
8052   auto &DL = CLI.DAG.getDataLayout();
8053   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8054 
8055   if (CLI.IsPostTypeLegalization) {
8056     // If we are lowering a libcall after legalization, split the return type.
8057     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8058     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8059     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8060       EVT RetVT = OldRetTys[i];
8061       uint64_t Offset = OldOffsets[i];
8062       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8063       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8064       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8065       RetTys.append(NumRegs, RegisterVT);
8066       for (unsigned j = 0; j != NumRegs; ++j)
8067         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8068     }
8069   }
8070 
8071   SmallVector<ISD::OutputArg, 4> Outs;
8072   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8073 
8074   bool CanLowerReturn =
8075       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8076                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8077 
8078   SDValue DemoteStackSlot;
8079   int DemoteStackIdx = -100;
8080   if (!CanLowerReturn) {
8081     // FIXME: equivalent assert?
8082     // assert(!CS.hasInAllocaArgument() &&
8083     //        "sret demotion is incompatible with inalloca");
8084     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8085     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8086     MachineFunction &MF = CLI.DAG.getMachineFunction();
8087     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8088     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
8089 
8090     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8091     ArgListEntry Entry;
8092     Entry.Node = DemoteStackSlot;
8093     Entry.Ty = StackSlotPtrType;
8094     Entry.IsSExt = false;
8095     Entry.IsZExt = false;
8096     Entry.IsInReg = false;
8097     Entry.IsSRet = true;
8098     Entry.IsNest = false;
8099     Entry.IsByVal = false;
8100     Entry.IsReturned = false;
8101     Entry.IsSwiftSelf = false;
8102     Entry.IsSwiftError = false;
8103     Entry.Alignment = Align;
8104     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8105     CLI.NumFixedArgs += 1;
8106     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8107 
8108     // sret demotion isn't compatible with tail-calls, since the sret argument
8109     // points into the callers stack frame.
8110     CLI.IsTailCall = false;
8111   } else {
8112     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8113       EVT VT = RetTys[I];
8114       MVT RegisterVT =
8115           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8116       unsigned NumRegs =
8117           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8118       for (unsigned i = 0; i != NumRegs; ++i) {
8119         ISD::InputArg MyFlags;
8120         MyFlags.VT = RegisterVT;
8121         MyFlags.ArgVT = VT;
8122         MyFlags.Used = CLI.IsReturnValueUsed;
8123         if (CLI.RetSExt)
8124           MyFlags.Flags.setSExt();
8125         if (CLI.RetZExt)
8126           MyFlags.Flags.setZExt();
8127         if (CLI.IsInReg)
8128           MyFlags.Flags.setInReg();
8129         CLI.Ins.push_back(MyFlags);
8130       }
8131     }
8132   }
8133 
8134   // We push in swifterror return as the last element of CLI.Ins.
8135   ArgListTy &Args = CLI.getArgs();
8136   if (supportSwiftError()) {
8137     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8138       if (Args[i].IsSwiftError) {
8139         ISD::InputArg MyFlags;
8140         MyFlags.VT = getPointerTy(DL);
8141         MyFlags.ArgVT = EVT(getPointerTy(DL));
8142         MyFlags.Flags.setSwiftError();
8143         CLI.Ins.push_back(MyFlags);
8144       }
8145     }
8146   }
8147 
8148   // Handle all of the outgoing arguments.
8149   CLI.Outs.clear();
8150   CLI.OutVals.clear();
8151   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8152     SmallVector<EVT, 4> ValueVTs;
8153     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8154     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8155     Type *FinalType = Args[i].Ty;
8156     if (Args[i].IsByVal)
8157       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8158     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8159         FinalType, CLI.CallConv, CLI.IsVarArg);
8160     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8161          ++Value) {
8162       EVT VT = ValueVTs[Value];
8163       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8164       SDValue Op = SDValue(Args[i].Node.getNode(),
8165                            Args[i].Node.getResNo() + Value);
8166       ISD::ArgFlagsTy Flags;
8167 
8168       // Certain targets (such as MIPS), may have a different ABI alignment
8169       // for a type depending on the context. Give the target a chance to
8170       // specify the alignment it wants.
8171       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8172 
8173       if (Args[i].IsZExt)
8174         Flags.setZExt();
8175       if (Args[i].IsSExt)
8176         Flags.setSExt();
8177       if (Args[i].IsInReg) {
8178         // If we are using vectorcall calling convention, a structure that is
8179         // passed InReg - is surely an HVA
8180         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8181             isa<StructType>(FinalType)) {
8182           // The first value of a structure is marked
8183           if (0 == Value)
8184             Flags.setHvaStart();
8185           Flags.setHva();
8186         }
8187         // Set InReg Flag
8188         Flags.setInReg();
8189       }
8190       if (Args[i].IsSRet)
8191         Flags.setSRet();
8192       if (Args[i].IsSwiftSelf)
8193         Flags.setSwiftSelf();
8194       if (Args[i].IsSwiftError)
8195         Flags.setSwiftError();
8196       if (Args[i].IsByVal)
8197         Flags.setByVal();
8198       if (Args[i].IsInAlloca) {
8199         Flags.setInAlloca();
8200         // Set the byval flag for CCAssignFn callbacks that don't know about
8201         // inalloca.  This way we can know how many bytes we should've allocated
8202         // and how many bytes a callee cleanup function will pop.  If we port
8203         // inalloca to more targets, we'll have to add custom inalloca handling
8204         // in the various CC lowering callbacks.
8205         Flags.setByVal();
8206       }
8207       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8208         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8209         Type *ElementTy = Ty->getElementType();
8210         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8211         // For ByVal, alignment should come from FE.  BE will guess if this
8212         // info is not there but there are cases it cannot get right.
8213         unsigned FrameAlign;
8214         if (Args[i].Alignment)
8215           FrameAlign = Args[i].Alignment;
8216         else
8217           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8218         Flags.setByValAlign(FrameAlign);
8219       }
8220       if (Args[i].IsNest)
8221         Flags.setNest();
8222       if (NeedsRegBlock)
8223         Flags.setInConsecutiveRegs();
8224       Flags.setOrigAlign(OriginalAlignment);
8225 
8226       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8227       unsigned NumParts =
8228           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8229       SmallVector<SDValue, 4> Parts(NumParts);
8230       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8231 
8232       if (Args[i].IsSExt)
8233         ExtendKind = ISD::SIGN_EXTEND;
8234       else if (Args[i].IsZExt)
8235         ExtendKind = ISD::ZERO_EXTEND;
8236 
8237       // Conservatively only handle 'returned' on non-vectors for now
8238       if (Args[i].IsReturned && !Op.getValueType().isVector()) {
8239         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8240                "unexpected use of 'returned'");
8241         // Before passing 'returned' to the target lowering code, ensure that
8242         // either the register MVT and the actual EVT are the same size or that
8243         // the return value and argument are extended in the same way; in these
8244         // cases it's safe to pass the argument register value unchanged as the
8245         // return register value (although it's at the target's option whether
8246         // to do so)
8247         // TODO: allow code generation to take advantage of partially preserved
8248         // registers rather than clobbering the entire register when the
8249         // parameter extension method is not compatible with the return
8250         // extension method
8251         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8252             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8253              CLI.RetZExt == Args[i].IsZExt))
8254           Flags.setReturned();
8255       }
8256 
8257       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8258                      CLI.CS.getInstruction(), ExtendKind, true);
8259 
8260       for (unsigned j = 0; j != NumParts; ++j) {
8261         // if it isn't first piece, alignment must be 1
8262         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8263                                i < CLI.NumFixedArgs,
8264                                i, j*Parts[j].getValueType().getStoreSize());
8265         if (NumParts > 1 && j == 0)
8266           MyFlags.Flags.setSplit();
8267         else if (j != 0) {
8268           MyFlags.Flags.setOrigAlign(1);
8269           if (j == NumParts - 1)
8270             MyFlags.Flags.setSplitEnd();
8271         }
8272 
8273         CLI.Outs.push_back(MyFlags);
8274         CLI.OutVals.push_back(Parts[j]);
8275       }
8276 
8277       if (NeedsRegBlock && Value == NumValues - 1)
8278         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8279     }
8280   }
8281 
8282   SmallVector<SDValue, 4> InVals;
8283   CLI.Chain = LowerCall(CLI, InVals);
8284 
8285   // Update CLI.InVals to use outside of this function.
8286   CLI.InVals = InVals;
8287 
8288   // Verify that the target's LowerCall behaved as expected.
8289   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8290          "LowerCall didn't return a valid chain!");
8291   assert((!CLI.IsTailCall || InVals.empty()) &&
8292          "LowerCall emitted a return value for a tail call!");
8293   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8294          "LowerCall didn't emit the correct number of values!");
8295 
8296   // For a tail call, the return value is merely live-out and there aren't
8297   // any nodes in the DAG representing it. Return a special value to
8298   // indicate that a tail call has been emitted and no more Instructions
8299   // should be processed in the current block.
8300   if (CLI.IsTailCall) {
8301     CLI.DAG.setRoot(CLI.Chain);
8302     return std::make_pair(SDValue(), SDValue());
8303   }
8304 
8305 #ifndef NDEBUG
8306   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8307     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8308     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8309            "LowerCall emitted a value with the wrong type!");
8310   }
8311 #endif
8312 
8313   SmallVector<SDValue, 4> ReturnValues;
8314   if (!CanLowerReturn) {
8315     // The instruction result is the result of loading from the
8316     // hidden sret parameter.
8317     SmallVector<EVT, 1> PVTs;
8318     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8319 
8320     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8321     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8322     EVT PtrVT = PVTs[0];
8323 
8324     unsigned NumValues = RetTys.size();
8325     ReturnValues.resize(NumValues);
8326     SmallVector<SDValue, 4> Chains(NumValues);
8327 
8328     // An aggregate return value cannot wrap around the address space, so
8329     // offsets to its parts don't wrap either.
8330     SDNodeFlags Flags;
8331     Flags.setNoUnsignedWrap(true);
8332 
8333     for (unsigned i = 0; i < NumValues; ++i) {
8334       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8335                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8336                                                         PtrVT), Flags);
8337       SDValue L = CLI.DAG.getLoad(
8338           RetTys[i], CLI.DL, CLI.Chain, Add,
8339           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8340                                             DemoteStackIdx, Offsets[i]),
8341           /* Alignment = */ 1);
8342       ReturnValues[i] = L;
8343       Chains[i] = L.getValue(1);
8344     }
8345 
8346     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8347   } else {
8348     // Collect the legal value parts into potentially illegal values
8349     // that correspond to the original function's return values.
8350     Optional<ISD::NodeType> AssertOp;
8351     if (CLI.RetSExt)
8352       AssertOp = ISD::AssertSext;
8353     else if (CLI.RetZExt)
8354       AssertOp = ISD::AssertZext;
8355     unsigned CurReg = 0;
8356     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8357       EVT VT = RetTys[I];
8358       MVT RegisterVT =
8359           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8360       unsigned NumRegs =
8361           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8362 
8363       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8364                                               NumRegs, RegisterVT, VT, nullptr,
8365                                               AssertOp, true));
8366       CurReg += NumRegs;
8367     }
8368 
8369     // For a function returning void, there is no return value. We can't create
8370     // such a node, so we just return a null return value in that case. In
8371     // that case, nothing will actually look at the value.
8372     if (ReturnValues.empty())
8373       return std::make_pair(SDValue(), CLI.Chain);
8374   }
8375 
8376   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8377                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8378   return std::make_pair(Res, CLI.Chain);
8379 }
8380 
8381 void TargetLowering::LowerOperationWrapper(SDNode *N,
8382                                            SmallVectorImpl<SDValue> &Results,
8383                                            SelectionDAG &DAG) const {
8384   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8385     Results.push_back(Res);
8386 }
8387 
8388 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8389   llvm_unreachable("LowerOperation not implemented for this target!");
8390 }
8391 
8392 void
8393 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8394   SDValue Op = getNonRegisterValue(V);
8395   assert((Op.getOpcode() != ISD::CopyFromReg ||
8396           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8397          "Copy from a reg to the same reg!");
8398   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8399 
8400   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8401   // If this is an InlineAsm we have to match the registers required, not the
8402   // notional registers required by the type.
8403 
8404   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
8405                    V->getType(), isABIRegCopy(V));
8406   SDValue Chain = DAG.getEntryNode();
8407 
8408   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8409                               FuncInfo.PreferredExtendType.end())
8410                                  ? ISD::ANY_EXTEND
8411                                  : FuncInfo.PreferredExtendType[V];
8412   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8413   PendingExports.push_back(Chain);
8414 }
8415 
8416 #include "llvm/CodeGen/SelectionDAGISel.h"
8417 
8418 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8419 /// entry block, return true.  This includes arguments used by switches, since
8420 /// the switch may expand into multiple basic blocks.
8421 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8422   // With FastISel active, we may be splitting blocks, so force creation
8423   // of virtual registers for all non-dead arguments.
8424   if (FastISel)
8425     return A->use_empty();
8426 
8427   const BasicBlock &Entry = A->getParent()->front();
8428   for (const User *U : A->users())
8429     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8430       return false;  // Use not in entry block.
8431 
8432   return true;
8433 }
8434 
8435 using ArgCopyElisionMapTy =
8436     DenseMap<const Argument *,
8437              std::pair<const AllocaInst *, const StoreInst *>>;
8438 
8439 /// Scan the entry block of the function in FuncInfo for arguments that look
8440 /// like copies into a local alloca. Record any copied arguments in
8441 /// ArgCopyElisionCandidates.
8442 static void
8443 findArgumentCopyElisionCandidates(const DataLayout &DL,
8444                                   FunctionLoweringInfo *FuncInfo,
8445                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8446   // Record the state of every static alloca used in the entry block. Argument
8447   // allocas are all used in the entry block, so we need approximately as many
8448   // entries as we have arguments.
8449   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8450   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8451   unsigned NumArgs = FuncInfo->Fn->arg_size();
8452   StaticAllocas.reserve(NumArgs * 2);
8453 
8454   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8455     if (!V)
8456       return nullptr;
8457     V = V->stripPointerCasts();
8458     const auto *AI = dyn_cast<AllocaInst>(V);
8459     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8460       return nullptr;
8461     auto Iter = StaticAllocas.insert({AI, Unknown});
8462     return &Iter.first->second;
8463   };
8464 
8465   // Look for stores of arguments to static allocas. Look through bitcasts and
8466   // GEPs to handle type coercions, as long as the alloca is fully initialized
8467   // by the store. Any non-store use of an alloca escapes it and any subsequent
8468   // unanalyzed store might write it.
8469   // FIXME: Handle structs initialized with multiple stores.
8470   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8471     // Look for stores, and handle non-store uses conservatively.
8472     const auto *SI = dyn_cast<StoreInst>(&I);
8473     if (!SI) {
8474       // We will look through cast uses, so ignore them completely.
8475       if (I.isCast())
8476         continue;
8477       // Ignore debug info intrinsics, they don't escape or store to allocas.
8478       if (isa<DbgInfoIntrinsic>(I))
8479         continue;
8480       // This is an unknown instruction. Assume it escapes or writes to all
8481       // static alloca operands.
8482       for (const Use &U : I.operands()) {
8483         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
8484           *Info = StaticAllocaInfo::Clobbered;
8485       }
8486       continue;
8487     }
8488 
8489     // If the stored value is a static alloca, mark it as escaped.
8490     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
8491       *Info = StaticAllocaInfo::Clobbered;
8492 
8493     // Check if the destination is a static alloca.
8494     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
8495     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
8496     if (!Info)
8497       continue;
8498     const AllocaInst *AI = cast<AllocaInst>(Dst);
8499 
8500     // Skip allocas that have been initialized or clobbered.
8501     if (*Info != StaticAllocaInfo::Unknown)
8502       continue;
8503 
8504     // Check if the stored value is an argument, and that this store fully
8505     // initializes the alloca. Don't elide copies from the same argument twice.
8506     const Value *Val = SI->getValueOperand()->stripPointerCasts();
8507     const auto *Arg = dyn_cast<Argument>(Val);
8508     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
8509         Arg->getType()->isEmptyTy() ||
8510         DL.getTypeStoreSize(Arg->getType()) !=
8511             DL.getTypeAllocSize(AI->getAllocatedType()) ||
8512         ArgCopyElisionCandidates.count(Arg)) {
8513       *Info = StaticAllocaInfo::Clobbered;
8514       continue;
8515     }
8516 
8517     DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI << '\n');
8518 
8519     // Mark this alloca and store for argument copy elision.
8520     *Info = StaticAllocaInfo::Elidable;
8521     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
8522 
8523     // Stop scanning if we've seen all arguments. This will happen early in -O0
8524     // builds, which is useful, because -O0 builds have large entry blocks and
8525     // many allocas.
8526     if (ArgCopyElisionCandidates.size() == NumArgs)
8527       break;
8528   }
8529 }
8530 
8531 /// Try to elide argument copies from memory into a local alloca. Succeeds if
8532 /// ArgVal is a load from a suitable fixed stack object.
8533 static void tryToElideArgumentCopy(
8534     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
8535     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
8536     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
8537     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
8538     SDValue ArgVal, bool &ArgHasUses) {
8539   // Check if this is a load from a fixed stack object.
8540   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
8541   if (!LNode)
8542     return;
8543   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
8544   if (!FINode)
8545     return;
8546 
8547   // Check that the fixed stack object is the right size and alignment.
8548   // Look at the alignment that the user wrote on the alloca instead of looking
8549   // at the stack object.
8550   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
8551   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
8552   const AllocaInst *AI = ArgCopyIter->second.first;
8553   int FixedIndex = FINode->getIndex();
8554   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
8555   int OldIndex = AllocaIndex;
8556   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
8557   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
8558     DEBUG(dbgs() << "  argument copy elision failed due to bad fixed stack "
8559                     "object size\n");
8560     return;
8561   }
8562   unsigned RequiredAlignment = AI->getAlignment();
8563   if (!RequiredAlignment) {
8564     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
8565         AI->getAllocatedType());
8566   }
8567   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
8568     DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
8569                     "greater than stack argument alignment ("
8570                  << RequiredAlignment << " vs "
8571                  << MFI.getObjectAlignment(FixedIndex) << ")\n");
8572     return;
8573   }
8574 
8575   // Perform the elision. Delete the old stack object and replace its only use
8576   // in the variable info map. Mark the stack object as mutable.
8577   DEBUG({
8578     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
8579            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
8580            << '\n';
8581   });
8582   MFI.RemoveStackObject(OldIndex);
8583   MFI.setIsImmutableObjectIndex(FixedIndex, false);
8584   AllocaIndex = FixedIndex;
8585   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
8586   Chains.push_back(ArgVal.getValue(1));
8587 
8588   // Avoid emitting code for the store implementing the copy.
8589   const StoreInst *SI = ArgCopyIter->second.second;
8590   ElidedArgCopyInstrs.insert(SI);
8591 
8592   // Check for uses of the argument again so that we can avoid exporting ArgVal
8593   // if it is't used by anything other than the store.
8594   for (const Value *U : Arg.users()) {
8595     if (U != SI) {
8596       ArgHasUses = true;
8597       break;
8598     }
8599   }
8600 }
8601 
8602 void SelectionDAGISel::LowerArguments(const Function &F) {
8603   SelectionDAG &DAG = SDB->DAG;
8604   SDLoc dl = SDB->getCurSDLoc();
8605   const DataLayout &DL = DAG.getDataLayout();
8606   SmallVector<ISD::InputArg, 16> Ins;
8607 
8608   if (!FuncInfo->CanLowerReturn) {
8609     // Put in an sret pointer parameter before all the other parameters.
8610     SmallVector<EVT, 1> ValueVTs;
8611     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8612                     F.getReturnType()->getPointerTo(
8613                         DAG.getDataLayout().getAllocaAddrSpace()),
8614                     ValueVTs);
8615 
8616     // NOTE: Assuming that a pointer will never break down to more than one VT
8617     // or one register.
8618     ISD::ArgFlagsTy Flags;
8619     Flags.setSRet();
8620     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
8621     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
8622                          ISD::InputArg::NoArgIndex, 0);
8623     Ins.push_back(RetArg);
8624   }
8625 
8626   // Look for stores of arguments to static allocas. Mark such arguments with a
8627   // flag to ask the target to give us the memory location of that argument if
8628   // available.
8629   ArgCopyElisionMapTy ArgCopyElisionCandidates;
8630   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
8631 
8632   // Set up the incoming argument description vector.
8633   for (const Argument &Arg : F.args()) {
8634     unsigned ArgNo = Arg.getArgNo();
8635     SmallVector<EVT, 4> ValueVTs;
8636     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8637     bool isArgValueUsed = !Arg.use_empty();
8638     unsigned PartBase = 0;
8639     Type *FinalType = Arg.getType();
8640     if (Arg.hasAttribute(Attribute::ByVal))
8641       FinalType = cast<PointerType>(FinalType)->getElementType();
8642     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
8643         FinalType, F.getCallingConv(), F.isVarArg());
8644     for (unsigned Value = 0, NumValues = ValueVTs.size();
8645          Value != NumValues; ++Value) {
8646       EVT VT = ValueVTs[Value];
8647       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
8648       ISD::ArgFlagsTy Flags;
8649 
8650       // Certain targets (such as MIPS), may have a different ABI alignment
8651       // for a type depending on the context. Give the target a chance to
8652       // specify the alignment it wants.
8653       unsigned OriginalAlignment =
8654           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
8655 
8656       if (Arg.hasAttribute(Attribute::ZExt))
8657         Flags.setZExt();
8658       if (Arg.hasAttribute(Attribute::SExt))
8659         Flags.setSExt();
8660       if (Arg.hasAttribute(Attribute::InReg)) {
8661         // If we are using vectorcall calling convention, a structure that is
8662         // passed InReg - is surely an HVA
8663         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
8664             isa<StructType>(Arg.getType())) {
8665           // The first value of a structure is marked
8666           if (0 == Value)
8667             Flags.setHvaStart();
8668           Flags.setHva();
8669         }
8670         // Set InReg Flag
8671         Flags.setInReg();
8672       }
8673       if (Arg.hasAttribute(Attribute::StructRet))
8674         Flags.setSRet();
8675       if (Arg.hasAttribute(Attribute::SwiftSelf))
8676         Flags.setSwiftSelf();
8677       if (Arg.hasAttribute(Attribute::SwiftError))
8678         Flags.setSwiftError();
8679       if (Arg.hasAttribute(Attribute::ByVal))
8680         Flags.setByVal();
8681       if (Arg.hasAttribute(Attribute::InAlloca)) {
8682         Flags.setInAlloca();
8683         // Set the byval flag for CCAssignFn callbacks that don't know about
8684         // inalloca.  This way we can know how many bytes we should've allocated
8685         // and how many bytes a callee cleanup function will pop.  If we port
8686         // inalloca to more targets, we'll have to add custom inalloca handling
8687         // in the various CC lowering callbacks.
8688         Flags.setByVal();
8689       }
8690       if (F.getCallingConv() == CallingConv::X86_INTR) {
8691         // IA Interrupt passes frame (1st parameter) by value in the stack.
8692         if (ArgNo == 0)
8693           Flags.setByVal();
8694       }
8695       if (Flags.isByVal() || Flags.isInAlloca()) {
8696         PointerType *Ty = cast<PointerType>(Arg.getType());
8697         Type *ElementTy = Ty->getElementType();
8698         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8699         // For ByVal, alignment should be passed from FE.  BE will guess if
8700         // this info is not there but there are cases it cannot get right.
8701         unsigned FrameAlign;
8702         if (Arg.getParamAlignment())
8703           FrameAlign = Arg.getParamAlignment();
8704         else
8705           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
8706         Flags.setByValAlign(FrameAlign);
8707       }
8708       if (Arg.hasAttribute(Attribute::Nest))
8709         Flags.setNest();
8710       if (NeedsRegBlock)
8711         Flags.setInConsecutiveRegs();
8712       Flags.setOrigAlign(OriginalAlignment);
8713       if (ArgCopyElisionCandidates.count(&Arg))
8714         Flags.setCopyElisionCandidate();
8715 
8716       MVT RegisterVT =
8717           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
8718       unsigned NumRegs =
8719           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
8720       for (unsigned i = 0; i != NumRegs; ++i) {
8721         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
8722                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
8723         if (NumRegs > 1 && i == 0)
8724           MyFlags.Flags.setSplit();
8725         // if it isn't first piece, alignment must be 1
8726         else if (i > 0) {
8727           MyFlags.Flags.setOrigAlign(1);
8728           if (i == NumRegs - 1)
8729             MyFlags.Flags.setSplitEnd();
8730         }
8731         Ins.push_back(MyFlags);
8732       }
8733       if (NeedsRegBlock && Value == NumValues - 1)
8734         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
8735       PartBase += VT.getStoreSize();
8736     }
8737   }
8738 
8739   // Call the target to set up the argument values.
8740   SmallVector<SDValue, 8> InVals;
8741   SDValue NewRoot = TLI->LowerFormalArguments(
8742       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
8743 
8744   // Verify that the target's LowerFormalArguments behaved as expected.
8745   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
8746          "LowerFormalArguments didn't return a valid chain!");
8747   assert(InVals.size() == Ins.size() &&
8748          "LowerFormalArguments didn't emit the correct number of values!");
8749   DEBUG({
8750       for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
8751         assert(InVals[i].getNode() &&
8752                "LowerFormalArguments emitted a null value!");
8753         assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
8754                "LowerFormalArguments emitted a value with the wrong type!");
8755       }
8756     });
8757 
8758   // Update the DAG with the new chain value resulting from argument lowering.
8759   DAG.setRoot(NewRoot);
8760 
8761   // Set up the argument values.
8762   unsigned i = 0;
8763   if (!FuncInfo->CanLowerReturn) {
8764     // Create a virtual register for the sret pointer, and put in a copy
8765     // from the sret argument into it.
8766     SmallVector<EVT, 1> ValueVTs;
8767     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8768                     F.getReturnType()->getPointerTo(
8769                         DAG.getDataLayout().getAllocaAddrSpace()),
8770                     ValueVTs);
8771     MVT VT = ValueVTs[0].getSimpleVT();
8772     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
8773     Optional<ISD::NodeType> AssertOp = None;
8774     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
8775                                         RegVT, VT, nullptr, AssertOp);
8776 
8777     MachineFunction& MF = SDB->DAG.getMachineFunction();
8778     MachineRegisterInfo& RegInfo = MF.getRegInfo();
8779     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
8780     FuncInfo->DemoteRegister = SRetReg;
8781     NewRoot =
8782         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
8783     DAG.setRoot(NewRoot);
8784 
8785     // i indexes lowered arguments.  Bump it past the hidden sret argument.
8786     ++i;
8787   }
8788 
8789   SmallVector<SDValue, 4> Chains;
8790   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
8791   for (const Argument &Arg : F.args()) {
8792     SmallVector<SDValue, 4> ArgValues;
8793     SmallVector<EVT, 4> ValueVTs;
8794     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8795     unsigned NumValues = ValueVTs.size();
8796     if (NumValues == 0)
8797       continue;
8798 
8799     bool ArgHasUses = !Arg.use_empty();
8800 
8801     // Elide the copying store if the target loaded this argument from a
8802     // suitable fixed stack object.
8803     if (Ins[i].Flags.isCopyElisionCandidate()) {
8804       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
8805                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
8806                              InVals[i], ArgHasUses);
8807     }
8808 
8809     // If this argument is unused then remember its value. It is used to generate
8810     // debugging information.
8811     bool isSwiftErrorArg =
8812         TLI->supportSwiftError() &&
8813         Arg.hasAttribute(Attribute::SwiftError);
8814     if (!ArgHasUses && !isSwiftErrorArg) {
8815       SDB->setUnusedArgValue(&Arg, InVals[i]);
8816 
8817       // Also remember any frame index for use in FastISel.
8818       if (FrameIndexSDNode *FI =
8819           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
8820         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8821     }
8822 
8823     for (unsigned Val = 0; Val != NumValues; ++Val) {
8824       EVT VT = ValueVTs[Val];
8825       MVT PartVT =
8826           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
8827       unsigned NumParts =
8828           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
8829 
8830       // Even an apparant 'unused' swifterror argument needs to be returned. So
8831       // we do generate a copy for it that can be used on return from the
8832       // function.
8833       if (ArgHasUses || isSwiftErrorArg) {
8834         Optional<ISD::NodeType> AssertOp;
8835         if (Arg.hasAttribute(Attribute::SExt))
8836           AssertOp = ISD::AssertSext;
8837         else if (Arg.hasAttribute(Attribute::ZExt))
8838           AssertOp = ISD::AssertZext;
8839 
8840         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
8841                                              PartVT, VT, nullptr, AssertOp,
8842                                              true));
8843       }
8844 
8845       i += NumParts;
8846     }
8847 
8848     // We don't need to do anything else for unused arguments.
8849     if (ArgValues.empty())
8850       continue;
8851 
8852     // Note down frame index.
8853     if (FrameIndexSDNode *FI =
8854         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
8855       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8856 
8857     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
8858                                      SDB->getCurSDLoc());
8859 
8860     SDB->setValue(&Arg, Res);
8861     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
8862       // We want to associate the argument with the frame index, among
8863       // involved operands, that correspond to the lowest address. The
8864       // getCopyFromParts function, called earlier, is swapping the order of
8865       // the operands to BUILD_PAIR depending on endianness. The result of
8866       // that swapping is that the least significant bits of the argument will
8867       // be in the first operand of the BUILD_PAIR node, and the most
8868       // significant bits will be in the second operand.
8869       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8870       if (LoadSDNode *LNode =
8871           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
8872         if (FrameIndexSDNode *FI =
8873             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
8874           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8875     }
8876 
8877     // Update the SwiftErrorVRegDefMap.
8878     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
8879       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
8880       if (TargetRegisterInfo::isVirtualRegister(Reg))
8881         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
8882                                            FuncInfo->SwiftErrorArg, Reg);
8883     }
8884 
8885     // If this argument is live outside of the entry block, insert a copy from
8886     // wherever we got it to the vreg that other BB's will reference it as.
8887     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
8888       // If we can, though, try to skip creating an unnecessary vreg.
8889       // FIXME: This isn't very clean... it would be nice to make this more
8890       // general.  It's also subtly incompatible with the hacks FastISel
8891       // uses with vregs.
8892       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
8893       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
8894         FuncInfo->ValueMap[&Arg] = Reg;
8895         continue;
8896       }
8897     }
8898     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
8899       FuncInfo->InitializeRegForValue(&Arg);
8900       SDB->CopyToExportRegsIfNeeded(&Arg);
8901     }
8902   }
8903 
8904   if (!Chains.empty()) {
8905     Chains.push_back(NewRoot);
8906     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
8907   }
8908 
8909   DAG.setRoot(NewRoot);
8910 
8911   assert(i == InVals.size() && "Argument register count mismatch!");
8912 
8913   // If any argument copy elisions occurred and we have debug info, update the
8914   // stale frame indices used in the dbg.declare variable info table.
8915   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
8916   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
8917     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
8918       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
8919       if (I != ArgCopyElisionFrameIndexMap.end())
8920         VI.Slot = I->second;
8921     }
8922   }
8923 
8924   // Finally, if the target has anything special to do, allow it to do so.
8925   EmitFunctionEntryCode();
8926 }
8927 
8928 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
8929 /// ensure constants are generated when needed.  Remember the virtual registers
8930 /// that need to be added to the Machine PHI nodes as input.  We cannot just
8931 /// directly add them, because expansion might result in multiple MBB's for one
8932 /// BB.  As such, the start of the BB might correspond to a different MBB than
8933 /// the end.
8934 void
8935 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
8936   const TerminatorInst *TI = LLVMBB->getTerminator();
8937 
8938   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
8939 
8940   // Check PHI nodes in successors that expect a value to be available from this
8941   // block.
8942   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
8943     const BasicBlock *SuccBB = TI->getSuccessor(succ);
8944     if (!isa<PHINode>(SuccBB->begin())) continue;
8945     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
8946 
8947     // If this terminator has multiple identical successors (common for
8948     // switches), only handle each succ once.
8949     if (!SuccsHandled.insert(SuccMBB).second)
8950       continue;
8951 
8952     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
8953 
8954     // At this point we know that there is a 1-1 correspondence between LLVM PHI
8955     // nodes and Machine PHI nodes, but the incoming operands have not been
8956     // emitted yet.
8957     for (const PHINode &PN : SuccBB->phis()) {
8958       // Ignore dead phi's.
8959       if (PN.use_empty())
8960         continue;
8961 
8962       // Skip empty types
8963       if (PN.getType()->isEmptyTy())
8964         continue;
8965 
8966       unsigned Reg;
8967       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
8968 
8969       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
8970         unsigned &RegOut = ConstantsOut[C];
8971         if (RegOut == 0) {
8972           RegOut = FuncInfo.CreateRegs(C->getType());
8973           CopyValueToVirtualRegister(C, RegOut);
8974         }
8975         Reg = RegOut;
8976       } else {
8977         DenseMap<const Value *, unsigned>::iterator I =
8978           FuncInfo.ValueMap.find(PHIOp);
8979         if (I != FuncInfo.ValueMap.end())
8980           Reg = I->second;
8981         else {
8982           assert(isa<AllocaInst>(PHIOp) &&
8983                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
8984                  "Didn't codegen value into a register!??");
8985           Reg = FuncInfo.CreateRegs(PHIOp->getType());
8986           CopyValueToVirtualRegister(PHIOp, Reg);
8987         }
8988       }
8989 
8990       // Remember that this register needs to added to the machine PHI node as
8991       // the input for this MBB.
8992       SmallVector<EVT, 4> ValueVTs;
8993       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8994       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
8995       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
8996         EVT VT = ValueVTs[vti];
8997         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
8998         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
8999           FuncInfo.PHINodesToUpdate.push_back(
9000               std::make_pair(&*MBBI++, Reg + i));
9001         Reg += NumRegisters;
9002       }
9003     }
9004   }
9005 
9006   ConstantsOut.clear();
9007 }
9008 
9009 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9010 /// is 0.
9011 MachineBasicBlock *
9012 SelectionDAGBuilder::StackProtectorDescriptor::
9013 AddSuccessorMBB(const BasicBlock *BB,
9014                 MachineBasicBlock *ParentMBB,
9015                 bool IsLikely,
9016                 MachineBasicBlock *SuccMBB) {
9017   // If SuccBB has not been created yet, create it.
9018   if (!SuccMBB) {
9019     MachineFunction *MF = ParentMBB->getParent();
9020     MachineFunction::iterator BBI(ParentMBB);
9021     SuccMBB = MF->CreateMachineBasicBlock(BB);
9022     MF->insert(++BBI, SuccMBB);
9023   }
9024   // Add it as a successor of ParentMBB.
9025   ParentMBB->addSuccessor(
9026       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9027   return SuccMBB;
9028 }
9029 
9030 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9031   MachineFunction::iterator I(MBB);
9032   if (++I == FuncInfo.MF->end())
9033     return nullptr;
9034   return &*I;
9035 }
9036 
9037 /// During lowering new call nodes can be created (such as memset, etc.).
9038 /// Those will become new roots of the current DAG, but complications arise
9039 /// when they are tail calls. In such cases, the call lowering will update
9040 /// the root, but the builder still needs to know that a tail call has been
9041 /// lowered in order to avoid generating an additional return.
9042 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9043   // If the node is null, we do have a tail call.
9044   if (MaybeTC.getNode() != nullptr)
9045     DAG.setRoot(MaybeTC);
9046   else
9047     HasTailCall = true;
9048 }
9049 
9050 uint64_t
9051 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9052                                        unsigned First, unsigned Last) const {
9053   assert(Last >= First);
9054   const APInt &LowCase = Clusters[First].Low->getValue();
9055   const APInt &HighCase = Clusters[Last].High->getValue();
9056   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9057 
9058   // FIXME: A range of consecutive cases has 100% density, but only requires one
9059   // comparison to lower. We should discriminate against such consecutive ranges
9060   // in jump tables.
9061 
9062   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9063 }
9064 
9065 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9066     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9067     unsigned Last) const {
9068   assert(Last >= First);
9069   assert(TotalCases[Last] >= TotalCases[First]);
9070   uint64_t NumCases =
9071       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9072   return NumCases;
9073 }
9074 
9075 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9076                                          unsigned First, unsigned Last,
9077                                          const SwitchInst *SI,
9078                                          MachineBasicBlock *DefaultMBB,
9079                                          CaseCluster &JTCluster) {
9080   assert(First <= Last);
9081 
9082   auto Prob = BranchProbability::getZero();
9083   unsigned NumCmps = 0;
9084   std::vector<MachineBasicBlock*> Table;
9085   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9086 
9087   // Initialize probabilities in JTProbs.
9088   for (unsigned I = First; I <= Last; ++I)
9089     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9090 
9091   for (unsigned I = First; I <= Last; ++I) {
9092     assert(Clusters[I].Kind == CC_Range);
9093     Prob += Clusters[I].Prob;
9094     const APInt &Low = Clusters[I].Low->getValue();
9095     const APInt &High = Clusters[I].High->getValue();
9096     NumCmps += (Low == High) ? 1 : 2;
9097     if (I != First) {
9098       // Fill the gap between this and the previous cluster.
9099       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9100       assert(PreviousHigh.slt(Low));
9101       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9102       for (uint64_t J = 0; J < Gap; J++)
9103         Table.push_back(DefaultMBB);
9104     }
9105     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9106     for (uint64_t J = 0; J < ClusterSize; ++J)
9107       Table.push_back(Clusters[I].MBB);
9108     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9109   }
9110 
9111   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9112   unsigned NumDests = JTProbs.size();
9113   if (TLI.isSuitableForBitTests(
9114           NumDests, NumCmps, Clusters[First].Low->getValue(),
9115           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9116     // Clusters[First..Last] should be lowered as bit tests instead.
9117     return false;
9118   }
9119 
9120   // Create the MBB that will load from and jump through the table.
9121   // Note: We create it here, but it's not inserted into the function yet.
9122   MachineFunction *CurMF = FuncInfo.MF;
9123   MachineBasicBlock *JumpTableMBB =
9124       CurMF->CreateMachineBasicBlock(SI->getParent());
9125 
9126   // Add successors. Note: use table order for determinism.
9127   SmallPtrSet<MachineBasicBlock *, 8> Done;
9128   for (MachineBasicBlock *Succ : Table) {
9129     if (Done.count(Succ))
9130       continue;
9131     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9132     Done.insert(Succ);
9133   }
9134   JumpTableMBB->normalizeSuccProbs();
9135 
9136   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9137                      ->createJumpTableIndex(Table);
9138 
9139   // Set up the jump table info.
9140   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9141   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9142                       Clusters[Last].High->getValue(), SI->getCondition(),
9143                       nullptr, false);
9144   JTCases.emplace_back(std::move(JTH), std::move(JT));
9145 
9146   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9147                                      JTCases.size() - 1, Prob);
9148   return true;
9149 }
9150 
9151 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9152                                          const SwitchInst *SI,
9153                                          MachineBasicBlock *DefaultMBB) {
9154 #ifndef NDEBUG
9155   // Clusters must be non-empty, sorted, and only contain Range clusters.
9156   assert(!Clusters.empty());
9157   for (CaseCluster &C : Clusters)
9158     assert(C.Kind == CC_Range);
9159   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9160     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9161 #endif
9162 
9163   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9164   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9165     return;
9166 
9167   const int64_t N = Clusters.size();
9168   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9169   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9170 
9171   if (N < 2 || N < MinJumpTableEntries)
9172     return;
9173 
9174   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9175   SmallVector<unsigned, 8> TotalCases(N);
9176   for (unsigned i = 0; i < N; ++i) {
9177     const APInt &Hi = Clusters[i].High->getValue();
9178     const APInt &Lo = Clusters[i].Low->getValue();
9179     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9180     if (i != 0)
9181       TotalCases[i] += TotalCases[i - 1];
9182   }
9183 
9184   // Cheap case: the whole range may be suitable for jump table.
9185   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9186   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9187   assert(NumCases < UINT64_MAX / 100);
9188   assert(Range >= NumCases);
9189   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9190     CaseCluster JTCluster;
9191     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9192       Clusters[0] = JTCluster;
9193       Clusters.resize(1);
9194       return;
9195     }
9196   }
9197 
9198   // The algorithm below is not suitable for -O0.
9199   if (TM.getOptLevel() == CodeGenOpt::None)
9200     return;
9201 
9202   // Split Clusters into minimum number of dense partitions. The algorithm uses
9203   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9204   // for the Case Statement'" (1994), but builds the MinPartitions array in
9205   // reverse order to make it easier to reconstruct the partitions in ascending
9206   // order. In the choice between two optimal partitionings, it picks the one
9207   // which yields more jump tables.
9208 
9209   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9210   SmallVector<unsigned, 8> MinPartitions(N);
9211   // LastElement[i] is the last element of the partition starting at i.
9212   SmallVector<unsigned, 8> LastElement(N);
9213   // PartitionsScore[i] is used to break ties when choosing between two
9214   // partitionings resulting in the same number of partitions.
9215   SmallVector<unsigned, 8> PartitionsScore(N);
9216   // For PartitionsScore, a small number of comparisons is considered as good as
9217   // a jump table and a single comparison is considered better than a jump
9218   // table.
9219   enum PartitionScores : unsigned {
9220     NoTable = 0,
9221     Table = 1,
9222     FewCases = 1,
9223     SingleCase = 2
9224   };
9225 
9226   // Base case: There is only one way to partition Clusters[N-1].
9227   MinPartitions[N - 1] = 1;
9228   LastElement[N - 1] = N - 1;
9229   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9230 
9231   // Note: loop indexes are signed to avoid underflow.
9232   for (int64_t i = N - 2; i >= 0; i--) {
9233     // Find optimal partitioning of Clusters[i..N-1].
9234     // Baseline: Put Clusters[i] into a partition on its own.
9235     MinPartitions[i] = MinPartitions[i + 1] + 1;
9236     LastElement[i] = i;
9237     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9238 
9239     // Search for a solution that results in fewer partitions.
9240     for (int64_t j = N - 1; j > i; j--) {
9241       // Try building a partition from Clusters[i..j].
9242       uint64_t Range = getJumpTableRange(Clusters, i, j);
9243       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9244       assert(NumCases < UINT64_MAX / 100);
9245       assert(Range >= NumCases);
9246       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9247         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9248         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9249         int64_t NumEntries = j - i + 1;
9250 
9251         if (NumEntries == 1)
9252           Score += PartitionScores::SingleCase;
9253         else if (NumEntries <= SmallNumberOfEntries)
9254           Score += PartitionScores::FewCases;
9255         else if (NumEntries >= MinJumpTableEntries)
9256           Score += PartitionScores::Table;
9257 
9258         // If this leads to fewer partitions, or to the same number of
9259         // partitions with better score, it is a better partitioning.
9260         if (NumPartitions < MinPartitions[i] ||
9261             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9262           MinPartitions[i] = NumPartitions;
9263           LastElement[i] = j;
9264           PartitionsScore[i] = Score;
9265         }
9266       }
9267     }
9268   }
9269 
9270   // Iterate over the partitions, replacing some with jump tables in-place.
9271   unsigned DstIndex = 0;
9272   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9273     Last = LastElement[First];
9274     assert(Last >= First);
9275     assert(DstIndex <= First);
9276     unsigned NumClusters = Last - First + 1;
9277 
9278     CaseCluster JTCluster;
9279     if (NumClusters >= MinJumpTableEntries &&
9280         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9281       Clusters[DstIndex++] = JTCluster;
9282     } else {
9283       for (unsigned I = First; I <= Last; ++I)
9284         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9285     }
9286   }
9287   Clusters.resize(DstIndex);
9288 }
9289 
9290 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9291                                         unsigned First, unsigned Last,
9292                                         const SwitchInst *SI,
9293                                         CaseCluster &BTCluster) {
9294   assert(First <= Last);
9295   if (First == Last)
9296     return false;
9297 
9298   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9299   unsigned NumCmps = 0;
9300   for (int64_t I = First; I <= Last; ++I) {
9301     assert(Clusters[I].Kind == CC_Range);
9302     Dests.set(Clusters[I].MBB->getNumber());
9303     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9304   }
9305   unsigned NumDests = Dests.count();
9306 
9307   APInt Low = Clusters[First].Low->getValue();
9308   APInt High = Clusters[Last].High->getValue();
9309   assert(Low.slt(High));
9310 
9311   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9312   const DataLayout &DL = DAG.getDataLayout();
9313   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9314     return false;
9315 
9316   APInt LowBound;
9317   APInt CmpRange;
9318 
9319   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9320   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9321          "Case range must fit in bit mask!");
9322 
9323   // Check if the clusters cover a contiguous range such that no value in the
9324   // range will jump to the default statement.
9325   bool ContiguousRange = true;
9326   for (int64_t I = First + 1; I <= Last; ++I) {
9327     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9328       ContiguousRange = false;
9329       break;
9330     }
9331   }
9332 
9333   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9334     // Optimize the case where all the case values fit in a word without having
9335     // to subtract minValue. In this case, we can optimize away the subtraction.
9336     LowBound = APInt::getNullValue(Low.getBitWidth());
9337     CmpRange = High;
9338     ContiguousRange = false;
9339   } else {
9340     LowBound = Low;
9341     CmpRange = High - Low;
9342   }
9343 
9344   CaseBitsVector CBV;
9345   auto TotalProb = BranchProbability::getZero();
9346   for (unsigned i = First; i <= Last; ++i) {
9347     // Find the CaseBits for this destination.
9348     unsigned j;
9349     for (j = 0; j < CBV.size(); ++j)
9350       if (CBV[j].BB == Clusters[i].MBB)
9351         break;
9352     if (j == CBV.size())
9353       CBV.push_back(
9354           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9355     CaseBits *CB = &CBV[j];
9356 
9357     // Update Mask, Bits and ExtraProb.
9358     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9359     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9360     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9361     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9362     CB->Bits += Hi - Lo + 1;
9363     CB->ExtraProb += Clusters[i].Prob;
9364     TotalProb += Clusters[i].Prob;
9365   }
9366 
9367   BitTestInfo BTI;
9368   std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
9369     // Sort by probability first, number of bits second, bit mask third.
9370     if (a.ExtraProb != b.ExtraProb)
9371       return a.ExtraProb > b.ExtraProb;
9372     if (a.Bits != b.Bits)
9373       return a.Bits > b.Bits;
9374     return a.Mask < b.Mask;
9375   });
9376 
9377   for (auto &CB : CBV) {
9378     MachineBasicBlock *BitTestBB =
9379         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9380     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9381   }
9382   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9383                             SI->getCondition(), -1U, MVT::Other, false,
9384                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9385                             TotalProb);
9386 
9387   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9388                                     BitTestCases.size() - 1, TotalProb);
9389   return true;
9390 }
9391 
9392 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9393                                               const SwitchInst *SI) {
9394 // Partition Clusters into as few subsets as possible, where each subset has a
9395 // range that fits in a machine word and has <= 3 unique destinations.
9396 
9397 #ifndef NDEBUG
9398   // Clusters must be sorted and contain Range or JumpTable clusters.
9399   assert(!Clusters.empty());
9400   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9401   for (const CaseCluster &C : Clusters)
9402     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9403   for (unsigned i = 1; i < Clusters.size(); ++i)
9404     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9405 #endif
9406 
9407   // The algorithm below is not suitable for -O0.
9408   if (TM.getOptLevel() == CodeGenOpt::None)
9409     return;
9410 
9411   // If target does not have legal shift left, do not emit bit tests at all.
9412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9413   const DataLayout &DL = DAG.getDataLayout();
9414 
9415   EVT PTy = TLI.getPointerTy(DL);
9416   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9417     return;
9418 
9419   int BitWidth = PTy.getSizeInBits();
9420   const int64_t N = Clusters.size();
9421 
9422   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9423   SmallVector<unsigned, 8> MinPartitions(N);
9424   // LastElement[i] is the last element of the partition starting at i.
9425   SmallVector<unsigned, 8> LastElement(N);
9426 
9427   // FIXME: This might not be the best algorithm for finding bit test clusters.
9428 
9429   // Base case: There is only one way to partition Clusters[N-1].
9430   MinPartitions[N - 1] = 1;
9431   LastElement[N - 1] = N - 1;
9432 
9433   // Note: loop indexes are signed to avoid underflow.
9434   for (int64_t i = N - 2; i >= 0; --i) {
9435     // Find optimal partitioning of Clusters[i..N-1].
9436     // Baseline: Put Clusters[i] into a partition on its own.
9437     MinPartitions[i] = MinPartitions[i + 1] + 1;
9438     LastElement[i] = i;
9439 
9440     // Search for a solution that results in fewer partitions.
9441     // Note: the search is limited by BitWidth, reducing time complexity.
9442     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9443       // Try building a partition from Clusters[i..j].
9444 
9445       // Check the range.
9446       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9447                                Clusters[j].High->getValue(), DL))
9448         continue;
9449 
9450       // Check nbr of destinations and cluster types.
9451       // FIXME: This works, but doesn't seem very efficient.
9452       bool RangesOnly = true;
9453       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9454       for (int64_t k = i; k <= j; k++) {
9455         if (Clusters[k].Kind != CC_Range) {
9456           RangesOnly = false;
9457           break;
9458         }
9459         Dests.set(Clusters[k].MBB->getNumber());
9460       }
9461       if (!RangesOnly || Dests.count() > 3)
9462         break;
9463 
9464       // Check if it's a better partition.
9465       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9466       if (NumPartitions < MinPartitions[i]) {
9467         // Found a better partition.
9468         MinPartitions[i] = NumPartitions;
9469         LastElement[i] = j;
9470       }
9471     }
9472   }
9473 
9474   // Iterate over the partitions, replacing with bit-test clusters in-place.
9475   unsigned DstIndex = 0;
9476   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9477     Last = LastElement[First];
9478     assert(First <= Last);
9479     assert(DstIndex <= First);
9480 
9481     CaseCluster BitTestCluster;
9482     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
9483       Clusters[DstIndex++] = BitTestCluster;
9484     } else {
9485       size_t NumClusters = Last - First + 1;
9486       std::memmove(&Clusters[DstIndex], &Clusters[First],
9487                    sizeof(Clusters[0]) * NumClusters);
9488       DstIndex += NumClusters;
9489     }
9490   }
9491   Clusters.resize(DstIndex);
9492 }
9493 
9494 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9495                                         MachineBasicBlock *SwitchMBB,
9496                                         MachineBasicBlock *DefaultMBB) {
9497   MachineFunction *CurMF = FuncInfo.MF;
9498   MachineBasicBlock *NextMBB = nullptr;
9499   MachineFunction::iterator BBI(W.MBB);
9500   if (++BBI != FuncInfo.MF->end())
9501     NextMBB = &*BBI;
9502 
9503   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9504 
9505   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9506 
9507   if (Size == 2 && W.MBB == SwitchMBB) {
9508     // If any two of the cases has the same destination, and if one value
9509     // is the same as the other, but has one bit unset that the other has set,
9510     // use bit manipulation to do two compares at once.  For example:
9511     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9512     // TODO: This could be extended to merge any 2 cases in switches with 3
9513     // cases.
9514     // TODO: Handle cases where W.CaseBB != SwitchBB.
9515     CaseCluster &Small = *W.FirstCluster;
9516     CaseCluster &Big = *W.LastCluster;
9517 
9518     if (Small.Low == Small.High && Big.Low == Big.High &&
9519         Small.MBB == Big.MBB) {
9520       const APInt &SmallValue = Small.Low->getValue();
9521       const APInt &BigValue = Big.Low->getValue();
9522 
9523       // Check that there is only one bit different.
9524       APInt CommonBit = BigValue ^ SmallValue;
9525       if (CommonBit.isPowerOf2()) {
9526         SDValue CondLHS = getValue(Cond);
9527         EVT VT = CondLHS.getValueType();
9528         SDLoc DL = getCurSDLoc();
9529 
9530         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9531                                  DAG.getConstant(CommonBit, DL, VT));
9532         SDValue Cond = DAG.getSetCC(
9533             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9534             ISD::SETEQ);
9535 
9536         // Update successor info.
9537         // Both Small and Big will jump to Small.BB, so we sum up the
9538         // probabilities.
9539         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9540         if (BPI)
9541           addSuccessorWithProb(
9542               SwitchMBB, DefaultMBB,
9543               // The default destination is the first successor in IR.
9544               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9545         else
9546           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9547 
9548         // Insert the true branch.
9549         SDValue BrCond =
9550             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9551                         DAG.getBasicBlock(Small.MBB));
9552         // Insert the false branch.
9553         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9554                              DAG.getBasicBlock(DefaultMBB));
9555 
9556         DAG.setRoot(BrCond);
9557         return;
9558       }
9559     }
9560   }
9561 
9562   if (TM.getOptLevel() != CodeGenOpt::None) {
9563     // Here, we order cases by probability so the most likely case will be
9564     // checked first. However, two clusters can have the same probability in
9565     // which case their relative ordering is non-deterministic. So we use Low
9566     // as a tie-breaker as clusters are guaranteed to never overlap.
9567     std::sort(W.FirstCluster, W.LastCluster + 1,
9568               [](const CaseCluster &a, const CaseCluster &b) {
9569       return a.Prob != b.Prob ?
9570              a.Prob > b.Prob :
9571              a.Low->getValue().slt(b.Low->getValue());
9572     });
9573 
9574     // Rearrange the case blocks so that the last one falls through if possible
9575     // without without changing the order of probabilities.
9576     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9577       --I;
9578       if (I->Prob > W.LastCluster->Prob)
9579         break;
9580       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9581         std::swap(*I, *W.LastCluster);
9582         break;
9583       }
9584     }
9585   }
9586 
9587   // Compute total probability.
9588   BranchProbability DefaultProb = W.DefaultProb;
9589   BranchProbability UnhandledProbs = DefaultProb;
9590   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
9591     UnhandledProbs += I->Prob;
9592 
9593   MachineBasicBlock *CurMBB = W.MBB;
9594   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
9595     MachineBasicBlock *Fallthrough;
9596     if (I == W.LastCluster) {
9597       // For the last cluster, fall through to the default destination.
9598       Fallthrough = DefaultMBB;
9599     } else {
9600       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
9601       CurMF->insert(BBI, Fallthrough);
9602       // Put Cond in a virtual register to make it available from the new blocks.
9603       ExportFromCurrentBlock(Cond);
9604     }
9605     UnhandledProbs -= I->Prob;
9606 
9607     switch (I->Kind) {
9608       case CC_JumpTable: {
9609         // FIXME: Optimize away range check based on pivot comparisons.
9610         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
9611         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
9612 
9613         // The jump block hasn't been inserted yet; insert it here.
9614         MachineBasicBlock *JumpMBB = JT->MBB;
9615         CurMF->insert(BBI, JumpMBB);
9616 
9617         auto JumpProb = I->Prob;
9618         auto FallthroughProb = UnhandledProbs;
9619 
9620         // If the default statement is a target of the jump table, we evenly
9621         // distribute the default probability to successors of CurMBB. Also
9622         // update the probability on the edge from JumpMBB to Fallthrough.
9623         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
9624                                               SE = JumpMBB->succ_end();
9625              SI != SE; ++SI) {
9626           if (*SI == DefaultMBB) {
9627             JumpProb += DefaultProb / 2;
9628             FallthroughProb -= DefaultProb / 2;
9629             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
9630             JumpMBB->normalizeSuccProbs();
9631             break;
9632           }
9633         }
9634 
9635         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
9636         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
9637         CurMBB->normalizeSuccProbs();
9638 
9639         // The jump table header will be inserted in our current block, do the
9640         // range check, and fall through to our fallthrough block.
9641         JTH->HeaderBB = CurMBB;
9642         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
9643 
9644         // If we're in the right place, emit the jump table header right now.
9645         if (CurMBB == SwitchMBB) {
9646           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
9647           JTH->Emitted = true;
9648         }
9649         break;
9650       }
9651       case CC_BitTests: {
9652         // FIXME: Optimize away range check based on pivot comparisons.
9653         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
9654 
9655         // The bit test blocks haven't been inserted yet; insert them here.
9656         for (BitTestCase &BTC : BTB->Cases)
9657           CurMF->insert(BBI, BTC.ThisBB);
9658 
9659         // Fill in fields of the BitTestBlock.
9660         BTB->Parent = CurMBB;
9661         BTB->Default = Fallthrough;
9662 
9663         BTB->DefaultProb = UnhandledProbs;
9664         // If the cases in bit test don't form a contiguous range, we evenly
9665         // distribute the probability on the edge to Fallthrough to two
9666         // successors of CurMBB.
9667         if (!BTB->ContiguousRange) {
9668           BTB->Prob += DefaultProb / 2;
9669           BTB->DefaultProb -= DefaultProb / 2;
9670         }
9671 
9672         // If we're in the right place, emit the bit test header right now.
9673         if (CurMBB == SwitchMBB) {
9674           visitBitTestHeader(*BTB, SwitchMBB);
9675           BTB->Emitted = true;
9676         }
9677         break;
9678       }
9679       case CC_Range: {
9680         const Value *RHS, *LHS, *MHS;
9681         ISD::CondCode CC;
9682         if (I->Low == I->High) {
9683           // Check Cond == I->Low.
9684           CC = ISD::SETEQ;
9685           LHS = Cond;
9686           RHS=I->Low;
9687           MHS = nullptr;
9688         } else {
9689           // Check I->Low <= Cond <= I->High.
9690           CC = ISD::SETLE;
9691           LHS = I->Low;
9692           MHS = Cond;
9693           RHS = I->High;
9694         }
9695 
9696         // The false probability is the sum of all unhandled cases.
9697         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
9698                      getCurSDLoc(), I->Prob, UnhandledProbs);
9699 
9700         if (CurMBB == SwitchMBB)
9701           visitSwitchCase(CB, SwitchMBB);
9702         else
9703           SwitchCases.push_back(CB);
9704 
9705         break;
9706       }
9707     }
9708     CurMBB = Fallthrough;
9709   }
9710 }
9711 
9712 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
9713                                               CaseClusterIt First,
9714                                               CaseClusterIt Last) {
9715   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
9716     if (X.Prob != CC.Prob)
9717       return X.Prob > CC.Prob;
9718 
9719     // Ties are broken by comparing the case value.
9720     return X.Low->getValue().slt(CC.Low->getValue());
9721   });
9722 }
9723 
9724 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
9725                                         const SwitchWorkListItem &W,
9726                                         Value *Cond,
9727                                         MachineBasicBlock *SwitchMBB) {
9728   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
9729          "Clusters not sorted?");
9730 
9731   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
9732 
9733   // Balance the tree based on branch probabilities to create a near-optimal (in
9734   // terms of search time given key frequency) binary search tree. See e.g. Kurt
9735   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
9736   CaseClusterIt LastLeft = W.FirstCluster;
9737   CaseClusterIt FirstRight = W.LastCluster;
9738   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
9739   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
9740 
9741   // Move LastLeft and FirstRight towards each other from opposite directions to
9742   // find a partitioning of the clusters which balances the probability on both
9743   // sides. If LeftProb and RightProb are equal, alternate which side is
9744   // taken to ensure 0-probability nodes are distributed evenly.
9745   unsigned I = 0;
9746   while (LastLeft + 1 < FirstRight) {
9747     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
9748       LeftProb += (++LastLeft)->Prob;
9749     else
9750       RightProb += (--FirstRight)->Prob;
9751     I++;
9752   }
9753 
9754   while (true) {
9755     // Our binary search tree differs from a typical BST in that ours can have up
9756     // to three values in each leaf. The pivot selection above doesn't take that
9757     // into account, which means the tree might require more nodes and be less
9758     // efficient. We compensate for this here.
9759 
9760     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
9761     unsigned NumRight = W.LastCluster - FirstRight + 1;
9762 
9763     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
9764       // If one side has less than 3 clusters, and the other has more than 3,
9765       // consider taking a cluster from the other side.
9766 
9767       if (NumLeft < NumRight) {
9768         // Consider moving the first cluster on the right to the left side.
9769         CaseCluster &CC = *FirstRight;
9770         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9771         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9772         if (LeftSideRank <= RightSideRank) {
9773           // Moving the cluster to the left does not demote it.
9774           ++LastLeft;
9775           ++FirstRight;
9776           continue;
9777         }
9778       } else {
9779         assert(NumRight < NumLeft);
9780         // Consider moving the last element on the left to the right side.
9781         CaseCluster &CC = *LastLeft;
9782         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9783         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9784         if (RightSideRank <= LeftSideRank) {
9785           // Moving the cluster to the right does not demot it.
9786           --LastLeft;
9787           --FirstRight;
9788           continue;
9789         }
9790       }
9791     }
9792     break;
9793   }
9794 
9795   assert(LastLeft + 1 == FirstRight);
9796   assert(LastLeft >= W.FirstCluster);
9797   assert(FirstRight <= W.LastCluster);
9798 
9799   // Use the first element on the right as pivot since we will make less-than
9800   // comparisons against it.
9801   CaseClusterIt PivotCluster = FirstRight;
9802   assert(PivotCluster > W.FirstCluster);
9803   assert(PivotCluster <= W.LastCluster);
9804 
9805   CaseClusterIt FirstLeft = W.FirstCluster;
9806   CaseClusterIt LastRight = W.LastCluster;
9807 
9808   const ConstantInt *Pivot = PivotCluster->Low;
9809 
9810   // New blocks will be inserted immediately after the current one.
9811   MachineFunction::iterator BBI(W.MBB);
9812   ++BBI;
9813 
9814   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
9815   // we can branch to its destination directly if it's squeezed exactly in
9816   // between the known lower bound and Pivot - 1.
9817   MachineBasicBlock *LeftMBB;
9818   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
9819       FirstLeft->Low == W.GE &&
9820       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
9821     LeftMBB = FirstLeft->MBB;
9822   } else {
9823     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
9824     FuncInfo.MF->insert(BBI, LeftMBB);
9825     WorkList.push_back(
9826         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
9827     // Put Cond in a virtual register to make it available from the new blocks.
9828     ExportFromCurrentBlock(Cond);
9829   }
9830 
9831   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
9832   // single cluster, RHS.Low == Pivot, and we can branch to its destination
9833   // directly if RHS.High equals the current upper bound.
9834   MachineBasicBlock *RightMBB;
9835   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
9836       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
9837     RightMBB = FirstRight->MBB;
9838   } else {
9839     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
9840     FuncInfo.MF->insert(BBI, RightMBB);
9841     WorkList.push_back(
9842         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
9843     // Put Cond in a virtual register to make it available from the new blocks.
9844     ExportFromCurrentBlock(Cond);
9845   }
9846 
9847   // Create the CaseBlock record that will be used to lower the branch.
9848   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
9849                getCurSDLoc(), LeftProb, RightProb);
9850 
9851   if (W.MBB == SwitchMBB)
9852     visitSwitchCase(CB, SwitchMBB);
9853   else
9854     SwitchCases.push_back(CB);
9855 }
9856 
9857 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
9858 // from the swith statement.
9859 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
9860                                             BranchProbability PeeledCaseProb) {
9861   if (PeeledCaseProb == BranchProbability::getOne())
9862     return BranchProbability::getZero();
9863   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
9864 
9865   uint32_t Numerator = CaseProb.getNumerator();
9866   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
9867   return BranchProbability(Numerator, std::max(Numerator, Denominator));
9868 }
9869 
9870 // Try to peel the top probability case if it exceeds the threshold.
9871 // Return current MachineBasicBlock for the switch statement if the peeling
9872 // does not occur.
9873 // If the peeling is performed, return the newly created MachineBasicBlock
9874 // for the peeled switch statement. Also update Clusters to remove the peeled
9875 // case. PeeledCaseProb is the BranchProbability for the peeled case.
9876 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
9877     const SwitchInst &SI, CaseClusterVector &Clusters,
9878     BranchProbability &PeeledCaseProb) {
9879   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
9880   // Don't perform if there is only one cluster or optimizing for size.
9881   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
9882       TM.getOptLevel() == CodeGenOpt::None ||
9883       SwitchMBB->getParent()->getFunction().optForMinSize())
9884     return SwitchMBB;
9885 
9886   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
9887   unsigned PeeledCaseIndex = 0;
9888   bool SwitchPeeled = false;
9889   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
9890     CaseCluster &CC = Clusters[Index];
9891     if (CC.Prob < TopCaseProb)
9892       continue;
9893     TopCaseProb = CC.Prob;
9894     PeeledCaseIndex = Index;
9895     SwitchPeeled = true;
9896   }
9897   if (!SwitchPeeled)
9898     return SwitchMBB;
9899 
9900   DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " << TopCaseProb
9901                << "\n");
9902 
9903   // Record the MBB for the peeled switch statement.
9904   MachineFunction::iterator BBI(SwitchMBB);
9905   ++BBI;
9906   MachineBasicBlock *PeeledSwitchMBB =
9907       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
9908   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
9909 
9910   ExportFromCurrentBlock(SI.getCondition());
9911   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
9912   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
9913                           nullptr,   nullptr,      TopCaseProb.getCompl()};
9914   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
9915 
9916   Clusters.erase(PeeledCaseIt);
9917   for (CaseCluster &CC : Clusters) {
9918     DEBUG(dbgs() << "Scale the probablity for one cluster, before scaling: "
9919                  << CC.Prob << "\n");
9920     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
9921     DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
9922   }
9923   PeeledCaseProb = TopCaseProb;
9924   return PeeledSwitchMBB;
9925 }
9926 
9927 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
9928   // Extract cases from the switch.
9929   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9930   CaseClusterVector Clusters;
9931   Clusters.reserve(SI.getNumCases());
9932   for (auto I : SI.cases()) {
9933     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
9934     const ConstantInt *CaseVal = I.getCaseValue();
9935     BranchProbability Prob =
9936         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
9937             : BranchProbability(1, SI.getNumCases() + 1);
9938     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
9939   }
9940 
9941   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
9942 
9943   // Cluster adjacent cases with the same destination. We do this at all
9944   // optimization levels because it's cheap to do and will make codegen faster
9945   // if there are many clusters.
9946   sortAndRangeify(Clusters);
9947 
9948   if (TM.getOptLevel() != CodeGenOpt::None) {
9949     // Replace an unreachable default with the most popular destination.
9950     // FIXME: Exploit unreachable default more aggressively.
9951     bool UnreachableDefault =
9952         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
9953     if (UnreachableDefault && !Clusters.empty()) {
9954       DenseMap<const BasicBlock *, unsigned> Popularity;
9955       unsigned MaxPop = 0;
9956       const BasicBlock *MaxBB = nullptr;
9957       for (auto I : SI.cases()) {
9958         const BasicBlock *BB = I.getCaseSuccessor();
9959         if (++Popularity[BB] > MaxPop) {
9960           MaxPop = Popularity[BB];
9961           MaxBB = BB;
9962         }
9963       }
9964       // Set new default.
9965       assert(MaxPop > 0 && MaxBB);
9966       DefaultMBB = FuncInfo.MBBMap[MaxBB];
9967 
9968       // Remove cases that were pointing to the destination that is now the
9969       // default.
9970       CaseClusterVector New;
9971       New.reserve(Clusters.size());
9972       for (CaseCluster &CC : Clusters) {
9973         if (CC.MBB != DefaultMBB)
9974           New.push_back(CC);
9975       }
9976       Clusters = std::move(New);
9977     }
9978   }
9979 
9980   // The branch probablity of the peeled case.
9981   BranchProbability PeeledCaseProb = BranchProbability::getZero();
9982   MachineBasicBlock *PeeledSwitchMBB =
9983       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
9984 
9985   // If there is only the default destination, jump there directly.
9986   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
9987   if (Clusters.empty()) {
9988     assert(PeeledSwitchMBB == SwitchMBB);
9989     SwitchMBB->addSuccessor(DefaultMBB);
9990     if (DefaultMBB != NextBlock(SwitchMBB)) {
9991       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
9992                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
9993     }
9994     return;
9995   }
9996 
9997   findJumpTables(Clusters, &SI, DefaultMBB);
9998   findBitTestClusters(Clusters, &SI);
9999 
10000   DEBUG({
10001     dbgs() << "Case clusters: ";
10002     for (const CaseCluster &C : Clusters) {
10003       if (C.Kind == CC_JumpTable) dbgs() << "JT:";
10004       if (C.Kind == CC_BitTests) dbgs() << "BT:";
10005 
10006       C.Low->getValue().print(dbgs(), true);
10007       if (C.Low != C.High) {
10008         dbgs() << '-';
10009         C.High->getValue().print(dbgs(), true);
10010       }
10011       dbgs() << ' ';
10012     }
10013     dbgs() << '\n';
10014   });
10015 
10016   assert(!Clusters.empty());
10017   SwitchWorkList WorkList;
10018   CaseClusterIt First = Clusters.begin();
10019   CaseClusterIt Last = Clusters.end() - 1;
10020   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10021   // Scale the branchprobability for DefaultMBB if the peel occurs and
10022   // DefaultMBB is not replaced.
10023   if (PeeledCaseProb != BranchProbability::getZero() &&
10024       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10025     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10026   WorkList.push_back(
10027       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10028 
10029   while (!WorkList.empty()) {
10030     SwitchWorkListItem W = WorkList.back();
10031     WorkList.pop_back();
10032     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10033 
10034     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10035         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10036       // For optimized builds, lower large range as a balanced binary tree.
10037       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10038       continue;
10039     }
10040 
10041     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10042   }
10043 }
10044