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