LCOV - code coverage report
Current view: top level - lib/CodeGen/SelectionDAG - SelectionDAGBuilder.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 4226 4358 97.0 %
Date: 2018-02-19 03:08:00 Functions: 175 180 97.2 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This implements routines for translating from LLVM IR into SelectionDAG IR.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "SelectionDAGBuilder.h"
      15             : #include "llvm/ADT/APFloat.h"
      16             : #include "llvm/ADT/APInt.h"
      17             : #include "llvm/ADT/ArrayRef.h"
      18             : #include "llvm/ADT/BitVector.h"
      19             : #include "llvm/ADT/DenseMap.h"
      20             : #include "llvm/ADT/None.h"
      21             : #include "llvm/ADT/Optional.h"
      22             : #include "llvm/ADT/STLExtras.h"
      23             : #include "llvm/ADT/SmallPtrSet.h"
      24             : #include "llvm/ADT/SmallSet.h"
      25             : #include "llvm/ADT/SmallVector.h"
      26             : #include "llvm/ADT/StringRef.h"
      27             : #include "llvm/ADT/Triple.h"
      28             : #include "llvm/ADT/Twine.h"
      29             : #include "llvm/Analysis/AliasAnalysis.h"
      30             : #include "llvm/Analysis/BranchProbabilityInfo.h"
      31             : #include "llvm/Analysis/ConstantFolding.h"
      32             : #include "llvm/Analysis/EHPersonalities.h"
      33             : #include "llvm/Analysis/Loads.h"
      34             : #include "llvm/Analysis/MemoryLocation.h"
      35             : #include "llvm/Analysis/TargetLibraryInfo.h"
      36             : #include "llvm/Analysis/ValueTracking.h"
      37             : #include "llvm/Analysis/VectorUtils.h"
      38             : #include "llvm/CodeGen/Analysis.h"
      39             : #include "llvm/CodeGen/FunctionLoweringInfo.h"
      40             : #include "llvm/CodeGen/GCMetadata.h"
      41             : #include "llvm/CodeGen/ISDOpcodes.h"
      42             : #include "llvm/CodeGen/MachineBasicBlock.h"
      43             : #include "llvm/CodeGen/MachineFrameInfo.h"
      44             : #include "llvm/CodeGen/MachineFunction.h"
      45             : #include "llvm/CodeGen/MachineInstr.h"
      46             : #include "llvm/CodeGen/MachineInstrBuilder.h"
      47             : #include "llvm/CodeGen/MachineJumpTableInfo.h"
      48             : #include "llvm/CodeGen/MachineMemOperand.h"
      49             : #include "llvm/CodeGen/MachineModuleInfo.h"
      50             : #include "llvm/CodeGen/MachineOperand.h"
      51             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      52             : #include "llvm/CodeGen/MachineValueType.h"
      53             : #include "llvm/CodeGen/RuntimeLibcalls.h"
      54             : #include "llvm/CodeGen/SelectionDAG.h"
      55             : #include "llvm/CodeGen/SelectionDAGNodes.h"
      56             : #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
      57             : #include "llvm/CodeGen/StackMaps.h"
      58             : #include "llvm/CodeGen/TargetFrameLowering.h"
      59             : #include "llvm/CodeGen/TargetInstrInfo.h"
      60             : #include "llvm/CodeGen/TargetLowering.h"
      61             : #include "llvm/CodeGen/TargetOpcodes.h"
      62             : #include "llvm/CodeGen/TargetRegisterInfo.h"
      63             : #include "llvm/CodeGen/TargetSubtargetInfo.h"
      64             : #include "llvm/CodeGen/ValueTypes.h"
      65             : #include "llvm/CodeGen/WinEHFuncInfo.h"
      66             : #include "llvm/IR/Argument.h"
      67             : #include "llvm/IR/Attributes.h"
      68             : #include "llvm/IR/BasicBlock.h"
      69             : #include "llvm/IR/CFG.h"
      70             : #include "llvm/IR/CallSite.h"
      71             : #include "llvm/IR/CallingConv.h"
      72             : #include "llvm/IR/Constant.h"
      73             : #include "llvm/IR/ConstantRange.h"
      74             : #include "llvm/IR/Constants.h"
      75             : #include "llvm/IR/DataLayout.h"
      76             : #include "llvm/IR/DebugInfoMetadata.h"
      77             : #include "llvm/IR/DebugLoc.h"
      78             : #include "llvm/IR/DerivedTypes.h"
      79             : #include "llvm/IR/Function.h"
      80             : #include "llvm/IR/GetElementPtrTypeIterator.h"
      81             : #include "llvm/IR/InlineAsm.h"
      82             : #include "llvm/IR/InstrTypes.h"
      83             : #include "llvm/IR/Instruction.h"
      84             : #include "llvm/IR/Instructions.h"
      85             : #include "llvm/IR/IntrinsicInst.h"
      86             : #include "llvm/IR/Intrinsics.h"
      87             : #include "llvm/IR/LLVMContext.h"
      88             : #include "llvm/IR/Metadata.h"
      89             : #include "llvm/IR/Module.h"
      90             : #include "llvm/IR/Operator.h"
      91             : #include "llvm/IR/Statepoint.h"
      92             : #include "llvm/IR/Type.h"
      93             : #include "llvm/IR/User.h"
      94             : #include "llvm/IR/Value.h"
      95             : #include "llvm/MC/MCContext.h"
      96             : #include "llvm/MC/MCSymbol.h"
      97             : #include "llvm/Support/AtomicOrdering.h"
      98             : #include "llvm/Support/BranchProbability.h"
      99             : #include "llvm/Support/Casting.h"
     100             : #include "llvm/Support/CodeGen.h"
     101             : #include "llvm/Support/CommandLine.h"
     102             : #include "llvm/Support/Compiler.h"
     103             : #include "llvm/Support/Debug.h"
     104             : #include "llvm/Support/ErrorHandling.h"
     105             : #include "llvm/Support/MathExtras.h"
     106             : #include "llvm/Support/raw_ostream.h"
     107             : #include "llvm/Target/TargetIntrinsicInfo.h"
     108             : #include "llvm/Target/TargetMachine.h"
     109             : #include "llvm/Target/TargetOptions.h"
     110             : #include <algorithm>
     111             : #include <cassert>
     112             : #include <cstddef>
     113             : #include <cstdint>
     114             : #include <cstring>
     115             : #include <iterator>
     116             : #include <limits>
     117             : #include <numeric>
     118             : #include <tuple>
     119             : #include <utility>
     120             : #include <vector>
     121             : 
     122             : using namespace llvm;
     123             : 
     124             : #define DEBUG_TYPE "isel"
     125             : 
     126             : /// LimitFloatPrecision - Generate low-precision inline sequences for
     127             : /// some float libcalls (6, 8 or 12 bits).
     128             : static unsigned LimitFloatPrecision;
     129             : 
     130             : static cl::opt<unsigned, true>
     131       97324 :     LimitFPPrecision("limit-float-precision",
     132       97324 :                      cl::desc("Generate low-precision inline sequences "
     133             :                               "for some float libcalls"),
     134      194648 :                      cl::location(LimitFloatPrecision), cl::Hidden,
     135      291972 :                      cl::init(0));
     136             : 
     137       97324 : static cl::opt<unsigned> SwitchPeelThreshold(
     138      194648 :     "switch-peel-threshold", cl::Hidden, cl::init(66),
     139       97324 :     cl::desc("Set the case probability threshold for peeling the case from a "
     140             :              "switch statement. A value greater than 100 will void this "
     141       97324 :              "optimization"));
     142             : 
     143             : // Limit the width of DAG chains. This is important in general to prevent
     144             : // DAG-based analysis from blowing up. For example, alias analysis and
     145             : // load clustering may not complete in reasonable time. It is difficult to
     146             : // recognize and avoid this situation within each individual analysis, and
     147             : // future analyses are likely to have the same behavior. Limiting DAG width is
     148             : // the safe approach and will be especially important with global DAGs.
     149             : //
     150             : // MaxParallelChains default is arbitrarily high to avoid affecting
     151             : // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
     152             : // sequence over this should have been converted to llvm.memcpy by the
     153             : // frontend. It is easy to induce this behavior with .ll code such as:
     154             : // %buffer = alloca [4096 x i8]
     155             : // %data = load [4096 x i8]* %argPtr
     156             : // store [4096 x i8] %data, [4096 x i8]* %buffer
     157             : static const unsigned MaxParallelChains = 64;
     158             : 
     159             : // True if the Value passed requires ABI mangling as it is a parameter to a
     160             : // function or a return value from a function which is not an intrinsic.
     161      268616 : static bool isABIRegCopy(const Value *V) {
     162      268616 :   const bool IsRetInst = V && isa<ReturnInst>(V);
     163      268616 :   const bool IsCallInst = V && isa<CallInst>(V);
     164             :   const bool IsInLineAsm =
     165       11123 :       IsCallInst && static_cast<const CallInst *>(V)->isInlineAsm();
     166             :   const bool IsIndirectFunctionCall =
     167      268616 :       IsCallInst && !IsInLineAsm &&
     168             :       !static_cast<const CallInst *>(V)->getCalledFunction();
     169             :   // It is possible that the call instruction is an inline asm statement or an
     170             :   // indirect function call in which case the return value of
     171             :   // getCalledFunction() would be nullptr.
     172             :   const bool IsInstrinsicCall =
     173      279222 :       IsCallInst && !IsInLineAsm && !IsIndirectFunctionCall &&
     174       10606 :       static_cast<const CallInst *>(V)->getCalledFunction()->getIntrinsicID() !=
     175             :           Intrinsic::not_intrinsic;
     176             : 
     177      268616 :   return IsRetInst || (IsCallInst && (!IsInLineAsm && !IsInstrinsicCall));
     178             : }
     179             : 
     180             : static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
     181             :                                       const SDValue *Parts, unsigned NumParts,
     182             :                                       MVT PartVT, EVT ValueVT, const Value *V,
     183             :                                       bool IsABIRegCopy);
     184             : 
     185             : /// getCopyFromParts - Create a value that contains the specified legal parts
     186             : /// combined into the value they represent.  If the parts combine to a type
     187             : /// larger than ValueVT then AssertOp can be used to specify whether the extra
     188             : /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
     189             : /// (ISD::AssertSext).
     190      497813 : static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
     191             :                                 const SDValue *Parts, unsigned NumParts,
     192             :                                 MVT PartVT, EVT ValueVT, const Value *V,
     193             :                                 Optional<ISD::NodeType> AssertOp = None,
     194             :                                 bool IsABIRegCopy = false) {
     195      497813 :   if (ValueVT.isVector())
     196             :     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
     197      132899 :                                   PartVT, ValueVT, V, IsABIRegCopy);
     198             : 
     199             :   assert(NumParts > 0 && "No parts to assemble!");
     200             :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     201      364914 :   SDValue Val = Parts[0];
     202             : 
     203      364914 :   if (NumParts > 1) {
     204             :     // Assemble the value from multiple parts.
     205       14360 :     if (ValueVT.isInteger()) {
     206       13242 :       unsigned PartBits = PartVT.getSizeInBits();
     207       13242 :       unsigned ValueBits = ValueVT.getSizeInBits();
     208             : 
     209             :       // Assemble the power of 2 part.
     210       13456 :       unsigned RoundParts = NumParts & (NumParts - 1) ?
     211         214 :         1 << Log2_32(NumParts) : NumParts;
     212       13242 :       unsigned RoundBits = PartBits * RoundParts;
     213             :       EVT RoundVT = RoundBits == ValueBits ?
     214       13242 :         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
     215       13242 :       SDValue Lo, Hi;
     216             : 
     217       13242 :       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
     218             : 
     219       13242 :       if (RoundParts > 2) {
     220        1647 :         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
     221        3294 :                               PartVT, HalfVT, V);
     222        3294 :         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
     223        3294 :                               RoundParts / 2, PartVT, HalfVT, V);
     224             :       } else {
     225       11595 :         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
     226       11595 :         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
     227             :       }
     228             : 
     229       26484 :       if (DAG.getDataLayout().isBigEndian())
     230             :         std::swap(Lo, Hi);
     231             : 
     232       13242 :       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
     233             : 
     234       13242 :       if (RoundParts < NumParts) {
     235             :         // Assemble the trailing non-power-of-2 part.
     236         214 :         unsigned OddParts = NumParts - RoundParts;
     237         214 :         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
     238         214 :         Hi = getCopyFromParts(DAG, DL,
     239         428 :                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
     240             : 
     241             :         // Combine the round and odd parts.
     242         214 :         Lo = Val;
     243         428 :         if (DAG.getDataLayout().isBigEndian())
     244             :           std::swap(Lo, Hi);
     245         214 :         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
     246         214 :         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
     247         214 :         Hi =
     248         428 :             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
     249         214 :                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
     250         642 :                                         TLI.getPointerTy(DAG.getDataLayout())));
     251         214 :         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
     252         214 :         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
     253             :       }
     254        1118 :     } else if (PartVT.isFloatingPoint()) {
     255             :       // FP split into multiple FP parts (for ppcf128)
     256             :       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
     257             :              "Unexpected split");
     258             :       SDValue Lo, Hi;
     259         168 :       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
     260         336 :       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
     261         336 :       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
     262             :         std::swap(Lo, Hi);
     263         168 :       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
     264             :     } else {
     265             :       // FP split into integer parts (soft fp)
     266             :       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
     267             :              !PartVT.isVector() && "Unexpected split");
     268         950 :       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
     269         950 :       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
     270             :     }
     271             :   }
     272             : 
     273             :   // There is now one part, held in Val.  Correct it to match ValueVT.
     274             :   // PartEVT is the type of the register class that holds the value.
     275             :   // ValueVT is the type of the inline asm operation.
     276      364914 :   EVT PartEVT = Val.getValueType();
     277             : 
     278      365723 :   if (PartEVT == ValueVT)
     279      339091 :     return Val;
     280             : 
     281       27461 :   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
     282        1638 :       ValueVT.bitsLT(PartEVT)) {
     283             :     // For an FP value in an integer part, we need to truncate to the right
     284             :     // width first.
     285          25 :     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
     286          25 :     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
     287             :   }
     288             : 
     289             :   // Handle types that have the same size.
     290       25823 :   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
     291        1703 :     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
     292             : 
     293             :   // Handle types with different sizes.
     294       24120 :   if (PartEVT.isInteger() && ValueVT.isInteger()) {
     295       23576 :     if (ValueVT.bitsLT(PartEVT)) {
     296             :       // For a truncate, see if we have any information to
     297             :       // indicate whether the truncated bits will always be
     298             :       // zero or sign-extension.
     299       23554 :       if (AssertOp.hasValue())
     300        9589 :         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
     301       19178 :                           DAG.getValueType(ValueVT));
     302       23554 :       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
     303             :     }
     304          22 :     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
     305             :   }
     306             : 
     307        1088 :   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
     308             :     // FP_ROUND's are always exact here.
     309         544 :     if (ValueVT.bitsLT(Val.getValueType()))
     310             :       return DAG.getNode(
     311             :           ISD::FP_ROUND, DL, ValueVT, Val,
     312        1088 :           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
     313             : 
     314           0 :     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
     315             :   }
     316             : 
     317           0 :   llvm_unreachable("Unknown mismatch!");
     318             : }
     319             : 
     320          12 : static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
     321             :                                               const Twine &ErrMsg) {
     322             :   const Instruction *I = dyn_cast_or_null<Instruction>(V);
     323          12 :   if (!V)
     324           0 :     return Ctx.emitError(ErrMsg);
     325             : 
     326             :   const char *AsmError = ", possible invalid constraint for vector type";
     327             :   if (const CallInst *CI = dyn_cast<CallInst>(I))
     328          12 :     if (isa<InlineAsm>(CI->getCalledValue()))
     329          12 :       return Ctx.emitError(I, ErrMsg + AsmError);
     330             : 
     331           0 :   return Ctx.emitError(I, ErrMsg);
     332             : }
     333             : 
     334             : /// getCopyFromPartsVector - Create a value that contains the specified legal
     335             : /// parts combined into the value they represent.  If the parts combine to a
     336             : /// type larger than ValueVT then AssertOp can be used to specify whether the
     337             : /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
     338             : /// ValueVT (ISD::AssertSext).
     339      132899 : static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
     340             :                                       const SDValue *Parts, unsigned NumParts,
     341             :                                       MVT PartVT, EVT ValueVT, const Value *V,
     342             :                                       bool IsABIRegCopy) {
     343             :   assert(ValueVT.isVector() && "Not a vector value");
     344             :   assert(NumParts > 0 && "No parts to assemble!");
     345      132899 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     346      132899 :   SDValue Val = Parts[0];
     347             : 
     348             :   // Handle a multi-element vector.
     349      132899 :   if (NumParts > 1) {
     350        8171 :     EVT IntermediateVT;
     351        8171 :     MVT RegisterVT;
     352             :     unsigned NumIntermediates;
     353             :     unsigned NumRegs;
     354             : 
     355        8171 :     if (IsABIRegCopy) {
     356       14626 :       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
     357        7313 :           *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
     358        7313 :           RegisterVT);
     359             :     } else {
     360         858 :       NumRegs =
     361         858 :           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
     362             :                                      NumIntermediates, RegisterVT);
     363             :     }
     364             : 
     365             :     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
     366             :     NumParts = NumRegs; // Silence a compiler warning.
     367             :     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
     368             :     assert(RegisterVT.getSizeInBits() ==
     369             :            Parts[0].getSimpleValueType().getSizeInBits() &&
     370             :            "Part type sizes don't match!");
     371             : 
     372             :     // Assemble the parts into intermediate operands.
     373       16342 :     SmallVector<SDValue, 8> Ops(NumIntermediates);
     374        8171 :     if (NumIntermediates == NumParts) {
     375             :       // If the register was not expanded, truncate or copy the value,
     376             :       // as appropriate.
     377       56063 :       for (unsigned i = 0; i != NumParts; ++i)
     378       72810 :         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
     379       48540 :                                   PartVT, IntermediateVT, V);
     380         648 :     } else if (NumParts > 0) {
     381             :       // If the intermediate type was expanded, build the intermediate
     382             :       // operands from the parts.
     383             :       assert(NumParts % NumIntermediates == 0 &&
     384             :              "Must expand into a divisible number of parts!");
     385         648 :       unsigned Factor = NumParts / NumIntermediates;
     386        3556 :       for (unsigned i = 0; i != NumIntermediates; ++i)
     387        4362 :         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
     388        2908 :                                   PartVT, IntermediateVT, V);
     389             :     }
     390             : 
     391             :     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
     392             :     // intermediate operands.
     393             :     EVT BuiltVectorTy =
     394        8171 :         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
     395             :                          (IntermediateVT.isVector()
     396        5980 :                               ? IntermediateVT.getVectorNumElements() * NumParts
     397       22322 :                               : NumIntermediates));
     398        8171 :     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
     399             :                                                 : ISD::BUILD_VECTOR,
     400       16342 :                       DL, BuiltVectorTy, Ops);
     401             :   }
     402             : 
     403             :   // There is now one part, held in Val.  Correct it to match ValueVT.
     404      265798 :   EVT PartEVT = Val.getValueType();
     405             : 
     406      133538 :   if (PartEVT == ValueVT)
     407      128040 :     return Val;
     408             : 
     409        4859 :   if (PartEVT.isVector()) {
     410             :     // If the element type of the source/dest vectors are the same, but the
     411             :     // parts vector has more elements than the value vector, then we have a
     412             :     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
     413             :     // elements we want.
     414        8164 :     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
     415             :       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
     416             :              "Cannot narrow, it would be a lossy transformation");
     417             :       return DAG.getNode(
     418             :           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
     419        2856 :           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
     420             :     }
     421             : 
     422             :     // Vector/Vector bitcast.
     423        3130 :     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
     424        1793 :       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
     425             : 
     426             :     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
     427             :       "Cannot handle this kind of promotion");
     428             :     // Promoted vector extract
     429        1337 :     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
     430             : 
     431             :   }
     432             : 
     433             :   // Trivial bitcast if the types are the same size and the destination
     434             :   // vector type is legal.
     435         777 :   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
     436             :       TLI.isTypeLegal(ValueVT))
     437          18 :     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
     438             : 
     439         759 :   if (ValueVT.getVectorNumElements() != 1) {
     440             :      // Certain ABIs require that vectors are passed as integers. For vectors
     441             :      // are the same size, this is an obvious bitcast.
     442         194 :      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
     443         106 :        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
     444          88 :      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
     445             :        // Bitcast Val back the original type and extract the corresponding
     446             :        // vector we want.
     447          80 :        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
     448          80 :        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
     449         160 :                                            ValueVT.getVectorElementType(), Elts);
     450          80 :        Val = DAG.getBitcast(WiderVecType, Val);
     451             :        return DAG.getNode(
     452             :            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
     453         240 :            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
     454             :      }
     455             : 
     456           8 :      diagnosePossiblyInvalidConstraint(
     457           8 :          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
     458           8 :      return DAG.getUNDEF(ValueVT);
     459             :   }
     460             : 
     461             :   // Handle cases such as i8 -> <1 x i1>
     462         565 :   EVT ValueSVT = ValueVT.getVectorElementType();
     463         565 :   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
     464          83 :     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
     465             :                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
     466             : 
     467         565 :   return DAG.getBuildVector(ValueVT, DL, Val);
     468             : }
     469             : 
     470             : static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
     471             :                                  SDValue Val, SDValue *Parts, unsigned NumParts,
     472             :                                  MVT PartVT, const Value *V, bool IsABIRegCopy);
     473             : 
     474             : /// getCopyToParts - Create a series of nodes that contain the specified value
     475             : /// split into legal parts.  If the parts contain more bits than Val, then, for
     476             : /// integers, ExtendKind can be used to specify how to generate the extra bits.
     477      735965 : static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
     478             :                            SDValue *Parts, unsigned NumParts, MVT PartVT,
     479             :                            const Value *V,
     480             :                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND,
     481             :                            bool IsABIRegCopy = false) {
     482      735965 :   EVT ValueVT = Val.getValueType();
     483             : 
     484             :   // Handle the vector case separately.
     485      735965 :   if (ValueVT.isVector())
     486       83020 :     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
     487       83020 :                                 IsABIRegCopy);
     488             : 
     489      652945 :   unsigned PartBits = PartVT.getSizeInBits();
     490             :   unsigned OrigNumParts = NumParts;
     491             :   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
     492             :          "Copying to an illegal type!");
     493             : 
     494      652945 :   if (NumParts == 0)
     495             :     return;
     496             : 
     497             :   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
     498             :   EVT PartEVT = PartVT;
     499           0 :   if (PartEVT == ValueVT) {
     500             :     assert(NumParts == 1 && "No-op copy with multiple parts!");
     501      624492 :     Parts[0] = Val;
     502      624492 :     return;
     503             :   }
     504             : 
     505       28453 :   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
     506             :     // If the parts cover more bits than the value has, promote the value.
     507       17654 :     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
     508             :       assert(NumParts == 1 && "Do not know what to promote to!");
     509         122 :       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
     510             :     } else {
     511       17532 :       if (ValueVT.isFloatingPoint()) {
     512             :         // FP values need to be bitcast, then extended if they are being put
     513             :         // into a larger container.
     514          22 :         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
     515          22 :         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
     516             :       }
     517             :       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
     518             :              ValueVT.isInteger() &&
     519             :              "Unknown mismatch!");
     520       17532 :       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
     521       17532 :       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
     522       17532 :       if (PartVT == MVT::x86mmx)
     523           1 :         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
     524             :     }
     525       10799 :   } else if (PartBits == ValueVT.getSizeInBits()) {
     526             :     // Different types of the same size.
     527             :     assert(NumParts == 1 && PartEVT != ValueVT);
     528         647 :     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
     529       10152 :   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
     530             :     // If the parts cover less bits than value has, truncate the value.
     531             :     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
     532             :            ValueVT.isInteger() &&
     533             :            "Unknown mismatch!");
     534         369 :     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
     535         369 :     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
     536         369 :     if (PartVT == MVT::x86mmx)
     537           0 :       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
     538             :   }
     539             : 
     540             :   // The value may have changed - recompute ValueVT.
     541       28453 :   ValueVT = Val.getValueType();
     542             :   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
     543             :          "Failed to tile the value with PartVT!");
     544             : 
     545       28453 :   if (NumParts == 1) {
     546           0 :     if (PartEVT != ValueVT) {
     547           4 :       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
     548             :                                         "scalar-to-vector conversion failed");
     549           4 :       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
     550             :     }
     551             : 
     552       18639 :     Parts[0] = Val;
     553       18639 :     return;
     554             :   }
     555             : 
     556             :   // Expand the value into multiple parts.
     557        9814 :   if (NumParts & (NumParts - 1)) {
     558             :     // The number of parts is not a power of 2.  Split off and copy the tail.
     559             :     assert(PartVT.isInteger() && ValueVT.isInteger() &&
     560             :            "Do not know what to expand to!");
     561          22 :     unsigned RoundParts = 1 << Log2_32(NumParts);
     562          22 :     unsigned RoundBits = RoundParts * PartBits;
     563          22 :     unsigned OddParts = NumParts - RoundParts;
     564             :     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
     565          22 :                                  DAG.getIntPtrConstant(RoundBits, DL));
     566          22 :     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
     567             : 
     568          44 :     if (DAG.getDataLayout().isBigEndian())
     569             :       // The odd parts were reversed by getCopyToParts - unreverse them.
     570           3 :       std::reverse(Parts + RoundParts, Parts + NumParts);
     571             : 
     572             :     NumParts = RoundParts;
     573          22 :     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
     574          22 :     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
     575             :   }
     576             : 
     577             :   // The number of parts is a power of 2.  Repeatedly bisect the value using
     578             :   // EXTRACT_ELEMENT.
     579        9814 :   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
     580        9814 :                          EVT::getIntegerVT(*DAG.getContext(),
     581             :                                            ValueVT.getSizeInBits()),
     582       29442 :                          Val);
     583             : 
     584       31252 :   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
     585       35175 :     for (unsigned i = 0; i < NumParts; i += StepSize) {
     586       12228 :       unsigned ThisBits = StepSize * PartBits / 2;
     587       12228 :       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
     588       12228 :       SDValue &Part0 = Parts[i];
     589       12228 :       SDValue &Part1 = Parts[i+StepSize/2];
     590             : 
     591       12228 :       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
     592       24456 :                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
     593       12228 :       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
     594       24456 :                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
     595             : 
     596       12228 :       if (ThisBits == PartBits && ThisVT != PartVT) {
     597         172 :         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
     598         172 :         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
     599             :       }
     600             :     }
     601             :   }
     602             : 
     603       19628 :   if (DAG.getDataLayout().isBigEndian())
     604        2385 :     std::reverse(Parts, Parts + OrigNumParts);
     605             : }
     606             : 
     607             : 
     608             : /// getCopyToPartsVector - Create a series of nodes that contain the specified
     609             : /// value split into legal parts.
     610       83020 : static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
     611             :                                  SDValue Val, SDValue *Parts, unsigned NumParts,
     612             :                                  MVT PartVT, const Value *V,
     613             :                                  bool IsABIRegCopy) {
     614       83020 :   EVT ValueVT = Val.getValueType();
     615             :   assert(ValueVT.isVector() && "Not a vector");
     616       83020 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     617             : 
     618       83020 :   if (NumParts == 1) {
     619             :     EVT PartEVT = PartVT;
     620           0 :     if (PartEVT == ValueVT) {
     621             :       // Nothing to do.
     622        2886 :     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
     623             :       // Bitconvert vector->vector case.
     624        1375 :       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
     625           0 :     } else if (PartVT.isVector() &&
     626        2581 :                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
     627         535 :                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
     628         535 :       EVT ElementVT = PartVT.getVectorElementType();
     629             :       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
     630             :       // undef elements.
     631             :       SmallVector<SDValue, 16> Ops;
     632        1940 :       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
     633        1405 :         Ops.push_back(DAG.getNode(
     634             :             ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
     635        5620 :             DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
     636             : 
     637        2460 :       for (unsigned i = ValueVT.getVectorNumElements(),
     638         535 :            e = PartVT.getVectorNumElements(); i != e; ++i)
     639        1925 :         Ops.push_back(DAG.getUNDEF(ElementVT));
     640             : 
     641         535 :       Val = DAG.getBuildVector(PartVT, DL, Ops);
     642             : 
     643             :       // FIXME: Use CONCAT for 2x -> 4x.
     644             : 
     645             :       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
     646             :       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
     647         882 :     } else if (PartVT.isVector() &&
     648        1858 :                PartEVT.getVectorElementType().bitsGE(
     649        1858 :                  ValueVT.getVectorElementType()) &&
     650         882 :                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
     651             : 
     652             :       // Promoted vector extract
     653         882 :       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
     654             :     } else {
     655          94 :       if (ValueVT.getVectorNumElements() == 1) {
     656          54 :         Val = DAG.getNode(
     657             :             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
     658         216 :             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
     659             :       } else {
     660             :         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
     661             :                "lossy conversion of vector to scalar type");
     662             :         EVT IntermediateType =
     663          40 :             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
     664          40 :         Val = DAG.getBitcast(IntermediateType, Val);
     665          40 :         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
     666             :       }
     667             :     }
     668             : 
     669             :     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
     670       78557 :     Parts[0] = Val;
     671             :     return;
     672             :   }
     673             : 
     674             :   // Handle a multi-element vector.
     675        4463 :   EVT IntermediateVT;
     676        4463 :   MVT RegisterVT;
     677             :   unsigned NumIntermediates;
     678             :   unsigned NumRegs;
     679        4463 :   if (IsABIRegCopy) {
     680        7618 :     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
     681        3809 :         *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
     682        3809 :         RegisterVT);
     683             :   } else {
     684         654 :     NumRegs =
     685         654 :         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
     686             :                                    NumIntermediates, RegisterVT);
     687             :   }
     688        4463 :   unsigned NumElements = ValueVT.getVectorNumElements();
     689             : 
     690             :   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
     691             :   NumParts = NumRegs; // Silence a compiler warning.
     692             :   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
     693             : 
     694             :   // Convert the vector to the appropiate type if necessary.
     695             :   unsigned DestVectorNoElts =
     696        4463 :       NumIntermediates *
     697        8926 :       (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1);
     698             :   EVT BuiltVectorTy = EVT::getVectorVT(
     699        4463 :       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
     700        4749 :   if (Val.getValueType() != BuiltVectorTy)
     701         189 :     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
     702             : 
     703             :   // Split the vector into intermediate operands.
     704        8926 :   SmallVector<SDValue, 8> Ops(NumIntermediates);
     705       27489 :   for (unsigned i = 0; i != NumIntermediates; ++i) {
     706       11513 :     if (IntermediateVT.isVector())
     707       16578 :       Ops[i] =
     708       16578 :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
     709        8289 :                       DAG.getConstant(i * (NumElements / NumIntermediates), DL,
     710       33156 :                                       TLI.getVectorIdxTy(DAG.getDataLayout())));
     711             :     else
     712        6448 :       Ops[i] = DAG.getNode(
     713             :           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
     714       12896 :           DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
     715             :   }
     716             : 
     717             :   // Split the intermediate operands into legal parts.
     718        4463 :   if (NumParts == NumIntermediates) {
     719             :     // If the register was not expanded, promote or copy the value,
     720             :     // as appropriate.
     721       26469 :     for (unsigned i = 0; i != NumParts; ++i)
     722       22134 :       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
     723         128 :   } else if (NumParts > 0) {
     724             :     // If the intermediate type was expanded, split each the value into
     725             :     // legal parts.
     726             :     assert(NumIntermediates != 0 && "division by zero");
     727             :     assert(NumParts % NumIntermediates == 0 &&
     728             :            "Must expand into a divisible number of parts!");
     729         128 :     unsigned Factor = NumParts / NumIntermediates;
     730        1020 :     for (unsigned i = 0; i != NumIntermediates; ++i)
     731         892 :       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
     732             :   }
     733             : }
     734             : 
     735       57769 : RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
     736       57769 :                            EVT valuevt, bool IsABIMangledValue)
     737             :     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
     738      115538 :       RegCount(1, regs.size()), IsABIMangled(IsABIMangledValue) {}
     739             : 
     740      268618 : RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
     741             :                            const DataLayout &DL, unsigned Reg, Type *Ty,
     742      537236 :                            bool IsABIMangledValue) {
     743      268618 :   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
     744             : 
     745      268618 :   IsABIMangled = IsABIMangledValue;
     746             : 
     747      821616 :   for (EVT ValueVT : ValueVTs) {
     748             :     unsigned NumRegs = IsABIMangledValue
     749      544755 :                            ? TLI.getNumRegistersForCallingConv(Context, ValueVT)
     750      544755 :                            : TLI.getNumRegisters(Context, ValueVT);
     751             :     MVT RegisterVT = IsABIMangledValue
     752        8243 :                          ? TLI.getRegisterTypeForCallingConv(Context, ValueVT)
     753      284742 :                          : TLI.getRegisterType(Context, ValueVT);
     754      850851 :     for (unsigned i = 0; i != NumRegs; ++i)
     755      287176 :       Regs.push_back(Reg + i);
     756      276499 :     RegVTs.push_back(RegisterVT);
     757      276499 :     RegCount.push_back(NumRegs);
     758      276499 :     Reg += NumRegs;
     759             :   }
     760      268618 : }
     761             : 
     762      143581 : SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
     763             :                                       FunctionLoweringInfo &FuncInfo,
     764             :                                       const SDLoc &dl, SDValue &Chain,
     765             :                                       SDValue *Flag, const Value *V) const {
     766             :   // A Value with type {} or [0 x %t] needs no registers.
     767      143581 :   if (ValueVTs.empty())
     768           0 :     return SDValue();
     769             : 
     770      143581 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     771             : 
     772             :   // Assemble the legal parts into the final values.
     773      287162 :   SmallVector<SDValue, 4> Values(ValueVTs.size());
     774             :   SmallVector<SDValue, 8> Parts;
     775      289093 :   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
     776             :     // Copy the legal parts from the registers.
     777      291024 :     EVT ValueVT = ValueVTs[Value];
     778      145512 :     unsigned NumRegs = RegCount[Value];
     779      145512 :     MVT RegisterVT = IsABIMangled
     780        5265 :                          ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
     781      291024 :                          : RegVTs[Value];
     782             : 
     783      145512 :     Parts.resize(NumRegs);
     784      448360 :     for (unsigned i = 0; i != NumRegs; ++i) {
     785             :       SDValue P;
     786      151424 :       if (!Flag) {
     787      295126 :         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
     788             :       } else {
     789        7722 :         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
     790        3861 :         *Flag = P.getValue(2);
     791             :       }
     792             : 
     793      151424 :       Chain = P.getValue(1);
     794      302848 :       Parts[i] = P;
     795             : 
     796             :       // If the source register was virtual and if we know something about it,
     797             :       // add an assert node.
     798      471354 :       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
     799      292647 :           !RegisterVT.isInteger() || RegisterVT.isVector())
     800      135221 :         continue;
     801             : 
     802             :       const FunctionLoweringInfo::LiveOutInfo *LOI =
     803             :         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
     804       72419 :       if (!LOI)
     805       72419 :         continue;
     806             : 
     807       61283 :       unsigned RegSize = RegisterVT.getSizeInBits();
     808       61283 :       unsigned NumSignBits = LOI->NumSignBits;
     809             :       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
     810             : 
     811       63131 :       if (NumZeroBits == RegSize) {
     812             :         // The current value is a zero.
     813             :         // Explicitly express that as it would be easier for
     814             :         // optimizations to kick in.
     815        3696 :         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
     816        1848 :         continue;
     817             :       }
     818             : 
     819             :       // FIXME: We capture more information than the dag can represent.  For
     820             :       // now, just use the tightest assertzext/assertsext possible.
     821             :       bool isSExt = true;
     822       59435 :       EVT FromVT(MVT::Other);
     823       59435 :       if (NumSignBits == RegSize) {
     824             :         isSExt = true;   // ASSERT SEXT 1
     825         590 :         FromVT = MVT::i1;
     826       58845 :       } else if (NumZeroBits >= RegSize - 1) {
     827             :         isSExt = false;  // ASSERT ZEXT 1
     828        7372 :         FromVT = MVT::i1;
     829       51473 :       } else if (NumSignBits > RegSize - 8) {
     830             :         isSExt = true;   // ASSERT SEXT 8
     831        1234 :         FromVT = MVT::i8;
     832       50239 :       } else if (NumZeroBits >= RegSize - 8) {
     833             :         isSExt = false;  // ASSERT ZEXT 8
     834        1334 :         FromVT = MVT::i8;
     835       48905 :       } else if (NumSignBits > RegSize - 16) {
     836             :         isSExt = true;   // ASSERT SEXT 16
     837         516 :         FromVT = MVT::i16;
     838       48389 :       } else if (NumZeroBits >= RegSize - 16) {
     839             :         isSExt = false;  // ASSERT ZEXT 16
     840         352 :         FromVT = MVT::i16;
     841       48037 :       } else if (NumSignBits > RegSize - 32) {
     842             :         isSExt = true;   // ASSERT SEXT 32
     843        2848 :         FromVT = MVT::i32;
     844       70699 :       } else if (NumZeroBits >= RegSize - 32) {
     845             :         isSExt = false;  // ASSERT ZEXT 32
     846       19679 :         FromVT = MVT::i32;
     847             :       } else {
     848       25510 :         continue;
     849             :       }
     850             :       // Add an assertion node.
     851             :       assert(FromVT != MVT::Other);
     852       67850 :       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
     853      101775 :                              RegisterVT, P, DAG.getValueType(FromVT));
     854             :     }
     855             : 
     856      291024 :     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
     857      145512 :                                      NumRegs, RegisterVT, ValueVT, V);
     858      145512 :     Part += NumRegs;
     859             :     Parts.clear();
     860             :   }
     861             : 
     862      143581 :   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
     863             : }
     864             : 
     865      134372 : void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
     866             :                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
     867             :                                  const Value *V,
     868             :                                  ISD::NodeType PreferredExtendType) const {
     869      134372 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     870             :   ISD::NodeType ExtendKind = PreferredExtendType;
     871             : 
     872             :   // Get the list of the values's legal parts.
     873      134372 :   unsigned NumRegs = Regs.size();
     874      268744 :   SmallVector<SDValue, 8> Parts(NumRegs);
     875      275080 :   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
     876      281416 :     unsigned NumParts = RegCount[Value];
     877             : 
     878      140708 :     MVT RegisterVT = IsABIMangled
     879        2978 :                          ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
     880      281416 :                          : RegVTs[Value];
     881             : 
     882      280518 :     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
     883             :       ExtendKind = ISD::ZERO_EXTEND;
     884             : 
     885      140708 :     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
     886      140708 :                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
     887      140708 :     Part += NumParts;
     888             :   }
     889             : 
     890             :   // Copy the parts into the registers.
     891      268744 :   SmallVector<SDValue, 8> Chains(NumRegs);
     892      425594 :   for (unsigned i = 0; i != NumRegs; ++i) {
     893             :     SDValue Part;
     894      145611 :     if (!Flag) {
     895      279136 :       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
     896             :     } else {
     897       12086 :       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
     898        6043 :       *Flag = Part.getValue(1);
     899             :     }
     900             : 
     901      291222 :     Chains[i] = Part.getValue(0);
     902             :   }
     903             : 
     904      134372 :   if (NumRegs == 1 || Flag)
     905             :     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
     906             :     // flagged to it. That is the CopyToReg nodes and the user are considered
     907             :     // a single scheduling unit. If we create a TokenFactor and return it as
     908             :     // chain, then the TokenFactor is both a predecessor (operand) of the
     909             :     // user as well as a successor (the TF operands are flagged to the user).
     910             :     // c1, f1 = CopyToReg
     911             :     // c2, f2 = CopyToReg
     912             :     // c3     = TokenFactor c1, c2
     913             :     // ...
     914             :     //        = op c3, ..., f2
     915      252144 :     Chain = Chains[NumRegs-1];
     916             :   else
     917        8300 :     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
     918      134372 : }
     919             : 
     920       57765 : void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
     921             :                                         unsigned MatchingIdx, const SDLoc &dl,
     922             :                                         SelectionDAG &DAG,
     923             :                                         std::vector<SDValue> &Ops) const {
     924       57765 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
     925             : 
     926       57765 :   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
     927       57765 :   if (HasMatching)
     928             :     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
     929      115008 :   else if (!Regs.empty() &&
     930       57504 :            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
     931             :     // Put the register class of the virtual registers in the flag word.  That
     932             :     // way, later passes can recompute register class constraints for inline
     933             :     // assembly as well as normal instructions.
     934             :     // Don't do this for tied operands that can use the regclass information
     935             :     // from the def.
     936        8255 :     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
     937             :     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
     938        8255 :     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
     939             :   }
     940             : 
     941      115530 :   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
     942       57765 :   Ops.push_back(Res);
     943             : 
     944       57765 :   if (Code == InlineAsm::Kind_Clobber) {
     945             :     // Clobbers should always have a 1:1 mapping with registers, and may
     946             :     // reference registers that have illegal (e.g. vector) types. Hence, we
     947             :     // shouldn't try to apply any sort of splitting logic to them.
     948             :     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
     949             :            "No 1:1 mapping from clobbers to regs?");
     950             :     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
     951             :     (void)SP;
     952       95970 :     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
     953      143955 :       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
     954             :       assert(
     955             :           (Regs[I] != SP ||
     956             :            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
     957             :           "If we clobbered the stack pointer, MFI should know about it.");
     958             :     }
     959       47985 :     return;
     960             :   }
     961             : 
     962       19560 :   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
     963       19560 :     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
     964        9780 :     MVT RegisterVT = RegVTs[Value];
     965       29632 :     for (unsigned i = 0; i != NumRegs; ++i) {
     966             :       assert(Reg < Regs.size() && "Mismatch in # registers expected");
     967       19852 :       unsigned TheReg = Regs[Reg++];
     968       19852 :       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
     969             :     }
     970             :   }
     971             : }
     972             : 
     973      200874 : void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
     974             :                                const TargetLibraryInfo *li) {
     975      200874 :   AA = aa;
     976      200874 :   GFI = gfi;
     977      200874 :   LibInfo = li;
     978      401748 :   DL = &DAG.getDataLayout();
     979      200874 :   Context = DAG.getContext();
     980      200874 :   LPadToCallSiteMap.clear();
     981      200874 : }
     982             : 
     983      332254 : void SelectionDAGBuilder::clear() {
     984      332254 :   NodeMap.clear();
     985      332254 :   UnusedArgNodeMap.clear();
     986             :   PendingLoads.clear();
     987             :   PendingExports.clear();
     988      332254 :   CurInst = nullptr;
     989      332254 :   HasTailCall = false;
     990      332254 :   SDNodeOrder = LowestSDNodeOrder;
     991      332254 :   StatepointLowering.clear();
     992      332254 : }
     993             : 
     994      200799 : void SelectionDAGBuilder::clearDanglingDebugInfo() {
     995      200799 :   DanglingDebugInfoMap.clear();
     996      200799 : }
     997             : 
     998      745742 : SDValue SelectionDAGBuilder::getRoot() {
     999      745742 :   if (PendingLoads.empty())
    1000      521958 :     return DAG.getRoot();
    1001             : 
    1002      223784 :   if (PendingLoads.size() == 1) {
    1003      190558 :     SDValue Root = PendingLoads[0];
    1004      190558 :     DAG.setRoot(Root);
    1005             :     PendingLoads.clear();
    1006      190558 :     return Root;
    1007             :   }
    1008             : 
    1009             :   // Otherwise, we have to make a token factor node.
    1010       99678 :   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
    1011       66452 :                              PendingLoads);
    1012             :   PendingLoads.clear();
    1013       33226 :   DAG.setRoot(Root);
    1014       33226 :   return Root;
    1015             : }
    1016             : 
    1017      643592 : SDValue SelectionDAGBuilder::getControlRoot() {
    1018      643592 :   SDValue Root = DAG.getRoot();
    1019             : 
    1020      643592 :   if (PendingExports.empty())
    1021      561904 :     return Root;
    1022             : 
    1023             :   // Turn all of the CopyToReg chains into one factored node.
    1024      163376 :   if (Root.getOpcode() != ISD::EntryToken) {
    1025       57310 :     unsigned i = 0, e = PendingExports.size();
    1026      236026 :     for (; i != e; ++i) {
    1027             :       assert(PendingExports[i].getNode()->getNumOperands() > 1);
    1028      178716 :       if (PendingExports[i].getNode()->getOperand(0) == Root)
    1029             :         break;  // Don't add the root if we already indirectly depend on it.
    1030             :     }
    1031             : 
    1032       57310 :     if (i == e)
    1033       57310 :       PendingExports.push_back(Root);
    1034             :   }
    1035             : 
    1036      326752 :   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
    1037       81688 :                      PendingExports);
    1038             :   PendingExports.clear();
    1039       81688 :   DAG.setRoot(Root);
    1040       81688 :   return Root;
    1041             : }
    1042             : 
    1043     2225391 : void SelectionDAGBuilder::visit(const Instruction &I) {
    1044             :   // Set up outgoing PHI node register values before emitting the terminator.
    1045     2225391 :   if (isa<TerminatorInst>(&I)) {
    1046      312022 :     HandlePHINodesInSuccessorBlocks(I.getParent());
    1047             :   }
    1048             : 
    1049             :   // Increase the SDNodeOrder if dealing with a non-debug instruction.
    1050             :   if (!isa<DbgInfoIntrinsic>(I))
    1051     2177131 :     ++SDNodeOrder;
    1052             : 
    1053     2225391 :   CurInst = &I;
    1054             : 
    1055     4450782 :   visit(I.getOpcode(), I);
    1056             : 
    1057     4136136 :   if (!isa<TerminatorInst>(&I) && !HasTailCall &&
    1058     1910751 :       !isStatepoint(&I)) // statepoints handle their exports internally
    1059     1910693 :     CopyToExportRegsIfNeeded(&I);
    1060             : 
    1061     2225385 :   CurInst = nullptr;
    1062     2225385 : }
    1063             : 
    1064           0 : void SelectionDAGBuilder::visitPHI(const PHINode &) {
    1065           0 :   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
    1066             : }
    1067             : 
    1068     2541561 : void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
    1069             :   // Note: this doesn't use InstVisitor, because it has to work with
    1070             :   // ConstantExpr's in addition to instructions.
    1071     2541561 :   switch (Opcode) {
    1072           0 :   default: llvm_unreachable("Unknown instruction type encountered!");
    1073             :     // Build the switch statement using the Instruction.def file.
    1074             : #define HANDLE_INST(NUM, OPCODE, CLASS) \
    1075             :     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
    1076             : #include "llvm/IR/Instruction.def"
    1077             :   }
    1078     2541555 : }
    1079             : 
    1080             : // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
    1081             : // generate the debug data structures now that we've seen its definition.
    1082     1669310 : void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
    1083             :                                                    SDValue Val) {
    1084     1669310 :   DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
    1085     1669310 :   if (DDI.getDI()) {
    1086             :     const DbgValueInst *DI = DDI.getDI();
    1087             :     DebugLoc dl = DDI.getdl();
    1088        3772 :     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
    1089             :     DILocalVariable *Variable = DI->getVariable();
    1090             :     DIExpression *Expr = DI->getExpression();
    1091             :     assert(Variable->isValidLocationForIntrinsic(dl) &&
    1092             :            "Expected inlined-at fields to agree");
    1093             :     SDDbgValue *SDV;
    1094        3772 :     if (Val.getNode()) {
    1095        3772 :       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
    1096        2724 :         SDV = getDbgValue(Val, Variable, Expr, dl, DbgSDNodeOrder);
    1097        2724 :         DAG.AddDbgValue(SDV, Val.getNode(), false);
    1098             :       }
    1099             :     } else
    1100             :       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
    1101        7544 :     DanglingDebugInfoMap[V] = DanglingDebugInfo();
    1102             :   }
    1103     1669310 : }
    1104             : 
    1105             : /// getCopyFromRegs - If there was virtual register allocated for the value V
    1106             : /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
    1107     1659728 : SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
    1108     1659728 :   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
    1109             :   SDValue Result;
    1110             : 
    1111     3319456 :   if (It != FuncInfo.ValueMap.end()) {
    1112      138483 :     unsigned InReg = It->second;
    1113             : 
    1114      276966 :     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
    1115      553932 :                      DAG.getDataLayout(), InReg, Ty, isABIRegCopy(V));
    1116      276966 :     SDValue Chain = DAG.getEntryNode();
    1117      415449 :     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
    1118      138483 :                                  V);
    1119      138483 :     resolveDanglingDebugInfo(V, Result);
    1120             :   }
    1121             : 
    1122     1659728 :   return Result;
    1123             : }
    1124             : 
    1125             : /// getValue - Return an SDValue for the given Value.
    1126     3982451 : SDValue SelectionDAGBuilder::getValue(const Value *V) {
    1127             :   // If we already have an SDValue for this value, use it. It's important
    1128             :   // to do this first, so that we don't create a CopyFromReg if we already
    1129             :   // have a regular SDValue.
    1130     3982451 :   SDValue &N = NodeMap[V];
    1131     3982451 :   if (N.getNode()) return N;
    1132             : 
    1133             :   // If there's a virtual register allocated and initialized for this
    1134             :   // value, use it.
    1135     1659726 :   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
    1136      138481 :     return copyFromReg;
    1137             : 
    1138             :   // Otherwise create a new SDValue and remember it.
    1139     1521245 :   SDValue Val = getValueImpl(V);
    1140     1521245 :   NodeMap[V] = Val;
    1141     1521245 :   resolveDanglingDebugInfo(V, Val);
    1142     1521245 :   return Val;
    1143             : }
    1144             : 
    1145             : // Return true if SDValue exists for the given Value
    1146         395 : bool SelectionDAGBuilder::findValue(const Value *V) const {
    1147         839 :   return (NodeMap.find(V) != NodeMap.end()) ||
    1148         888 :     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
    1149             : }
    1150             : 
    1151             : /// getNonRegisterValue - Return an SDValue for the given Value, but
    1152             : /// don't look in FuncInfo.ValueMap for a virtual register.
    1153      128407 : SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
    1154             :   // If we already have an SDValue for this value, use it.
    1155      128407 :   SDValue &N = NodeMap[V];
    1156      128407 :   if (N.getNode()) {
    1157             :     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
    1158             :       // Remove the debug location from the node as the node is about to be used
    1159             :       // in a location which may differ from the original debug location.  This
    1160             :       // is relevant to Constant and ConstantFP nodes because they can appear
    1161             :       // as constant expressions inside PHI nodes.
    1162        3110 :       N->setDebugLoc(DebugLoc());
    1163             :     }
    1164      118825 :     return N;
    1165             :   }
    1166             : 
    1167             :   // Otherwise create a new SDValue and remember it.
    1168        9582 :   SDValue Val = getValueImpl(V);
    1169        9582 :   NodeMap[V] = Val;
    1170        9582 :   resolveDanglingDebugInfo(V, Val);
    1171        9582 :   return Val;
    1172             : }
    1173             : 
    1174             : /// getValueImpl - Helper function for getValue and getNonRegisterValue.
    1175             : /// Create an SDValue for the given value.
    1176     1530827 : SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
    1177     1530827 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    1178             : 
    1179     1530827 :   if (const Constant *C = dyn_cast<Constant>(V)) {
    1180     2793552 :     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
    1181             : 
    1182             :     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
    1183     1188912 :       return DAG.getConstant(*CI, getCurSDLoc(), VT);
    1184             : 
    1185             :     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
    1186     1689762 :       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
    1187             : 
    1188      437218 :     if (isa<ConstantPointerNull>(C)) {
    1189       19128 :       unsigned AS = V->getType()->getPointerAddressSpace();
    1190       57384 :       return DAG.getConstant(0, getCurSDLoc(),
    1191       57384 :                              TLI.getPointerTy(DAG.getDataLayout(), AS));
    1192             :     }
    1193             : 
    1194             :     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
    1195       44904 :       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
    1196             : 
    1197      403122 :     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
    1198       24853 :       return DAG.getUNDEF(VT);
    1199             : 
    1200             :     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
    1201      632340 :       visit(CE->getOpcode(), *CE);
    1202      632340 :       SDValue N1 = NodeMap[V];
    1203             :       assert(N1.getNode() && "visit didn't populate the NodeMap!");
    1204      316170 :       return N1;
    1205             :     }
    1206             : 
    1207       62099 :     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
    1208             :       SmallVector<SDValue, 4> Constants;
    1209         163 :       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
    1210         163 :            OI != OE; ++OI) {
    1211         120 :         SDNode *Val = getValue(*OI).getNode();
    1212             :         // If the operand is an empty aggregate, there are no values.
    1213         120 :         if (!Val) continue;
    1214             :         // Add each leaf value from the operand to the Constants list
    1215             :         // to form a flattened list of all the values.
    1216         490 :         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
    1217         126 :           Constants.push_back(SDValue(Val, i));
    1218             :       }
    1219             : 
    1220         129 :       return DAG.getMergeValues(Constants, getCurSDLoc());
    1221             :     }
    1222             : 
    1223             :     if (const ConstantDataSequential *CDS =
    1224             :           dyn_cast<ConstantDataSequential>(C)) {
    1225             :       SmallVector<SDValue, 4> Ops;
    1226      241077 :       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
    1227      194211 :         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
    1228             :         // Add each leaf value from the operand to the Constants list
    1229             :         // to form a flattened list of all the values.
    1230      776844 :         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
    1231      194211 :           Ops.push_back(SDValue(Val, i));
    1232             :       }
    1233             : 
    1234       46866 :       if (isa<ArrayType>(CDS->getType()))
    1235          15 :         return DAG.getMergeValues(Ops, getCurSDLoc());
    1236      234305 :       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
    1237             :     }
    1238             : 
    1239       30380 :     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
    1240             :       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
    1241             :              "Unknown struct or array constant!");
    1242             : 
    1243             :       SmallVector<EVT, 4> ValueVTs;
    1244        1142 :       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
    1245         571 :       unsigned NumElts = ValueVTs.size();
    1246         571 :       if (NumElts == 0)
    1247           1 :         return SDValue(); // empty struct
    1248        1140 :       SmallVector<SDValue, 4> Constants(NumElts);
    1249        4802 :       for (unsigned i = 0; i != NumElts; ++i) {
    1250        4232 :         EVT EltVT = ValueVTs[i];
    1251        2116 :         if (isa<UndefValue>(C))
    1252        3584 :           Constants[i] = DAG.getUNDEF(EltVT);
    1253         324 :         else if (EltVT.isFloatingPoint())
    1254         120 :           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
    1255             :         else
    1256        1176 :           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
    1257             :       }
    1258             : 
    1259        1710 :       return DAG.getMergeValues(Constants, getCurSDLoc());
    1260             :     }
    1261             : 
    1262             :     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
    1263         114 :       return DAG.getBlockAddress(BA, VT);
    1264             : 
    1265       14505 :     VectorType *VecTy = cast<VectorType>(V->getType());
    1266       14505 :     unsigned NumElements = VecTy->getNumElements();
    1267             : 
    1268             :     // Now that we know the number and type of the elements, get that number of
    1269             :     // elements into the Ops array based on what kind of constant it is.
    1270             :     SmallVector<SDValue, 16> Ops;
    1271             :     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
    1272       34125 :       for (unsigned i = 0; i != NumElements; ++i)
    1273       32684 :         Ops.push_back(getValue(CV->getOperand(i)));
    1274             :     } else {
    1275             :       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
    1276             :       EVT EltVT =
    1277       26128 :           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
    1278             : 
    1279       13064 :       SDValue Op;
    1280       13064 :       if (EltVT.isFloatingPoint())
    1281        8967 :         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
    1282             :       else
    1283       30225 :         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
    1284       13064 :       Ops.assign(NumElements, Op);
    1285             :     }
    1286             : 
    1287             :     // Create a BUILD_VECTOR node.
    1288       72525 :     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
    1289             :   }
    1290             : 
    1291             :   // If this is a static alloca, generate it as the frameindex instead of
    1292             :   // computation.
    1293             :   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
    1294             :     DenseMap<const AllocaInst*, int>::iterator SI =
    1295      132364 :       FuncInfo.StaticAllocaMap.find(AI);
    1296      264728 :     if (SI != FuncInfo.StaticAllocaMap.end())
    1297      132364 :       return DAG.getFrameIndex(SI->second,
    1298      397092 :                                TLI.getFrameIndexTy(DAG.getDataLayout()));
    1299             :   }
    1300             : 
    1301             :   // If this is an instruction which fast-isel has deferred, select it now.
    1302        1687 :   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
    1303        1687 :     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
    1304             : 
    1305        3374 :     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
    1306        6748 :                      Inst->getType(), isABIRegCopy(V));
    1307        3374 :     SDValue Chain = DAG.getEntryNode();
    1308        5061 :     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
    1309             :   }
    1310             : 
    1311           0 :   llvm_unreachable("Can't get register for value!");
    1312             : }
    1313             : 
    1314         105 : void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
    1315         105 :   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
    1316         105 :   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
    1317         105 :   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
    1318         105 :   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
    1319             :   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
    1320         105 :   if (IsMSVCCXX || IsCoreCLR)
    1321             :     CatchPadMBB->setIsEHFuncletEntry();
    1322             : 
    1323         525 :   DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot()));
    1324         105 : }
    1325             : 
    1326          88 : void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
    1327             :   // Update machine-CFG edge.
    1328         176 :   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
    1329          88 :   FuncInfo.MBB->addSuccessor(TargetMBB);
    1330             : 
    1331          88 :   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
    1332             :   bool IsSEH = isAsynchronousEHPersonality(Pers);
    1333             :   if (IsSEH) {
    1334             :     // If this is not a fall-through branch or optimizations are switched off,
    1335             :     // emit the branch.
    1336          43 :     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
    1337          17 :         TM.getOptLevel() == CodeGenOpt::None)
    1338          40 :       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
    1339          30 :                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
    1340          26 :     return;
    1341             :   }
    1342             : 
    1343             :   // Figure out the funclet membership for the catchret's successor.
    1344             :   // This will be used by the FuncletLayout pass to determine how to order the
    1345             :   // BB's.
    1346             :   // A 'catchret' returns to the outer scope's color.
    1347             :   Value *ParentPad = I.getCatchSwitchParentPad();
    1348             :   const BasicBlock *SuccessorColor;
    1349          62 :   if (isa<ConstantTokenNone>(ParentPad))
    1350         112 :     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
    1351             :   else
    1352           6 :     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
    1353             :   assert(SuccessorColor && "No parent funclet for catchret!");
    1354         124 :   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
    1355             :   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
    1356             : 
    1357             :   // Create the terminator node.
    1358         186 :   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
    1359          62 :                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
    1360         248 :                             DAG.getBasicBlock(SuccessorColorMBB));
    1361          62 :   DAG.setRoot(Ret);
    1362             : }
    1363             : 
    1364          40 : void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
    1365             :   // Don't emit any special code for the cleanuppad instruction. It just marks
    1366             :   // the start of a funclet.
    1367          40 :   FuncInfo.MBB->setIsEHFuncletEntry();
    1368          40 :   FuncInfo.MBB->setIsCleanupFuncletEntry();
    1369          40 : }
    1370             : 
    1371             : /// When an invoke or a cleanupret unwinds to the next EH pad, there are
    1372             : /// many places it could ultimately go. In the IR, we have a single unwind
    1373             : /// destination, but in the machine CFG, we enumerate all the possible blocks.
    1374             : /// This function skips over imaginary basic blocks that hold catchswitch
    1375             : /// instructions, and finds all the "real" machine
    1376             : /// basic block destinations. As those destinations may not be successors of
    1377             : /// EHPadBB, here we also calculate the edge probability to those destinations.
    1378             : /// The passed-in Prob is the edge probability to EHPadBB.
    1379       41187 : static void findUnwindDestinations(
    1380             :     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
    1381             :     BranchProbability Prob,
    1382             :     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
    1383             :         &UnwindDests) {
    1384             :   EHPersonality Personality =
    1385       41187 :     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
    1386       41187 :   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
    1387       41187 :   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
    1388             : 
    1389       41305 :   while (EHPadBB) {
    1390       41193 :     const Instruction *Pad = EHPadBB->getFirstNonPHI();
    1391             :     BasicBlock *NewEHPadBB = nullptr;
    1392       41193 :     if (isa<LandingPadInst>(Pad)) {
    1393             :       // Stop on landingpads. They are not funclets.
    1394       82022 :       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
    1395       41011 :       break;
    1396         182 :     } else if (isa<CleanupPadInst>(Pad)) {
    1397             :       // Stop on cleanup pads. Cleanups are always funclet entries for all known
    1398             :       // personalities.
    1399         128 :       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
    1400          64 :       UnwindDests.back().first->setIsEHFuncletEntry();
    1401             :       break;
    1402           0 :     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
    1403             :       // Add the catchpad handlers to the possible destinations.
    1404         376 :       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
    1405         258 :         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
    1406             :         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
    1407         129 :         if (IsMSVCCXX || IsCoreCLR)
    1408          91 :           UnwindDests.back().first->setIsEHFuncletEntry();
    1409             :       }
    1410             :       NewEHPadBB = CatchSwitch->getUnwindDest();
    1411             :     } else {
    1412             :       continue;
    1413             :     }
    1414             : 
    1415         118 :     BranchProbabilityInfo *BPI = FuncInfo.BPI;
    1416         118 :     if (BPI && NewEHPadBB)
    1417          28 :       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
    1418         118 :     EHPadBB = NewEHPadBB;
    1419             :   }
    1420       41187 : }
    1421             : 
    1422          32 : void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
    1423             :   // Update successor info.
    1424             :   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
    1425             :   auto UnwindDest = I.getUnwindDest();
    1426          32 :   BranchProbabilityInfo *BPI = FuncInfo.BPI;
    1427             :   BranchProbability UnwindDestProb =
    1428          32 :       (BPI && UnwindDest)
    1429          10 :           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
    1430          42 :           : BranchProbability::getZero();
    1431          32 :   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
    1432          54 :   for (auto &UnwindDest : UnwindDests) {
    1433          11 :     UnwindDest.first->setIsEHPad();
    1434          11 :     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
    1435             :   }
    1436          32 :   FuncInfo.MBB->normalizeSuccProbs();
    1437             : 
    1438             :   // Create the terminator node.
    1439             :   SDValue Ret =
    1440         160 :       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
    1441          32 :   DAG.setRoot(Ret);
    1442          32 : }
    1443             : 
    1444           0 : void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
    1445           0 :   report_fatal_error("visitCatchSwitch not yet implemented!");
    1446             : }
    1447             : 
    1448      157751 : void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
    1449      157751 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    1450      157751 :   auto &DL = DAG.getDataLayout();
    1451      157751 :   SDValue Chain = getControlRoot();
    1452             :   SmallVector<ISD::OutputArg, 8> Outs;
    1453             :   SmallVector<SDValue, 8> OutVals;
    1454             : 
    1455             :   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
    1456             :   // lower
    1457             :   //
    1458             :   //   %val = call <ty> @llvm.experimental.deoptimize()
    1459             :   //   ret <ty> %val
    1460             :   //
    1461             :   // differently.
    1462      157751 :   if (I.getParent()->getTerminatingDeoptimizeCall()) {
    1463           0 :     LowerDeoptimizingReturn();
    1464             :     return;
    1465             :   }
    1466             : 
    1467      157751 :   if (!FuncInfo.CanLowerReturn) {
    1468         536 :     unsigned DemoteReg = FuncInfo.DemoteRegister;
    1469         536 :     const Function *F = I.getParent()->getParent();
    1470             : 
    1471             :     // Emit a store of the return value through the virtual register.
    1472             :     // Leave Outs empty so that LowerReturn won't try to load return
    1473             :     // registers the usual way.
    1474             :     SmallVector<EVT, 1> PtrValueVTs;
    1475         536 :     ComputeValueVTs(TLI, DL,
    1476         536 :                     F->getReturnType()->getPointerTo(
    1477         536 :                         DAG.getDataLayout().getAllocaAddrSpace()),
    1478             :                     PtrValueVTs);
    1479             : 
    1480        2144 :     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
    1481         536 :                                         DemoteReg, PtrValueVTs[0]);
    1482         536 :     SDValue RetOp = getValue(I.getOperand(0));
    1483             : 
    1484             :     SmallVector<EVT, 4> ValueVTs;
    1485             :     SmallVector<uint64_t, 4> Offsets;
    1486         536 :     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
    1487         536 :     unsigned NumValues = ValueVTs.size();
    1488             : 
    1489        1072 :     SmallVector<SDValue, 4> Chains(NumValues);
    1490        2060 :     for (unsigned i = 0; i != NumValues; ++i) {
    1491             :       // An aggregate return value cannot wrap around the address space, so
    1492             :       // offsets to its parts don't wrap either.
    1493        3048 :       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
    1494        2286 :       Chains[i] = DAG.getStore(
    1495        2286 :           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
    1496             :           // FIXME: better loc info would be nice.
    1497        2286 :           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
    1498             :     }
    1499             : 
    1500        2144 :     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
    1501         536 :                         MVT::Other, Chains);
    1502      157215 :   } else if (I.getNumOperands() != 0) {
    1503             :     SmallVector<EVT, 4> ValueVTs;
    1504      107179 :     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
    1505      107179 :     unsigned NumValues = ValueVTs.size();
    1506      107179 :     if (NumValues) {
    1507      107178 :       SDValue RetOp = getValue(I.getOperand(0));
    1508             : 
    1509      107178 :       const Function *F = I.getParent()->getParent();
    1510             : 
    1511             :       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
    1512      107178 :       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
    1513             :                                           Attribute::SExt))
    1514             :         ExtendKind = ISD::SIGN_EXTEND;
    1515      103471 :       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
    1516             :                                                Attribute::ZExt))
    1517             :         ExtendKind = ISD::ZERO_EXTEND;
    1518             : 
    1519      107178 :       LLVMContext &Context = F->getContext();
    1520      214356 :       bool RetInReg = F->getAttributes().hasAttribute(
    1521      107178 :           AttributeList::ReturnIndex, Attribute::InReg);
    1522             : 
    1523      325654 :       for (unsigned j = 0; j != NumValues; ++j) {
    1524      218476 :         EVT VT = ValueVTs[j];
    1525             : 
    1526      109238 :         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
    1527        6795 :           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
    1528             : 
    1529      109238 :         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT);
    1530      109238 :         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT);
    1531      218476 :         SmallVector<SDValue, 4> Parts(NumParts);
    1532      546190 :         getCopyToParts(DAG, getCurSDLoc(),
    1533      109238 :                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
    1534             :                        &Parts[0], NumParts, PartVT, &I, ExtendKind, true);
    1535             : 
    1536             :         // 'inreg' on function refers to return value
    1537             :         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
    1538      109238 :         if (RetInReg)
    1539             :           Flags.setInReg();
    1540             : 
    1541             :         // Propagate extension type if any
    1542      109238 :         if (ExtendKind == ISD::SIGN_EXTEND)
    1543             :           Flags.setSExt();
    1544      105531 :         else if (ExtendKind == ISD::ZERO_EXTEND)
    1545             :           Flags.setZExt();
    1546             : 
    1547      344612 :         for (unsigned i = 0; i < NumParts; ++i) {
    1548      353061 :           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
    1549             :                                         VT, /*isfixed=*/true, 0, 0));
    1550      117687 :           OutVals.push_back(Parts[i]);
    1551             :         }
    1552             :       }
    1553             :     }
    1554             :   }
    1555             : 
    1556             :   // Push in swifterror virtual register as the last element of Outs. This makes
    1557             :   // sure swifterror virtual register will be returned in the swifterror
    1558             :   // physical register.
    1559      157751 :   const Function *F = I.getParent()->getParent();
    1560      255985 :   if (TLI.supportSwiftError() &&
    1561      255873 :       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
    1562             :     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
    1563             :     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
    1564             :     Flags.setSwiftError();
    1565         112 :     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
    1566             :                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
    1567             :                                   true /*isfixed*/, 1 /*origidx*/,
    1568             :                                   0 /*partOffs*/));
    1569             :     // Create SDNode for the swifterror virtual register.
    1570         112 :     OutVals.push_back(
    1571         560 :         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
    1572         112 :                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
    1573         224 :                         EVT(TLI.getPointerTy(DL))));
    1574             :   }
    1575             : 
    1576      157751 :   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
    1577             :   CallingConv::ID CallConv =
    1578             :     DAG.getMachineFunction().getFunction().getCallingConv();
    1579      315502 :   Chain = DAG.getTargetLoweringInfo().LowerReturn(
    1580      473253 :       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
    1581             : 
    1582             :   // Verify that the target's LowerReturn behaved as expected.
    1583             :   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
    1584             :          "LowerReturn didn't return a valid chain!");
    1585             : 
    1586             :   // Update the DAG with the new chain value resulting from return lowering.
    1587      157751 :   DAG.setRoot(Chain);
    1588             : }
    1589             : 
    1590             : /// CopyToExportRegsIfNeeded - If the given value has virtual registers
    1591             : /// created for it, emit nodes to copy the value into the virtual
    1592             : /// registers.
    1593     1971778 : void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
    1594             :   // Skip empty types
    1595     1971778 :   if (V->getType()->isEmptyTy())
    1596          16 :     return;
    1597             : 
    1598     1971762 :   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
    1599     3943524 :   if (VMI != FuncInfo.ValueMap.end()) {
    1600             :     assert(!V->use_empty() && "Unused value assigned virtual registers!");
    1601      116991 :     CopyValueToVirtualRegister(V, VMI->second);
    1602             :   }
    1603             : }
    1604             : 
    1605             : /// ExportFromCurrentBlock - If this condition isn't known to be exported from
    1606             : /// the current basic block, add it to ValueMap now so that we'll get a
    1607             : /// CopyTo/FromReg.
    1608        2025 : void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
    1609             :   // No need to export constants.
    1610        2025 :   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
    1611             : 
    1612             :   // Already exported?
    1613        1596 :   if (FuncInfo.isExportedInst(V)) return;
    1614             : 
    1615         757 :   unsigned Reg = FuncInfo.InitializeRegForValue(V);
    1616         757 :   CopyValueToVirtualRegister(V, Reg);
    1617             : }
    1618             : 
    1619         654 : bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
    1620             :                                                      const BasicBlock *FromBB) {
    1621             :   // The operands of the setcc have to be in this block.  We don't know
    1622             :   // how to export them from some other block.
    1623             :   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
    1624             :     // Can export from current BB.
    1625         295 :     if (VI->getParent() == FromBB)
    1626             :       return true;
    1627             : 
    1628             :     // Is already exported, noop.
    1629         146 :     return FuncInfo.isExportedInst(V);
    1630             :   }
    1631             : 
    1632             :   // If this is an argument, we can export it if the BB is the entry block or
    1633             :   // if it is already exported.
    1634         359 :   if (isa<Argument>(V)) {
    1635         208 :     if (FromBB == &FromBB->getParent()->getEntryBlock())
    1636             :       return true;
    1637             : 
    1638             :     // Otherwise, can only export this if it is already exported.
    1639          82 :     return FuncInfo.isExportedInst(V);
    1640             :   }
    1641             : 
    1642             :   // Otherwise, constants can always be exported.
    1643             :   return true;
    1644             : }
    1645             : 
    1646             : /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
    1647             : BranchProbability
    1648      107287 : SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
    1649             :                                         const MachineBasicBlock *Dst) const {
    1650      107287 :   BranchProbabilityInfo *BPI = FuncInfo.BPI;
    1651      107287 :   const BasicBlock *SrcBB = Src->getBasicBlock();
    1652      107287 :   const BasicBlock *DstBB = Dst->getBasicBlock();
    1653      107287 :   if (!BPI) {
    1654             :     // If BPI is not available, set the default probability as 1 / N, where N is
    1655             :     // the number of successors.
    1656             :     auto SuccSize = std::max<uint32_t>(
    1657        1074 :         std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1);
    1658         537 :     return BranchProbability(1, SuccSize);
    1659             :   }
    1660      106750 :   return BPI->getEdgeProbability(SrcBB, DstBB);
    1661             : }
    1662             : 
    1663      168968 : void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
    1664             :                                                MachineBasicBlock *Dst,
    1665             :                                                BranchProbability Prob) {
    1666      168968 :   if (!FuncInfo.BPI)
    1667       31184 :     Src->addSuccessorWithoutProb(Dst);
    1668             :   else {
    1669      137784 :     if (Prob.isUnknown())
    1670      105506 :       Prob = getEdgeProbability(Src, Dst);
    1671      137784 :     Src->addSuccessor(Dst, Prob);
    1672             :   }
    1673      168968 : }
    1674             : 
    1675             : static bool InBlock(const Value *V, const BasicBlock *BB) {
    1676             :   if (const Instruction *I = dyn_cast<Instruction>(V))
    1677         750 :     return I->getParent() == BB;
    1678             :   return true;
    1679             : }
    1680             : 
    1681             : /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
    1682             : /// This function emits a branch and is used at the leaves of an OR or an
    1683             : /// AND operator tree.
    1684             : void
    1685         745 : SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
    1686             :                                                   MachineBasicBlock *TBB,
    1687             :                                                   MachineBasicBlock *FBB,
    1688             :                                                   MachineBasicBlock *CurBB,
    1689             :                                                   MachineBasicBlock *SwitchBB,
    1690             :                                                   BranchProbability TProb,
    1691             :                                                   BranchProbability FProb,
    1692             :                                                   bool InvertCond) {
    1693         745 :   const BasicBlock *BB = CurBB->getBasicBlock();
    1694             : 
    1695             :   // If the leaf of the tree is a comparison, merge the condition into
    1696             :   // the caseblock.
    1697             :   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
    1698             :     // The operands of the cmp have to be in this block.  We don't know
    1699             :     // how to export them from some other block.  If this is the first block
    1700             :     // of the sequence, no exporting is needed.
    1701         965 :     if (CurBB == SwitchBB ||
    1702         654 :         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
    1703         327 :          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
    1704             :       ISD::CondCode Condition;
    1705             :       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
    1706             :         ICmpInst::Predicate Pred =
    1707         591 :             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
    1708         591 :         Condition = getICmpCondCode(Pred);
    1709             :       } else {
    1710             :         const FCmpInst *FC = cast<FCmpInst>(Cond);
    1711             :         FCmpInst::Predicate Pred =
    1712          47 :             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
    1713          47 :         Condition = getFCmpCondCode(Pred);
    1714          47 :         if (TM.Options.NoNaNsFPMath)
    1715           0 :           Condition = getFCmpCodeWithoutNaN(Condition);
    1716             :       }
    1717             : 
    1718             :       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
    1719        1276 :                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
    1720         638 :       SwitchCases.push_back(CB);
    1721             :       return;
    1722             :     }
    1723             :   }
    1724             : 
    1725             :   // Create a CaseBlock record representing this branch.
    1726         107 :   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
    1727         107 :   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
    1728         214 :                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
    1729         107 :   SwitchCases.push_back(CB);
    1730             : }
    1731             : 
    1732             : /// FindMergedConditions - If Cond is an expression like
    1733        1158 : void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
    1734             :                                                MachineBasicBlock *TBB,
    1735             :                                                MachineBasicBlock *FBB,
    1736             :                                                MachineBasicBlock *CurBB,
    1737             :                                                MachineBasicBlock *SwitchBB,
    1738             :                                                Instruction::BinaryOps Opc,
    1739             :                                                BranchProbability TProb,
    1740             :                                                BranchProbability FProb,
    1741             :                                                bool InvertCond) {
    1742             :   // Skip over not part of the tree and remember to invert op and operands at
    1743             :   // next level.
    1744        1182 :   if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
    1745          21 :     const Value *CondOp = BinaryOperator::getNotArgument(Cond);
    1746          39 :     if (InBlock(CondOp, CurBB->getBasicBlock())) {
    1747          20 :       FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
    1748          20 :                            !InvertCond);
    1749          20 :       return;
    1750             :     }
    1751             :   }
    1752             : 
    1753             :   const Instruction *BOp = dyn_cast<Instruction>(Cond);
    1754             :   // Compute the effective opcode for Cond, taking into account whether it needs
    1755             :   // to be inverted, e.g.
    1756             :   //   and (not (or A, B)), C
    1757             :   // gets lowered as
    1758             :   //   and (and (not A, not B), C)
    1759             :   unsigned BOpc = 0;
    1760             :   if (BOp) {
    1761             :     BOpc = BOp->getOpcode();
    1762        1068 :     if (InvertCond) {
    1763          31 :       if (BOpc == Instruction::And)
    1764             :         BOpc = Instruction::Or;
    1765          28 :       else if (BOpc == Instruction::Or)
    1766             :         BOpc = Instruction::And;
    1767             :     }
    1768             :   }
    1769             : 
    1770             :   // If this node is not part of the or/and tree, emit it as a branch.
    1771        2126 :   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
    1772         808 :       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
    1773         781 :       BOp->getParent() != CurBB->getBasicBlock() ||
    1774        1893 :       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
    1775             :       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
    1776         745 :     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
    1777             :                                  TProb, FProb, InvertCond);
    1778         745 :     return;
    1779             :   }
    1780             : 
    1781             :   //  Create TmpBB after CurBB.
    1782             :   MachineFunction::iterator BBI(CurBB);
    1783         393 :   MachineFunction &MF = DAG.getMachineFunction();
    1784         393 :   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
    1785         393 :   CurBB->getParent()->insert(++BBI, TmpBB);
    1786             : 
    1787         393 :   if (Opc == Instruction::Or) {
    1788             :     // Codegen X | Y as:
    1789             :     // BB1:
    1790             :     //   jmp_if_X TBB
    1791             :     //   jmp TmpBB
    1792             :     // TmpBB:
    1793             :     //   jmp_if_Y TBB
    1794             :     //   jmp FBB
    1795             :     //
    1796             : 
    1797             :     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
    1798             :     // The requirement is that
    1799             :     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
    1800             :     //     = TrueProb for original BB.
    1801             :     // Assuming the original probabilities are A and B, one choice is to set
    1802             :     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
    1803             :     // A/(1+B) and 2B/(1+B). This choice assumes that
    1804             :     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
    1805             :     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
    1806             :     // TmpBB, but the math is more complicated.
    1807             : 
    1808         176 :     auto NewTrueProb = TProb / 2;
    1809         176 :     auto NewFalseProb = TProb / 2 + FProb;
    1810             :     // Emit the LHS condition.
    1811         352 :     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
    1812             :                          NewTrueProb, NewFalseProb, InvertCond);
    1813             : 
    1814             :     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
    1815         352 :     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
    1816         176 :     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
    1817             :     // Emit the RHS condition into TmpBB.
    1818         176 :     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
    1819             :                          Probs[0], Probs[1], InvertCond);
    1820             :   } else {
    1821             :     assert(Opc == Instruction::And && "Unknown merge op!");
    1822             :     // Codegen X & Y as:
    1823             :     // BB1:
    1824             :     //   jmp_if_X TmpBB
    1825             :     //   jmp FBB
    1826             :     // TmpBB:
    1827             :     //   jmp_if_Y TBB
    1828             :     //   jmp FBB
    1829             :     //
    1830             :     //  This requires creation of TmpBB after CurBB.
    1831             : 
    1832             :     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
    1833             :     // The requirement is that
    1834             :     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
    1835             :     //     = FalseProb for original BB.
    1836             :     // Assuming the original probabilities are A and B, one choice is to set
    1837             :     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
    1838             :     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
    1839             :     // TrueProb for BB1 * FalseProb for TmpBB.
    1840             : 
    1841         217 :     auto NewTrueProb = TProb + FProb / 2;
    1842         217 :     auto NewFalseProb = FProb / 2;
    1843             :     // Emit the LHS condition.
    1844         434 :     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
    1845             :                          NewTrueProb, NewFalseProb, InvertCond);
    1846             : 
    1847             :     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
    1848         434 :     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
    1849         217 :     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
    1850             :     // Emit the RHS condition into TmpBB.
    1851         217 :     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
    1852             :                          Probs[0], Probs[1], InvertCond);
    1853             :   }
    1854             : }
    1855             : 
    1856             : /// If the set of cases should be emitted as a series of branches, return true.
    1857             : /// If we should emit this as a bunch of and/or'd together conditions, return
    1858             : /// false.
    1859             : bool
    1860         352 : SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
    1861         704 :   if (Cases.size() != 2) return true;
    1862             : 
    1863             :   // If this is two comparisons of the same values or'd or and'd together, they
    1864             :   // will get folded into a single comparison, so don't emit two blocks.
    1865         337 :   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
    1866         625 :        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
    1867         309 :       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
    1868           1 :        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
    1869             :     return false;
    1870             :   }
    1871             : 
    1872             :   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
    1873             :   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
    1874         374 :   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
    1875         116 :       Cases[0].CC == Cases[1].CC &&
    1876         358 :       isa<Constant>(Cases[0].CmpRHS) &&
    1877          50 :       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
    1878          29 :     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
    1879             :       return false;
    1880          28 :     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
    1881             :       return false;
    1882             :   }
    1883             : 
    1884             :   return true;
    1885             : }
    1886             : 
    1887       99150 : void SelectionDAGBuilder::visitBr(const BranchInst &I) {
    1888       99150 :   MachineBasicBlock *BrMBB = FuncInfo.MBB;
    1889             : 
    1890             :   // Update machine-CFG edges.
    1891      198300 :   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
    1892             : 
    1893       99150 :   if (I.isUnconditional()) {
    1894             :     // Update machine-CFG edges.
    1895       59432 :     BrMBB->addSuccessor(Succ0MBB);
    1896             : 
    1897             :     // If this is not a fall-through branch or optimizations are switched off,
    1898             :     // emit the branch.
    1899       59432 :     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
    1900      122320 :       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
    1901             :                               MVT::Other, getControlRoot(),
    1902       91740 :                               DAG.getBasicBlock(Succ0MBB)));
    1903             : 
    1904       59773 :     return;
    1905             :   }
    1906             : 
    1907             :   // If this condition is one of the special cases we handle, do special stuff
    1908             :   // now.
    1909             :   const Value *CondVal = I.getCondition();
    1910       79436 :   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
    1911             : 
    1912             :   // If this is a series of conditions that are or'd or and'd together, emit
    1913             :   // this as a sequence of branches instead of setcc's with and/or operations.
    1914             :   // As long as jumps are not expensive, this should improve performance.
    1915             :   // For example, instead of something like:
    1916             :   //     cmp A, B
    1917             :   //     C = seteq
    1918             :   //     cmp D, E
    1919             :   //     F = setle
    1920             :   //     or C, F
    1921             :   //     jnz foo
    1922             :   // Emit:
    1923             :   //     cmp A, B
    1924             :   //     je foo
    1925             :   //     cmp D, E
    1926             :   //     jle foo
    1927             :   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
    1928             :     Instruction::BinaryOps Opcode = BOp->getOpcode();
    1929        1241 :     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
    1930        1303 :         !I.getMetadata(LLVMContext::MD_unpredictable) &&
    1931         365 :         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
    1932         352 :       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
    1933             :                            Opcode,
    1934             :                            getEdgeProbability(BrMBB, Succ0MBB),
    1935             :                            getEdgeProbability(BrMBB, Succ1MBB),
    1936             :                            /*InvertCond=*/false);
    1937             :       // If the compares in later blocks need to use values not currently
    1938             :       // exported from this block, export them now.  This block should always
    1939             :       // be the first entry.
    1940             :       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
    1941             : 
    1942             :       // Allow some cases to be rejected.
    1943         352 :       if (ShouldEmitAsBranches(SwitchCases)) {
    1944        1064 :         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
    1945         764 :           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
    1946         764 :           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
    1947             :         }
    1948             : 
    1949             :         // Emit the branch for this block.
    1950         341 :         visitSwitchCase(SwitchCases[0], BrMBB);
    1951             :         SwitchCases.erase(SwitchCases.begin());
    1952         341 :         return;
    1953             :       }
    1954             : 
    1955             :       // Okay, we decided not to do this, remove any inserted MBB's and clear
    1956             :       // SwitchCases.
    1957          33 :       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
    1958          22 :         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
    1959             : 
    1960          11 :       SwitchCases.clear();
    1961             :     }
    1962             :   }
    1963             : 
    1964             :   // Create a CaseBlock record representing this branch.
    1965       39377 :   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
    1966       78754 :                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
    1967             : 
    1968             :   // Use visitSwitchCase to actually insert the fast branch sequence for this
    1969             :   // cond branch.
    1970       39377 :   visitSwitchCase(CB, BrMBB);
    1971             : }
    1972             : 
    1973             : /// visitSwitchCase - Emits the necessary code to represent a single node in
    1974             : /// the binary search tree resulting from lowering a switch instruction.
    1975       42203 : void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
    1976             :                                           MachineBasicBlock *SwitchBB) {
    1977             :   SDValue Cond;
    1978       42203 :   SDValue CondLHS = getValue(CB.CmpLHS);
    1979             :   SDLoc dl = CB.DL;
    1980             : 
    1981             :   // Build the setcc now.
    1982       42203 :   if (!CB.CmpMHS) {
    1983             :     // Fold "(X == true)" to X and "(X == false)" to !X to
    1984             :     // handle common cases produced by branch lowering.
    1985       81416 :     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
    1986       39481 :         CB.CC == ISD::SETEQ)
    1987             :       Cond = CondLHS;
    1988        2463 :     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
    1989           3 :              CB.CC == ISD::SETEQ) {
    1990           6 :       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
    1991           6 :       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
    1992             :     } else
    1993        4914 :       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
    1994             :   } else {
    1995             :     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
    1996             : 
    1997         268 :     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
    1998         268 :     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
    1999             : 
    2000         268 :     SDValue CmpOp = getValue(CB.CmpMHS);
    2001         536 :     EVT VT = CmpOp.getValueType();
    2002             : 
    2003         268 :     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
    2004           2 :       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
    2005           2 :                           ISD::SETLE);
    2006             :     } else {
    2007         267 :       SDValue SUB = DAG.getNode(ISD::SUB, dl,
    2008         267 :                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
    2009         534 :       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
    2010        1068 :                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
    2011             :     }
    2012             :   }
    2013             : 
    2014             :   // Update successor info
    2015       42203 :   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
    2016             :   // TrueBB and FalseBB are always different unless the incoming IR is
    2017             :   // degenerate. This only happens when running llc on weird IR.
    2018       42203 :   if (CB.TrueBB != CB.FalseBB)
    2019       42198 :     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
    2020             :   SwitchBB->normalizeSuccProbs();
    2021             : 
    2022             :   // If the lhs block is the next block, invert the condition so that we can
    2023             :   // fall through to the lhs instead of the rhs block.
    2024       42203 :   if (CB.TrueBB == NextBlock(SwitchBB)) {
    2025             :     std::swap(CB.TrueBB, CB.FalseBB);
    2026       47958 :     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
    2027       47958 :     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
    2028             :   }
    2029             : 
    2030       42203 :   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
    2031             :                                MVT::Other, getControlRoot(), Cond,
    2032       84406 :                                DAG.getBasicBlock(CB.TrueBB));
    2033             : 
    2034             :   // Insert the false branch. Do this even if it's a fall through branch,
    2035             :   // this makes it easier to do DAG optimizations which require inverting
    2036             :   // the branch condition.
    2037       84406 :   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
    2038       84406 :                        DAG.getBasicBlock(CB.FalseBB));
    2039             : 
    2040       42203 :   DAG.setRoot(BrCond);
    2041       42203 : }
    2042             : 
    2043             : /// visitJumpTable - Emit JumpTable node in the current MBB
    2044         198 : void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
    2045             :   // Emit the code for the jump table
    2046             :   assert(JT.Reg != -1U && "Should lower JT Header first!");
    2047         198 :   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
    2048         594 :   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
    2049         396 :                                      JT.Reg, PTy);
    2050         198 :   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
    2051         594 :   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
    2052             :                                     MVT::Other, Index.getValue(1),
    2053         594 :                                     Table, Index);
    2054         198 :   DAG.setRoot(BrJumpTable);
    2055         198 : }
    2056             : 
    2057             : /// visitJumpTableHeader - This function emits necessary code to produce index
    2058             : /// in the JumpTable from switch case.
    2059         198 : void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
    2060             :                                                JumpTableHeader &JTH,
    2061             :                                                MachineBasicBlock *SwitchBB) {
    2062         198 :   SDLoc dl = getCurSDLoc();
    2063             : 
    2064             :   // Subtract the lowest switch case value from the value being switched on and
    2065             :   // conditional branch to default mbb if the result is greater than the
    2066             :   // difference between smallest and largest cases.
    2067         198 :   SDValue SwitchOp = getValue(JTH.SValue);
    2068         198 :   EVT VT = SwitchOp.getValueType();
    2069         198 :   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
    2070         198 :                             DAG.getConstant(JTH.First, dl, VT));
    2071             : 
    2072             :   // The SDNode we just created, which holds the value being switched on minus
    2073             :   // the smallest case value, needs to be copied to a virtual register so it
    2074             :   // can be used as an index into the jump table in a subsequent basic block.
    2075             :   // This value may be smaller or larger than the target's pointer type, and
    2076             :   // therefore require extension or truncating.
    2077         198 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2078         396 :   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
    2079             : 
    2080             :   unsigned JumpTableReg =
    2081         396 :       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
    2082         198 :   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
    2083         198 :                                     JumpTableReg, SwitchOp);
    2084         198 :   JT.Reg = JumpTableReg;
    2085             : 
    2086             :   // Emit the range check for the jump table, and branch to the default block
    2087             :   // for the switch statement if the value being switched on exceeds the largest
    2088             :   // case in the switch.
    2089         198 :   SDValue CMP = DAG.getSetCC(
    2090         198 :       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
    2091         198 :                                  Sub.getValueType()),
    2092        1386 :       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
    2093             : 
    2094         198 :   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
    2095             :                                MVT::Other, CopyTo, CMP,
    2096         396 :                                DAG.getBasicBlock(JT.Default));
    2097             : 
    2098             :   // Avoid emitting unnecessary branches to the next block.
    2099         198 :   if (JT.MBB != NextBlock(SwitchBB))
    2100          54 :     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
    2101          54 :                          DAG.getBasicBlock(JT.MBB));
    2102             : 
    2103         198 :   DAG.setRoot(BrCond);
    2104         198 : }
    2105             : 
    2106             : /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
    2107             : /// variable if there exists one.
    2108         431 : static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
    2109             :                                  SDValue &Chain) {
    2110         431 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2111         431 :   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
    2112         431 :   MachineFunction &MF = DAG.getMachineFunction();
    2113         431 :   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
    2114             :   MachineSDNode *Node =
    2115         431 :       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
    2116         431 :   if (Global) {
    2117             :     MachinePointerInfo MPInfo(Global);
    2118         416 :     MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
    2119             :     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
    2120             :                  MachineMemOperand::MODereferenceable;
    2121         416 :     *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8,
    2122             :                                        DAG.getEVTAlignment(PtrTy));
    2123         416 :     Node->setMemRefs(MemRefs, MemRefs + 1);
    2124             :   }
    2125         431 :   return SDValue(Node, 0);
    2126             : }
    2127             : 
    2128             : /// Codegen a new tail for a stack protector check ParentMBB which has had its
    2129             : /// tail spliced into a stack protector check success bb.
    2130             : ///
    2131             : /// For a high level explanation of how this fits into the stack protector
    2132             : /// generation see the comment on the declaration of class
    2133             : /// StackProtectorDescriptor.
    2134         268 : void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
    2135             :                                                   MachineBasicBlock *ParentBB) {
    2136             : 
    2137             :   // First create the loads to the guard/stack slot for the comparison.
    2138         268 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2139         268 :   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
    2140             : 
    2141         268 :   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
    2142         268 :   int FI = MFI.getStackProtectorIndex();
    2143             : 
    2144             :   SDValue Guard;
    2145         268 :   SDLoc dl = getCurSDLoc();
    2146         268 :   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
    2147         268 :   const Module &M = *ParentBB->getParent()->getFunction().getParent();
    2148         268 :   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
    2149             : 
    2150             :   // Generate code to load the content of the guard slot.
    2151         268 :   SDValue GuardVal = DAG.getLoad(
    2152         268 :       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
    2153             :       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
    2154         536 :       MachineMemOperand::MOVolatile);
    2155             : 
    2156         268 :   if (TLI.useStackGuardXorFP())
    2157          78 :     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
    2158             : 
    2159             :   // Retrieve guard check function, nullptr if instrumentation is inlined.
    2160         268 :   if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
    2161             :     // The target provides a guard check function to validate the guard value.
    2162             :     // Generate a call to that function with the content of the guard slot as
    2163             :     // argument.
    2164             :     auto *Fn = cast<Function>(GuardCheck);
    2165             :     FunctionType *FnTy = Fn->getFunctionType();
    2166             :     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
    2167             : 
    2168             :     TargetLowering::ArgListTy Args;
    2169             :     TargetLowering::ArgListEntry Entry;
    2170          78 :     Entry.Node = GuardVal;
    2171         156 :     Entry.Ty = FnTy->getParamType(0);
    2172          78 :     if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
    2173          78 :       Entry.IsInReg = true;
    2174          78 :     Args.push_back(Entry);
    2175             : 
    2176         156 :     TargetLowering::CallLoweringInfo CLI(DAG);
    2177         156 :     CLI.setDebugLoc(getCurSDLoc())
    2178          78 :       .setChain(DAG.getEntryNode())
    2179             :       .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
    2180          78 :                  getValue(GuardCheck), std::move(Args));
    2181             : 
    2182          78 :     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
    2183          78 :     DAG.setRoot(Result.second);
    2184             :     return;
    2185             :   }
    2186             : 
    2187             :   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
    2188             :   // Otherwise, emit a volatile load to retrieve the stack guard value.
    2189         380 :   SDValue Chain = DAG.getEntryNode();
    2190         190 :   if (TLI.useLoadStackGuardNode()) {
    2191         139 :     Guard = getLoadStackGuard(DAG, dl, Chain);
    2192             :   } else {
    2193          51 :     const Value *IRGuard = TLI.getSDagStackGuard(M);
    2194          51 :     SDValue GuardPtr = getValue(IRGuard);
    2195             : 
    2196          51 :     Guard =
    2197         153 :         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
    2198          51 :                     Align, MachineMemOperand::MOVolatile);
    2199             :   }
    2200             : 
    2201             :   // Perform the comparison via a subtract/getsetcc.
    2202         190 :   EVT VT = Guard.getValueType();
    2203         380 :   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
    2204             : 
    2205         190 :   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
    2206         190 :                                                         *DAG.getContext(),
    2207         190 :                                                         Sub.getValueType()),
    2208         760 :                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
    2209             : 
    2210             :   // If the sub is not 0, then we know the guard/stackslot do not equal, so
    2211             :   // branch to failure MBB.
    2212         190 :   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
    2213             :                                MVT::Other, GuardVal.getOperand(0),
    2214         380 :                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
    2215             :   // Otherwise branch to success MBB.
    2216         190 :   SDValue Br = DAG.getNode(ISD::BR, dl,
    2217             :                            MVT::Other, BrCond,
    2218         380 :                            DAG.getBasicBlock(SPD.getSuccessMBB()));
    2219             : 
    2220         190 :   DAG.setRoot(Br);
    2221             : }
    2222             : 
    2223             : /// Codegen the failure basic block for a stack protector check.
    2224             : ///
    2225             : /// A failure stack protector machine basic block consists simply of a call to
    2226             : /// __stack_chk_fail().
    2227             : ///
    2228             : /// For a high level explanation of how this fits into the stack protector
    2229             : /// generation see the comment on the declaration of class
    2230             : /// StackProtectorDescriptor.
    2231             : void
    2232         185 : SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
    2233         185 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2234             :   SDValue Chain =
    2235         370 :       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
    2236         925 :                       None, false, getCurSDLoc(), false, false).second;
    2237         185 :   DAG.setRoot(Chain);
    2238         185 : }
    2239             : 
    2240             : /// visitBitTestHeader - This function emits necessary code to produce value
    2241             : /// suitable for "bit tests"
    2242          26 : void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
    2243             :                                              MachineBasicBlock *SwitchBB) {
    2244          26 :   SDLoc dl = getCurSDLoc();
    2245             : 
    2246             :   // Subtract the minimum value
    2247          26 :   SDValue SwitchOp = getValue(B.SValue);
    2248          52 :   EVT VT = SwitchOp.getValueType();
    2249          26 :   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
    2250          26 :                             DAG.getConstant(B.First, dl, VT));
    2251             : 
    2252             :   // Check range
    2253          26 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2254             :   SDValue RangeCmp = DAG.getSetCC(
    2255          26 :       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
    2256          26 :                                  Sub.getValueType()),
    2257          78 :       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
    2258             : 
    2259             :   // Determine the type of the test operands.
    2260             :   bool UsePtrType = false;
    2261             :   if (!TLI.isTypeLegal(VT))
    2262             :     UsePtrType = true;
    2263             :   else {
    2264          57 :     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
    2265          76 :       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
    2266             :         // Switch table case range are encoded into series of masks.
    2267             :         // Just use pointer type, it's guaranteed to fit.
    2268             :         UsePtrType = true;
    2269             :         break;
    2270             :       }
    2271             :   }
    2272          26 :   if (UsePtrType) {
    2273          14 :     VT = TLI.getPointerTy(DAG.getDataLayout());
    2274           7 :     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
    2275             :   }
    2276             : 
    2277          26 :   B.RegVT = VT.getSimpleVT();
    2278          26 :   B.Reg = FuncInfo.CreateReg(B.RegVT);
    2279          26 :   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
    2280             : 
    2281          26 :   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
    2282             : 
    2283          26 :   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
    2284          26 :   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
    2285             :   SwitchBB->normalizeSuccProbs();
    2286             : 
    2287          26 :   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
    2288             :                                 MVT::Other, CopyTo, RangeCmp,
    2289          52 :                                 DAG.getBasicBlock(B.Default));
    2290             : 
    2291             :   // Avoid emitting unnecessary branches to the next block.
    2292          26 :   if (MBB != NextBlock(SwitchBB))
    2293          12 :     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
    2294          12 :                           DAG.getBasicBlock(MBB));
    2295             : 
    2296          26 :   DAG.setRoot(BrRange);
    2297          26 : }
    2298             : 
    2299             : /// visitBitTestCase - this function produces one "bit test"
    2300          37 : void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
    2301             :                                            MachineBasicBlock* NextMBB,
    2302             :                                            BranchProbability BranchProbToNext,
    2303             :                                            unsigned Reg,
    2304             :                                            BitTestCase &B,
    2305             :                                            MachineBasicBlock *SwitchBB) {
    2306          37 :   SDLoc dl = getCurSDLoc();
    2307          37 :   MVT VT = BB.RegVT;
    2308          74 :   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
    2309          37 :   SDValue Cmp;
    2310          37 :   unsigned PopCount = countPopulation(B.Mask);
    2311          37 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2312          37 :   if (PopCount == 1) {
    2313             :     // Testing for a single bit; just compare the shift count with what it
    2314             :     // would need to be to shift a 1 bit in that position.
    2315           3 :     Cmp = DAG.getSetCC(
    2316           6 :         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
    2317             :         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
    2318          12 :         ISD::SETEQ);
    2319          68 :   } else if (PopCount == BB.Range) {
    2320             :     // There is only one zero bit in the range, test for it directly.
    2321           3 :     Cmp = DAG.getSetCC(
    2322           6 :         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
    2323             :         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
    2324          12 :         ISD::SETNE);
    2325             :   } else {
    2326             :     // Make desired shift
    2327             :     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
    2328          62 :                                     DAG.getConstant(1, dl, VT), ShiftOp);
    2329             : 
    2330             :     // Emit bit tests and jumps
    2331          31 :     SDValue AndOp = DAG.getNode(ISD::AND, dl,
    2332          62 :                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
    2333          62 :     Cmp = DAG.getSetCC(
    2334          62 :         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
    2335         124 :         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
    2336             :   }
    2337             : 
    2338             :   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
    2339          37 :   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
    2340             :   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
    2341          37 :   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
    2342             :   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
    2343             :   // one as they are relative probabilities (and thus work more like weights),
    2344             :   // and hence we need to normalize them to let the sum of them become one.
    2345             :   SwitchBB->normalizeSuccProbs();
    2346             : 
    2347          37 :   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
    2348             :                               MVT::Other, getControlRoot(),
    2349          74 :                               Cmp, DAG.getBasicBlock(B.TargetBB));
    2350             : 
    2351             :   // Avoid emitting unnecessary branches to the next block.
    2352          37 :   if (NextMBB != NextBlock(SwitchBB))
    2353          44 :     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
    2354          44 :                         DAG.getBasicBlock(NextMBB));
    2355             : 
    2356          37 :   DAG.setRoot(BrAnd);
    2357          37 : }
    2358             : 
    2359       41155 : void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
    2360       41155 :   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
    2361             : 
    2362             :   // Retrieve successors. Look through artificial IR level blocks like
    2363             :   // catchswitch for successors.
    2364       82310 :   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
    2365             :   const BasicBlock *EHPadBB = I.getSuccessor(1);
    2366             : 
    2367             :   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
    2368             :   // have to do anything here to lower funclet bundles.
    2369             :   assert(!I.hasOperandBundlesOtherThan(
    2370             :              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
    2371             :          "Cannot lower invokes with arbitrary operand bundles yet!");
    2372             : 
    2373             :   const Value *Callee(I.getCalledValue());
    2374             :   const Function *Fn = dyn_cast<Function>(Callee);
    2375       41155 :   if (isa<InlineAsm>(Callee))
    2376           1 :     visitInlineAsm(&I);
    2377       81977 :   else if (Fn && Fn->isIntrinsic()) {
    2378          10 :     switch (Fn->getIntrinsicID()) {
    2379           0 :     default:
    2380           0 :       llvm_unreachable("Cannot invoke this intrinsic");
    2381             :     case Intrinsic::donothing:
    2382             :       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
    2383             :       break;
    2384             :     case Intrinsic::experimental_patchpoint_void:
    2385             :     case Intrinsic::experimental_patchpoint_i64:
    2386           1 :       visitPatchpoint(&I, EHPadBB);
    2387           1 :       break;
    2388           8 :     case Intrinsic::experimental_gc_statepoint:
    2389          16 :       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
    2390           8 :       break;
    2391             :     }
    2392       41144 :   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
    2393             :     // Currently we do not lower any intrinsic calls with deopt operand bundles.
    2394             :     // Eventually we will support lowering the @llvm.experimental.deoptimize
    2395             :     // intrinsic, and right now there are no plans to support other intrinsics
    2396             :     // with deopt state.
    2397           0 :     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
    2398             :   } else {
    2399       82288 :     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
    2400             :   }
    2401             : 
    2402             :   // If the value of the invoke is used outside of its defining block, make it
    2403             :   // available as a virtual register.
    2404             :   // We already took care of the exported value for the statepoint instruction
    2405             :   // during call to the LowerStatepoint.
    2406       41155 :   if (!isStatepoint(I)) {
    2407       41147 :     CopyToExportRegsIfNeeded(&I);
    2408             :   }
    2409             : 
    2410             :   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
    2411       41155 :   BranchProbabilityInfo *BPI = FuncInfo.BPI;
    2412             :   BranchProbability EHPadBBProb =
    2413       27114 :       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
    2414       68269 :           : BranchProbability::getZero();
    2415       41155 :   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
    2416             : 
    2417             :   // Update successor info.
    2418       41155 :   addSuccessorWithProb(InvokeMBB, Return);
    2419      123541 :   for (auto &UnwindDest : UnwindDests) {
    2420       41193 :     UnwindDest.first->setIsEHPad();
    2421       41193 :     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
    2422             :   }
    2423             :   InvokeMBB->normalizeSuccProbs();
    2424             : 
    2425             :   // Drop into normal successor.
    2426      164620 :   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
    2427             :                           MVT::Other, getControlRoot(),
    2428      123465 :                           DAG.getBasicBlock(Return)));
    2429       41155 : }
    2430             : 
    2431           0 : void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
    2432           0 :   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
    2433             : }
    2434             : 
    2435       27067 : void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
    2436             :   assert(FuncInfo.MBB->isEHPad() &&
    2437             :          "Call to landingpad not in landing pad!");
    2438             : 
    2439       27067 :   MachineBasicBlock *MBB = FuncInfo.MBB;
    2440       27067 :   addLandingPadInfo(LP, *MBB);
    2441             : 
    2442             :   // If there aren't registers to copy the values into (e.g., during SjLj
    2443             :   // exceptions), then don't bother to create these DAG nodes.
    2444       27067 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2445       27067 :   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
    2446       27191 :   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
    2447         124 :       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
    2448         132 :     return;
    2449             : 
    2450             :   // If landingpad's return type is token type, we don't create DAG nodes
    2451             :   // for its exception pointer and selector value. The extraction of exception
    2452             :   // pointer or selector value from token type landingpads is not currently
    2453             :   // supported.
    2454       53886 :   if (LP.getType()->isTokenTy())
    2455             :     return;
    2456             : 
    2457             :   SmallVector<EVT, 2> ValueVTs;
    2458       26935 :   SDLoc dl = getCurSDLoc();
    2459       53870 :   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
    2460             :   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
    2461             : 
    2462             :   // Get the two live-in registers as SDValues. The physregs have already been
    2463             :   // copied into virtual registers.
    2464       26935 :   SDValue Ops[2];
    2465       26935 :   if (FuncInfo.ExceptionPointerVirtReg) {
    2466       53870 :     Ops[0] = DAG.getZExtOrTrunc(
    2467       26935 :         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
    2468       26935 :                            FuncInfo.ExceptionPointerVirtReg,
    2469             :                            TLI.getPointerTy(DAG.getDataLayout())),
    2470      107740 :         dl, ValueVTs[0]);
    2471             :   } else {
    2472           0 :     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
    2473             :   }
    2474       53870 :   Ops[1] = DAG.getZExtOrTrunc(
    2475       26935 :       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
    2476       26935 :                          FuncInfo.ExceptionSelectorVirtReg,
    2477             :                          TLI.getPointerTy(DAG.getDataLayout())),
    2478      107740 :       dl, ValueVTs[1]);
    2479             : 
    2480             :   // Merge into one.
    2481       26935 :   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
    2482       26935 :                             DAG.getVTList(ValueVTs), Ops);
    2483       26935 :   setValue(&LP, Res);
    2484             : }
    2485             : 
    2486        1081 : void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
    2487             : #ifndef NDEBUG
    2488             :   for (const CaseCluster &CC : Clusters)
    2489             :     assert(CC.Low == CC.High && "Input clusters must be single-case");
    2490             : #endif
    2491             : 
    2492             :   std::sort(Clusters.begin(), Clusters.end(),
    2493             :             [](const CaseCluster &a, const CaseCluster &b) {
    2494             :     return a.Low->getValue().slt(b.Low->getValue());
    2495             :   });
    2496             : 
    2497             :   // Merge adjacent clusters with the same destination.
    2498        2162 :   const unsigned N = Clusters.size();
    2499             :   unsigned DstIndex = 0;
    2500       10285 :   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
    2501        4602 :     CaseCluster &CC = Clusters[SrcIndex];
    2502        4602 :     const ConstantInt *CaseVal = CC.Low;
    2503        4602 :     MachineBasicBlock *Succ = CC.MBB;
    2504             : 
    2505       13789 :     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
    2506       15926 :         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
    2507             :       // If this case has the same successor and is a neighbour, merge it into
    2508             :       // the previous cluster.
    2509        1806 :       Clusters[DstIndex - 1].High = CaseVal;
    2510             :       Clusters[DstIndex - 1].Prob += CC.Prob;
    2511             :     } else {
    2512       11097 :       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
    2513             :                    sizeof(Clusters[SrcIndex]));
    2514             :     }
    2515             :   }
    2516        1081 :   Clusters.resize(DstIndex);
    2517        1081 : }
    2518             : 
    2519           0 : void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
    2520             :                                            MachineBasicBlock *Last) {
    2521             :   // Update JTCases.
    2522           0 :   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
    2523           0 :     if (JTCases[i].first.HeaderBB == First)
    2524           0 :       JTCases[i].first.HeaderBB = Last;
    2525             : 
    2526             :   // Update BitTestCases.
    2527           0 :   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
    2528           0 :     if (BitTestCases[i].Parent == First)
    2529           0 :       BitTestCases[i].Parent = Last;
    2530           0 : }
    2531             : 
    2532          80 : void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
    2533          80 :   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
    2534             : 
    2535             :   // Update machine-CFG edges with unique successors.
    2536             :   SmallSet<BasicBlock*, 32> Done;
    2537         292 :   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
    2538             :     BasicBlock *BB = I.getSuccessor(i);
    2539         212 :     bool Inserted = Done.insert(BB).second;
    2540         212 :     if (!Inserted)
    2541           6 :         continue;
    2542             : 
    2543         412 :     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
    2544         206 :     addSuccessorWithProb(IndirectBrMBB, Succ);
    2545             :   }
    2546             :   IndirectBrMBB->normalizeSuccProbs();
    2547             : 
    2548         320 :   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
    2549             :                           MVT::Other, getControlRoot(),
    2550         240 :                           getValue(I.getAddress())));
    2551          80 : }
    2552             : 
    2553       12685 : void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
    2554       12685 :   if (DAG.getTarget().Options.TrapUnreachable)
    2555          72 :     DAG.setRoot(
    2556         216 :         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
    2557       12685 : }
    2558             : 
    2559        5389 : void SelectionDAGBuilder::visitFSub(const User &I) {
    2560             :   // -0.0 - X --> fneg
    2561        5389 :   Type *Ty = I.getType();
    2562        7862 :   if (isa<Constant>(I.getOperand(0)) &&
    2563        2473 :       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
    2564        2018 :     SDValue Op2 = getValue(I.getOperand(1));
    2565       10090 :     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
    2566             :                              Op2.getValueType(), Op2));
    2567             :     return;
    2568             :   }
    2569             : 
    2570        3371 :   visitBinary(I, ISD::FSUB);
    2571             : }
    2572             : 
    2573             : /// Checks if the given instruction performs a vector reduction, in which case
    2574             : /// we have the freedom to alter the elements in the result as long as the
    2575             : /// reduction of them stays unchanged.
    2576      276013 : static bool isVectorReductionOp(const User *I) {
    2577             :   const Instruction *Inst = dyn_cast<Instruction>(I);
    2578      551812 :   if (!Inst || !Inst->getType()->isVectorTy())
    2579             :     return false;
    2580             : 
    2581             :   auto OpCode = Inst->getOpcode();
    2582             :   switch (OpCode) {
    2583             :   case Instruction::Add:
    2584             :   case Instruction::Mul:
    2585             :   case Instruction::And:
    2586             :   case Instruction::Or:
    2587             :   case Instruction::Xor:
    2588             :     break;
    2589             :   case Instruction::FAdd:
    2590             :   case Instruction::FMul:
    2591             :     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
    2592        7036 :       if (FPOp->getFastMathFlags().isFast())
    2593             :         break;
    2594             :     LLVM_FALLTHROUGH;
    2595             :   default:
    2596             :     return false;
    2597             :   }
    2598             : 
    2599             :   unsigned ElemNum = Inst->getType()->getVectorNumElements();
    2600             :   unsigned ElemNumToReduce = ElemNum;
    2601             : 
    2602             :   // Do DFS search on the def-use chain from the given instruction. We only
    2603             :   // allow four kinds of operations during the search until we reach the
    2604             :   // instruction that extracts the first element from the vector:
    2605             :   //
    2606             :   //   1. The reduction operation of the same opcode as the given instruction.
    2607             :   //
    2608             :   //   2. PHI node.
    2609             :   //
    2610             :   //   3. ShuffleVector instruction together with a reduction operation that
    2611             :   //      does a partial reduction.
    2612             :   //
    2613             :   //   4. ExtractElement that extracts the first element from the vector, and we
    2614             :   //      stop searching the def-use chain here.
    2615             :   //
    2616             :   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
    2617             :   // from 1-3 to the stack to continue the DFS. The given instruction is not
    2618             :   // a reduction operation if we meet any other instructions other than those
    2619             :   // listed above.
    2620             : 
    2621      170632 :   SmallVector<const User *, 16> UsersToVisit{Inst};
    2622             :   SmallPtrSet<const User *, 16> Visited;
    2623             :   bool ReduxExtracted = false;
    2624             : 
    2625       87440 :   while (!UsersToVisit.empty()) {
    2626       87286 :     auto User = UsersToVisit.back();
    2627             :     UsersToVisit.pop_back();
    2628       87286 :     if (!Visited.insert(User).second)
    2629         248 :       continue;
    2630             : 
    2631      177270 :     for (const auto &U : User->users()) {
    2632             :       auto Inst = dyn_cast<Instruction>(U);
    2633             :       if (!Inst)
    2634             :         return false;
    2635             : 
    2636       87697 :       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
    2637             :         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
    2638           7 :           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
    2639             :             return false;
    2640        2303 :         UsersToVisit.push_back(U);
    2641             :       } else if (const ShuffleVectorInst *ShufInst =
    2642             :                      dyn_cast<ShuffleVectorInst>(U)) {
    2643             :         // Detect the following pattern: A ShuffleVector instruction together
    2644             :         // with a reduction that do partial reduction on the first and second
    2645             :         // ElemNumToReduce / 2 elements, and store the result in
    2646             :         // ElemNumToReduce / 2 elements in another vector.
    2647             : 
    2648             :         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
    2649        1629 :         if (ResultElements < ElemNum)
    2650             :           return false;
    2651             : 
    2652        1551 :         if (ElemNumToReduce == 1)
    2653             :           return false;
    2654        1551 :         if (!isa<UndefValue>(U->getOperand(1)))
    2655             :           return false;
    2656        2508 :         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
    2657        1405 :           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
    2658             :             return false;
    2659        7405 :         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
    2660        3611 :           if (ShufInst->getMaskValue(i) != -1)
    2661             :             return false;
    2662             : 
    2663             :         // There is only one user of this ShuffleVector instruction, which
    2664             :         // must be a reduction operation.
    2665         366 :         if (!U->hasOneUse())
    2666             :           return false;
    2667             : 
    2668             :         auto U2 = dyn_cast<Instruction>(*U->user_begin());
    2669         183 :         if (!U2 || U2->getOpcode() != OpCode)
    2670             :           return false;
    2671             : 
    2672             :         // Check operands of the reduction operation.
    2673         543 :         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
    2674           0 :             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
    2675         181 :           UsersToVisit.push_back(U2);
    2676             :           ElemNumToReduce /= 2;
    2677             :         } else
    2678             :           return false;
    2679             :       } else if (isa<ExtractElementInst>(U)) {
    2680             :         // At this moment we should have reduced all elements in the vector.
    2681         596 :         if (ElemNumToReduce != 1)
    2682             :           return false;
    2683             : 
    2684             :         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
    2685          51 :         if (!Val || Val->getZExtValue() != 0)
    2686             :           return false;
    2687             : 
    2688             :         ReduxExtracted = true;
    2689             :       } else
    2690             :         return false;
    2691             :     }
    2692             :   }
    2693             :   return ReduxExtracted;
    2694             : }
    2695             : 
    2696      276013 : void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
    2697      276013 :   SDValue Op1 = getValue(I.getOperand(0));
    2698      276013 :   SDValue Op2 = getValue(I.getOperand(1));
    2699             : 
    2700             :   bool nuw = false;
    2701             :   bool nsw = false;
    2702             :   bool exact = false;
    2703             :   bool vec_redux = false;
    2704             :   FastMathFlags FMF;
    2705             : 
    2706             :   if (const OverflowingBinaryOperator *OFBinOp =
    2707             :           dyn_cast<const OverflowingBinaryOperator>(&I)) {
    2708             :     nuw = OFBinOp->hasNoUnsignedWrap();
    2709             :     nsw = OFBinOp->hasNoSignedWrap();
    2710             :   }
    2711             :   if (const PossiblyExactOperator *ExactOp =
    2712             :           dyn_cast<const PossiblyExactOperator>(&I))
    2713             :     exact = ExactOp->isExact();
    2714             :   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
    2715             :     FMF = FPOp->getFastMathFlags();
    2716             : 
    2717      276013 :   if (isVectorReductionOp(&I)) {
    2718             :     vec_redux = true;
    2719             :     DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
    2720             :   }
    2721             : 
    2722             :   SDNodeFlags Flags;
    2723             :   Flags.setExact(exact);
    2724             :   Flags.setNoSignedWrap(nsw);
    2725             :   Flags.setNoUnsignedWrap(nuw);
    2726             :   Flags.setVectorReduction(vec_redux);
    2727             :   Flags.setAllowReciprocal(FMF.allowReciprocal());
    2728             :   Flags.setAllowContract(FMF.allowContract());
    2729             :   Flags.setNoInfs(FMF.noInfs());
    2730             :   Flags.setNoNaNs(FMF.noNaNs());
    2731             :   Flags.setNoSignedZeros(FMF.noSignedZeros());
    2732             :   Flags.setUnsafeAlgebra(FMF.isFast());
    2733             : 
    2734      828039 :   SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
    2735      552026 :                                      Op1, Op2, Flags);
    2736             :   setValue(&I, BinNodeValue);
    2737      276013 : }
    2738             : 
    2739       16958 : void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
    2740       16958 :   SDValue Op1 = getValue(I.getOperand(0));
    2741       16958 :   SDValue Op2 = getValue(I.getOperand(1));
    2742             : 
    2743       16958 :   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
    2744       50874 :       Op2.getValueType(), DAG.getDataLayout());
    2745             : 
    2746             :   // Coerce the shift amount to the right type if we can.
    2747       45972 :   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
    2748        8552 :     unsigned ShiftSize = ShiftTy.getSizeInBits();
    2749        8552 :     unsigned Op2Size = Op2.getValueSizeInBits();
    2750        8552 :     SDLoc DL = getCurSDLoc();
    2751             : 
    2752             :     // If the operand is smaller than the shift count type, promote it.
    2753        8552 :     if (ShiftSize > Op2Size)
    2754        1146 :       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
    2755             : 
    2756             :     // If the operand is larger than the shift count type but the shift
    2757             :     // count type has enough bits to represent any shift value, truncate
    2758             :     // it now. This is a common case and it exposes the truncate to
    2759             :     // optimization early.
    2760       15958 :     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
    2761       15940 :       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
    2762             :     // Otherwise we'll need to temporarily settle for some other convenient
    2763             :     // type.  Type legalization will make adjustments once the shiftee is split.
    2764             :     else
    2765          18 :       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
    2766             :   }
    2767             : 
    2768             :   bool nuw = false;
    2769             :   bool nsw = false;
    2770             :   bool exact = false;
    2771             : 
    2772       16958 :   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
    2773             : 
    2774             :     if (const OverflowingBinaryOperator *OFBinOp =
    2775             :             dyn_cast<const OverflowingBinaryOperator>(&I)) {
    2776             :       nuw = OFBinOp->hasNoUnsignedWrap();
    2777             :       nsw = OFBinOp->hasNoSignedWrap();
    2778             :     }
    2779             :     if (const PossiblyExactOperator *ExactOp =
    2780             :             dyn_cast<const PossiblyExactOperator>(&I))
    2781             :       exact = ExactOp->isExact();
    2782             :   }
    2783             :   SDNodeFlags Flags;
    2784             :   Flags.setExact(exact);
    2785             :   Flags.setNoSignedWrap(nsw);
    2786             :   Flags.setNoUnsignedWrap(nuw);
    2787       50874 :   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
    2788       33916 :                             Flags);
    2789       16958 :   setValue(&I, Res);
    2790       16958 : }
    2791             : 
    2792        1451 : void SelectionDAGBuilder::visitSDiv(const User &I) {
    2793        1451 :   SDValue Op1 = getValue(I.getOperand(0));
    2794        1451 :   SDValue Op2 = getValue(I.getOperand(1));
    2795             : 
    2796             :   SDNodeFlags Flags;
    2797        2902 :   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
    2798             :                  cast<PossiblyExactOperator>(&I)->isExact());
    2799        5804 :   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
    2800             :                            Op2, Flags));
    2801        1451 : }
    2802             : 
    2803       57950 : void SelectionDAGBuilder::visitICmp(const User &I) {
    2804             :   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
    2805             :   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
    2806             :     predicate = IC->getPredicate();
    2807             :   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
    2808         123 :     predicate = ICmpInst::Predicate(IC->getPredicate());
    2809       57950 :   SDValue Op1 = getValue(I.getOperand(0));
    2810       57950 :   SDValue Op2 = getValue(I.getOperand(1));
    2811       57950 :   ISD::CondCode Opcode = getICmpCondCode(predicate);
    2812             : 
    2813       57950 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    2814      115900 :                                                         I.getType());
    2815      173850 :   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
    2816       57950 : }
    2817             : 
    2818        6718 : void SelectionDAGBuilder::visitFCmp(const User &I) {
    2819             :   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
    2820             :   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
    2821             :     predicate = FC->getPredicate();
    2822             :   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
    2823           5 :     predicate = FCmpInst::Predicate(FC->getPredicate());
    2824        6718 :   SDValue Op1 = getValue(I.getOperand(0));
    2825        6718 :   SDValue Op2 = getValue(I.getOperand(1));
    2826        6718 :   ISD::CondCode Condition = getFCmpCondCode(predicate);
    2827             : 
    2828             :   // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
    2829             :   // FIXME: We should propagate the fast-math-flags to the DAG node itself for
    2830             :   // further optimization, but currently FMF is only applicable to binary nodes.
    2831        6718 :   if (TM.Options.NoNaNsFPMath)
    2832         283 :     Condition = getFCmpCodeWithoutNaN(Condition);
    2833        6718 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    2834       13436 :                                                         I.getType());
    2835       20154 :   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
    2836        6718 : }
    2837             : 
    2838             : // Check if the condition of the select has one use or two users that are both
    2839             : // selects with the same condition.
    2840             : static bool hasOnlySelectUsers(const Value *Cond) {
    2841             :   return llvm::all_of(Cond->users(), [](const Value *V) {
    2842             :     return isa<SelectInst>(V);
    2843             :   });
    2844             : }
    2845             : 
    2846       45983 : void SelectionDAGBuilder::visitSelect(const User &I) {
    2847             :   SmallVector<EVT, 4> ValueVTs;
    2848       91966 :   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
    2849             :                   ValueVTs);
    2850       45983 :   unsigned NumValues = ValueVTs.size();
    2851       45983 :   if (NumValues == 0) return;
    2852             : 
    2853       91952 :   SmallVector<SDValue, 4> Values(NumValues);
    2854       45976 :   SDValue Cond     = getValue(I.getOperand(0));
    2855       45976 :   SDValue LHSVal   = getValue(I.getOperand(1));
    2856       45976 :   SDValue RHSVal   = getValue(I.getOperand(2));
    2857       45976 :   auto BaseOps = {Cond};
    2858      137928 :   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
    2859             :     ISD::VSELECT : ISD::SELECT;
    2860             : 
    2861             :   // Min/max matching is only viable if all output VTs are the same.
    2862             :   if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
    2863       45976 :     EVT VT = ValueVTs[0];
    2864       45976 :     LLVMContext &Ctx = *DAG.getContext();
    2865       45976 :     auto &TLI = DAG.getTargetLoweringInfo();
    2866             : 
    2867             :     // We care about the legality of the operation after it has been type
    2868             :     // legalized.
    2869      104999 :     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
    2870        4353 :            VT != TLI.getTypeToTransformTo(Ctx, VT))
    2871        4342 :       VT = TLI.getTypeToTransformTo(Ctx, VT);
    2872             : 
    2873             :     // If the vselect is legal, assume we want to leave this as a vector setcc +
    2874             :     // vselect. Otherwise, if this is going to be scalarized, we want to see if
    2875             :     // min/max is legal on the scalar type.
    2876       45976 :     bool UseScalarMinMax = VT.isVector() &&
    2877             :       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
    2878             : 
    2879             :     Value *LHS, *RHS;
    2880       45976 :     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
    2881             :     ISD::NodeType Opc = ISD::DELETED_NODE;
    2882       45976 :     switch (SPR.Flavor) {
    2883             :     case SPF_UMAX:    Opc = ISD::UMAX; break;
    2884             :     case SPF_UMIN:    Opc = ISD::UMIN; break;
    2885             :     case SPF_SMAX:    Opc = ISD::SMAX; break;
    2886             :     case SPF_SMIN:    Opc = ISD::SMIN; break;
    2887         134 :     case SPF_FMINNUM:
    2888         134 :       switch (SPR.NaNBehavior) {
    2889           0 :       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
    2890             :       case SPNB_RETURNS_NAN:   Opc = ISD::FMINNAN; break;
    2891             :       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
    2892          37 :       case SPNB_RETURNS_ANY: {
    2893          37 :         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
    2894             :           Opc = ISD::FMINNUM;
    2895             :         else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
    2896             :           Opc = ISD::FMINNAN;
    2897           7 :         else if (UseScalarMinMax)
    2898           0 :           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
    2899             :             ISD::FMINNUM : ISD::FMINNAN;
    2900             :         break;
    2901             :       }
    2902             :       }
    2903             :       break;
    2904         153 :     case SPF_FMAXNUM:
    2905         153 :       switch (SPR.NaNBehavior) {
    2906           0 :       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
    2907             :       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXNAN; break;
    2908             :       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
    2909          41 :       case SPNB_RETURNS_ANY:
    2910             : 
    2911          41 :         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
    2912             :           Opc = ISD::FMAXNUM;
    2913             :         else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
    2914             :           Opc = ISD::FMAXNAN;
    2915           6 :         else if (UseScalarMinMax)
    2916           0 :           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
    2917             :             ISD::FMAXNUM : ISD::FMAXNAN;
    2918             :         break;
    2919             :       }
    2920             :       break;
    2921             :     default: break;
    2922             :     }
    2923             : 
    2924        7710 :     if (Opc != ISD::DELETED_NODE &&
    2925        8582 :         (TLI.isOperationLegalOrCustom(Opc, VT) ||
    2926          80 :          (UseScalarMinMax &&
    2927        6995 :           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
    2928             :         // If the underlying comparison instruction is used by any other
    2929             :         // instruction, the consumed instructions won't be destroyed, so it is
    2930             :         // not profitable to convert to a min/max.
    2931             :         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
    2932             :       OpCode = Opc;
    2933        6892 :       LHSVal = getValue(LHS);
    2934        6892 :       RHSVal = getValue(RHS);
    2935             :       BaseOps = {};
    2936             :     }
    2937             :   }
    2938             : 
    2939      137936 :   for (unsigned i = 0; i != NumValues; ++i) {
    2940             :     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
    2941       91960 :     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
    2942       91960 :     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
    2943      229900 :     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
    2944             :                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
    2945       91960 :                             Ops);
    2946             :   }
    2947             : 
    2948      183904 :   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
    2949             :                            DAG.getVTList(ValueVTs), Values));
    2950             : }
    2951             : 
    2952        9081 : void SelectionDAGBuilder::visitTrunc(const User &I) {
    2953             :   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
    2954        9081 :   SDValue N = getValue(I.getOperand(0));
    2955        9081 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    2956       18162 :                                                         I.getType());
    2957       36324 :   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
    2958        9081 : }
    2959             : 
    2960       16030 : void SelectionDAGBuilder::visitZExt(const User &I) {
    2961             :   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
    2962             :   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
    2963       16030 :   SDValue N = getValue(I.getOperand(0));
    2964       16030 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    2965       32060 :                                                         I.getType());
    2966       64120 :   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
    2967       16030 : }
    2968             : 
    2969       14302 : void SelectionDAGBuilder::visitSExt(const User &I) {
    2970             :   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
    2971             :   // SExt also can't be a cast to bool for same reason. So, nothing much to do
    2972       14302 :   SDValue N = getValue(I.getOperand(0));
    2973       14302 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    2974       28604 :                                                         I.getType());
    2975       57208 :   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
    2976       14302 : }
    2977             : 
    2978         795 : void SelectionDAGBuilder::visitFPTrunc(const User &I) {
    2979             :   // FPTrunc is never a no-op cast, no need to check
    2980         795 :   SDValue N = getValue(I.getOperand(0));
    2981         795 :   SDLoc dl = getCurSDLoc();
    2982         795 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    2983        1590 :   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    2984        3180 :   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
    2985             :                            DAG.getTargetConstant(
    2986             :                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
    2987         795 : }
    2988             : 
    2989        1905 : void SelectionDAGBuilder::visitFPExt(const User &I) {
    2990             :   // FPExt is never a no-op cast, no need to check
    2991        1905 :   SDValue N = getValue(I.getOperand(0));
    2992        1905 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    2993        3810 :                                                         I.getType());
    2994        7620 :   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
    2995        1905 : }
    2996             : 
    2997        1240 : void SelectionDAGBuilder::visitFPToUI(const User &I) {
    2998             :   // FPToUI is never a no-op cast, no need to check
    2999        1240 :   SDValue N = getValue(I.getOperand(0));
    3000        1240 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3001        2480 :                                                         I.getType());
    3002        4960 :   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
    3003        1240 : }
    3004             : 
    3005        1581 : void SelectionDAGBuilder::visitFPToSI(const User &I) {
    3006             :   // FPToSI is never a no-op cast, no need to check
    3007        1581 :   SDValue N = getValue(I.getOperand(0));
    3008        1581 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3009        3162 :                                                         I.getType());
    3010        6324 :   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
    3011        1581 : }
    3012             : 
    3013        1630 : void SelectionDAGBuilder::visitUIToFP(const User &I) {
    3014             :   // UIToFP is never a no-op cast, no need to check
    3015        1630 :   SDValue N = getValue(I.getOperand(0));
    3016        1630 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3017        3260 :                                                         I.getType());
    3018        6520 :   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
    3019        1630 : }
    3020             : 
    3021        2162 : void SelectionDAGBuilder::visitSIToFP(const User &I) {
    3022             :   // SIToFP is never a no-op cast, no need to check
    3023        2162 :   SDValue N = getValue(I.getOperand(0));
    3024        2162 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3025        4324 :                                                         I.getType());
    3026        8648 :   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
    3027        2162 : }
    3028             : 
    3029        2868 : void SelectionDAGBuilder::visitPtrToInt(const User &I) {
    3030             :   // What to do depends on the size of the integer and the size of the pointer.
    3031             :   // We can either truncate, zero extend, or no-op, accordingly.
    3032        2868 :   SDValue N = getValue(I.getOperand(0));
    3033        2868 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3034        5736 :                                                         I.getType());
    3035        8604 :   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
    3036        2868 : }
    3037             : 
    3038        3438 : void SelectionDAGBuilder::visitIntToPtr(const User &I) {
    3039             :   // What to do depends on the size of the integer and the size of the pointer.
    3040             :   // We can either truncate, zero extend, or no-op, accordingly.
    3041        3438 :   SDValue N = getValue(I.getOperand(0));
    3042        3438 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3043        6876 :                                                         I.getType());
    3044       10314 :   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
    3045        3438 : }
    3046             : 
    3047      240806 : void SelectionDAGBuilder::visitBitCast(const User &I) {
    3048      240806 :   SDValue N = getValue(I.getOperand(0));
    3049      240806 :   SDLoc dl = getCurSDLoc();
    3050      240806 :   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    3051      481612 :                                                         I.getType());
    3052             : 
    3053             :   // BitCast assures us that source and destination are the same size so this is
    3054             :   // either a BITCAST or a no-op.
    3055      481736 :   if (DestVT != N.getValueType())
    3056       73224 :     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
    3057             :                              DestVT, N)); // convert types.
    3058             :   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
    3059             :   // might fold any kind of constant expression to an integer constant and that
    3060             :   // is not what we are looking for. Only recognize a bitcast of a genuine
    3061             :   // constant integer as an opaque constant.
    3062             :   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
    3063         856 :     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
    3064             :                                  /*isOpaque*/true));
    3065             :   else
    3066      215970 :     setValue(&I, N);            // noop cast.
    3067      240806 : }
    3068             : 
    3069         292 : void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
    3070         292 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3071             :   const Value *SV = I.getOperand(0);
    3072         292 :   SDValue N = getValue(SV);
    3073         584 :   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    3074             : 
    3075         292 :   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
    3076         292 :   unsigned DestAS = I.getType()->getPointerAddressSpace();
    3077             : 
    3078         292 :   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
    3079         603 :     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
    3080             : 
    3081         292 :   setValue(&I, N);
    3082         292 : }
    3083             : 
    3084       23959 : void SelectionDAGBuilder::visitInsertElement(const User &I) {
    3085       23959 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3086       23959 :   SDValue InVec = getValue(I.getOperand(0));
    3087       23959 :   SDValue InVal = getValue(I.getOperand(1));
    3088       71877 :   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
    3089       95836 :                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
    3090       95836 :   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
    3091             :                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
    3092             :                            InVec, InVal, InIdx));
    3093       23959 : }
    3094             : 
    3095       18114 : void SelectionDAGBuilder::visitExtractElement(const User &I) {
    3096       18114 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3097       18114 :   SDValue InVec = getValue(I.getOperand(0));
    3098       54342 :   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
    3099       72456 :                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
    3100       90570 :   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
    3101             :                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
    3102             :                            InVec, InIdx));
    3103       18114 : }
    3104             : 
    3105       34496 : void SelectionDAGBuilder::visitShuffleVector(const User &I) {
    3106       34496 :   SDValue Src1 = getValue(I.getOperand(0));
    3107       34496 :   SDValue Src2 = getValue(I.getOperand(1));
    3108       34496 :   SDLoc DL = getCurSDLoc();
    3109             : 
    3110             :   SmallVector<int, 8> Mask;
    3111       34496 :   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
    3112       34496 :   unsigned MaskNumElts = Mask.size();
    3113             : 
    3114       34496 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3115       68992 :   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    3116       68992 :   EVT SrcVT = Src1.getValueType();
    3117       34496 :   unsigned SrcNumElts = SrcVT.getVectorNumElements();
    3118             : 
    3119       34496 :   if (SrcNumElts == MaskNumElts) {
    3120       72156 :     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
    3121       24052 :     return;
    3122             :   }
    3123             : 
    3124             :   // Normalize the shuffle vector since mask and vector length don't match.
    3125       10444 :   if (SrcNumElts < MaskNumElts) {
    3126             :     // Mask is longer than the source vectors. We can use concatenate vector to
    3127             :     // make the mask and vectors lengths match.
    3128             : 
    3129        5346 :     if (MaskNumElts % SrcNumElts == 0) {
    3130             :       // Mask length is a multiple of the source vector length.
    3131             :       // Check if the shuffle is some kind of concatenation of the input
    3132             :       // vectors.
    3133        5218 :       unsigned NumConcat = MaskNumElts / SrcNumElts;
    3134             :       bool IsConcat = true;
    3135       10436 :       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
    3136      187480 :       for (unsigned i = 0; i != MaskNumElts; ++i) {
    3137      184642 :         int Idx = Mask[i];
    3138       92321 :         if (Idx < 0)
    3139        2193 :           continue;
    3140             :         // Ensure the indices in each SrcVT sized piece are sequential and that
    3141             :         // the same source is used for the whole piece.
    3142      179070 :         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
    3143      250049 :             (ConcatSrcs[i / SrcNumElts] >= 0 &&
    3144       72165 :              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
    3145             :           IsConcat = false;
    3146             :           break;
    3147             :         }
    3148             :         // Remember which source this index came from.
    3149       88938 :         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
    3150             :       }
    3151             : 
    3152             :       // The shuffle is concatenating multiple vectors together. Just emit
    3153             :       // a CONCAT_VECTORS operation.
    3154        5218 :       if (IsConcat) {
    3155             :         SmallVector<SDValue, 8> ConcatOps;
    3156       36512 :         for (auto Src : ConcatSrcs) {
    3157       16242 :           if (Src < 0)
    3158         503 :             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
    3159       15739 :           else if (Src == 0)
    3160        5657 :             ConcatOps.push_back(Src1);
    3161             :           else
    3162       10082 :             ConcatOps.push_back(Src2);
    3163             :         }
    3164       12084 :         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
    3165             :         return;
    3166             :       }
    3167             :     }
    3168             : 
    3169        2636 :     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
    3170        1318 :     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
    3171        1318 :     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
    3172        2636 :                                     PaddedMaskNumElts);
    3173             : 
    3174             :     // Pad both vectors with undefs to make them the same length as the mask.
    3175        1318 :     SDValue UndefVal = DAG.getUNDEF(SrcVT);
    3176             : 
    3177        1318 :     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
    3178             :     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
    3179        1318 :     MOps1[0] = Src1;
    3180        1318 :     MOps2[0] = Src2;
    3181             : 
    3182        2636 :     Src1 = Src1.isUndef()
    3183        3948 :                ? DAG.getUNDEF(PaddedVT)
    3184        2630 :                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
    3185        2636 :     Src2 = Src2.isUndef()
    3186        3018 :                ? DAG.getUNDEF(PaddedVT)
    3187        1700 :                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
    3188             : 
    3189             :     // Readjust mask for new input vector length.
    3190        2636 :     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
    3191       45116 :     for (unsigned i = 0; i != MaskNumElts; ++i) {
    3192       43798 :       int Idx = Mask[i];
    3193       21899 :       if (Idx >= (int)SrcNumElts)
    3194        4331 :         Idx -= SrcNumElts - PaddedMaskNumElts;
    3195       21899 :       MappedOps[i] = Idx;
    3196             :     }
    3197             : 
    3198        2636 :     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
    3199             : 
    3200             :     // If the concatenated vector was padded, extract a subvector with the
    3201             :     // correct number of elements.
    3202        1318 :     if (MaskNumElts != PaddedMaskNumElts)
    3203         256 :       Result = DAG.getNode(
    3204             :           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
    3205         512 :           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
    3206             : 
    3207        1318 :     setValue(&I, Result);
    3208             :     return;
    3209             :   }
    3210             : 
    3211        5098 :   if (SrcNumElts > MaskNumElts) {
    3212             :     // Analyze the access pattern of the vector to see if we can extract
    3213             :     // two subvectors and do the shuffle.
    3214        5098 :     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
    3215             :     bool CanExtract = true;
    3216       57904 :     for (int Idx : Mask) {
    3217             :       unsigned Input = 0;
    3218       26403 :       if (Idx < 0)
    3219          17 :         continue;
    3220             : 
    3221       26386 :       if (Idx >= (int)SrcNumElts) {
    3222             :         Input = 1;
    3223        1882 :         Idx -= SrcNumElts;
    3224             :       }
    3225             : 
    3226             :       // If all the indices come from the same MaskNumElts sized portion of
    3227             :       // the sources we can use extract. Also make sure the extract wouldn't
    3228             :       // extract past the end of the source.
    3229       52772 :       int NewStartIdx = alignDown(Idx, MaskNumElts);
    3230       52761 :       if (NewStartIdx + MaskNumElts > SrcNumElts ||
    3231       47576 :           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
    3232             :         CanExtract = false;
    3233             :       // Make sure we always update StartIdx as we use it to track if all
    3234             :       // elements are undef.
    3235       26386 :       StartIdx[Input] = NewStartIdx;
    3236             :     }
    3237             : 
    3238        5098 :     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
    3239           0 :       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
    3240        3932 :       return;
    3241             :     }
    3242        5098 :     if (CanExtract) {
    3243             :       // Extract appropriate subvector and generate a vector shuffle
    3244       19660 :       for (unsigned Input = 0; Input < 2; ++Input) {
    3245        7864 :         SDValue &Src = Input == 0 ? Src1 : Src2;
    3246        7864 :         if (StartIdx[Input] < 0)
    3247        3880 :           Src = DAG.getUNDEF(VT);
    3248             :         else {
    3249        7968 :           Src = DAG.getNode(
    3250             :               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
    3251             :               DAG.getConstant(StartIdx[Input], DL,
    3252       15936 :                               TLI.getVectorIdxTy(DAG.getDataLayout())));
    3253             :         }
    3254             :       }
    3255             : 
    3256             :       // Calculate new mask.
    3257             :       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
    3258       41154 :       for (int &Idx : MappedOps) {
    3259       18611 :         if (Idx >= (int)SrcNumElts)
    3260        1831 :           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
    3261       16780 :         else if (Idx >= 0)
    3262       16769 :           Idx -= StartIdx[0];
    3263             :       }
    3264             : 
    3265       11796 :       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
    3266             :       return;
    3267             :     }
    3268             :   }
    3269             : 
    3270             :   // We can't use either concat vectors or extract subvectors so fall back to
    3271             :   // replacing the shuffle with extract and build vector.
    3272             :   // to insert and build vector.
    3273        1166 :   EVT EltVT = VT.getVectorElementType();
    3274        2332 :   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
    3275             :   SmallVector<SDValue,8> Ops;
    3276       16750 :   for (int Idx : Mask) {
    3277        7792 :     SDValue Res;
    3278             : 
    3279        7792 :     if (Idx < 0) {
    3280           6 :       Res = DAG.getUNDEF(EltVT);
    3281             :     } else {
    3282        7786 :       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
    3283        7786 :       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
    3284             : 
    3285       15572 :       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
    3286       15572 :                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
    3287             :     }
    3288             : 
    3289        7792 :     Ops.push_back(Res);
    3290             :   }
    3291             : 
    3292        3498 :   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
    3293             : }
    3294             : 
    3295        1006 : void SelectionDAGBuilder::visitInsertValue(const User &I) {
    3296             :   ArrayRef<unsigned> Indices;
    3297             :   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
    3298             :     Indices = IV->getIndices();
    3299             :   else
    3300           0 :     Indices = cast<ConstantExpr>(&I)->getIndices();
    3301             : 
    3302             :   const Value *Op0 = I.getOperand(0);
    3303             :   const Value *Op1 = I.getOperand(1);
    3304        1006 :   Type *AggTy = I.getType();
    3305        1006 :   Type *ValTy = Op1->getType();
    3306             :   bool IntoUndef = isa<UndefValue>(Op0);
    3307             :   bool FromUndef = isa<UndefValue>(Op1);
    3308             : 
    3309             :   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
    3310             : 
    3311        1006 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3312             :   SmallVector<EVT, 4> AggValueVTs;
    3313        2012 :   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
    3314             :   SmallVector<EVT, 4> ValValueVTs;
    3315        2012 :   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
    3316             : 
    3317        1006 :   unsigned NumAggValues = AggValueVTs.size();
    3318        1006 :   unsigned NumValValues = ValValueVTs.size();
    3319        2012 :   SmallVector<SDValue, 4> Values(NumAggValues);
    3320             : 
    3321             :   // Ignore an insertvalue that produces an empty object
    3322        1006 :   if (!NumAggValues) {
    3323           3 :     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
    3324             :     return;
    3325             :   }
    3326             : 
    3327        1005 :   SDValue Agg = getValue(Op0);
    3328             :   unsigned i = 0;
    3329             :   // Copy the beginning value(s) from the original aggregate.
    3330        4137 :   for (; i != LinearIndex; ++i)
    3331        3226 :     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
    3332             :                 SDValue(Agg.getNode(), Agg.getResNo() + i);
    3333             :   // Copy values from the inserted value(s).
    3334        1005 :   if (NumValValues) {
    3335        1003 :     SDValue Val = getValue(Op1);
    3336        3061 :     for (; i != LinearIndex + NumValValues; ++i)
    3337        3087 :       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
    3338        1012 :                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
    3339             :   }
    3340             :   // Copy remaining value(s) from the original aggregate.
    3341        4189 :   for (; i != NumAggValues; ++i)
    3342        3803 :     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
    3343             :                 SDValue(Agg.getNode(), Agg.getResNo() + i);
    3344             : 
    3345        4020 :   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
    3346             :                            DAG.getVTList(AggValueVTs), Values));
    3347             : }
    3348             : 
    3349       42128 : void SelectionDAGBuilder::visitExtractValue(const User &I) {
    3350             :   ArrayRef<unsigned> Indices;
    3351             :   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
    3352             :     Indices = EV->getIndices();
    3353             :   else
    3354           1 :     Indices = cast<ConstantExpr>(&I)->getIndices();
    3355             : 
    3356             :   const Value *Op0 = I.getOperand(0);
    3357       42128 :   Type *AggTy = Op0->getType();
    3358       42128 :   Type *ValTy = I.getType();
    3359             :   bool OutOfUndef = isa<UndefValue>(Op0);
    3360             : 
    3361             :   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
    3362             : 
    3363       42128 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3364             :   SmallVector<EVT, 4> ValValueVTs;
    3365       84256 :   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
    3366             : 
    3367       42128 :   unsigned NumValValues = ValValueVTs.size();
    3368             : 
    3369             :   // Ignore a extractvalue that produces an empty object
    3370       42128 :   if (!NumValValues) {
    3371          12 :     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
    3372             :     return;
    3373             :   }
    3374             : 
    3375       84248 :   SmallVector<SDValue, 4> Values(NumValValues);
    3376             : 
    3377       42124 :   SDValue Agg = getValue(Op0);
    3378             :   // Copy out the selected value(s).
    3379      126402 :   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
    3380       84278 :     Values[i - LinearIndex] =
    3381       84293 :       OutOfUndef ?
    3382          15 :         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
    3383             :         SDValue(Agg.getNode(), Agg.getResNo() + i);
    3384             : 
    3385      168496 :   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
    3386             :                            DAG.getVTList(ValValueVTs), Values));
    3387             : }
    3388             : 
    3389      358559 : void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
    3390             :   Value *Op0 = I.getOperand(0);
    3391             :   // Note that the pointer operand may be a vector of pointers. Take the scalar
    3392             :   // element which holds a pointer.
    3393      358559 :   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
    3394      358559 :   SDValue N = getValue(Op0);
    3395      358559 :   SDLoc dl = getCurSDLoc();
    3396             : 
    3397             :   // Normalize Vector GEP - all scalar operands should be converted to the
    3398             :   // splat vector.
    3399      717118 :   unsigned VectorWidth = I.getType()->isVectorTy() ?
    3400             :     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
    3401             : 
    3402         693 :   if (VectorWidth && !N.getValueType().isVector()) {
    3403         132 :     LLVMContext &Context = *DAG.getContext();
    3404         132 :     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
    3405         132 :     N = DAG.getSplatBuildVector(VT, dl, N);
    3406             :   }
    3407             : 
    3408     1013082 :   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
    3409     1013082 :        GTI != E; ++GTI) {
    3410             :     const Value *Idx = GTI.getOperand();
    3411       41063 :     if (StructType *StTy = GTI.getStructTypeOrNull()) {
    3412       82126 :       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
    3413       41063 :       if (Field) {
    3414             :         // N = N + Offset
    3415       23089 :         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
    3416             : 
    3417             :         // In an inbounds GEP with an offset that is nonnegative even when
    3418             :         // interpreted as signed, assume there is no unsigned overflow.
    3419             :         SDNodeFlags Flags;
    3420       46178 :         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
    3421             :           Flags.setNoUnsignedWrap(true);
    3422             : 
    3423       46178 :         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
    3424       23089 :                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
    3425             :       }
    3426             :     } else {
    3427      613460 :       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
    3428      613460 :       MVT IdxTy = MVT::getIntegerVT(IdxSize);
    3429      613460 :       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
    3430             : 
    3431             :       // If this is a scalar constant or a splat vector of constants,
    3432             :       // handle it quickly.
    3433             :       const auto *CI = dyn_cast<ConstantInt>(Idx);
    3434       46817 :       if (!CI && isa<ConstantDataVector>(Idx) &&
    3435          20 :           cast<ConstantDataVector>(Idx)->getSplatValue())
    3436          14 :         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
    3437             : 
    3438      613460 :       if (CI) {
    3439      566677 :         if (CI->isZero())
    3440      385151 :           continue;
    3441      363052 :         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
    3442      181526 :         LLVMContext &Context = *DAG.getContext();
    3443             :         SDValue OffsVal = VectorWidth ?
    3444      181547 :           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
    3445      363052 :           DAG.getConstant(Offs, dl, IdxTy);
    3446             : 
    3447             :         // In an inbouds GEP with an offset that is nonnegative even when
    3448             :         // interpreted as signed, assume there is no unsigned overflow.
    3449             :         SDNodeFlags Flags;
    3450      360404 :         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
    3451             :           Flags.setNoUnsignedWrap(true);
    3452             : 
    3453      363052 :         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
    3454             :         continue;
    3455             :       }
    3456             : 
    3457             :       // N = N + Idx * ElementSize;
    3458       46783 :       SDValue IdxN = getValue(Idx);
    3459             : 
    3460       93566 :       if (!IdxN.getValueType().isVector() && VectorWidth) {
    3461          12 :         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
    3462          12 :         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
    3463             :       }
    3464             : 
    3465             :       // If the index is smaller or larger than intptr_t, truncate or extend
    3466             :       // it.
    3467       93566 :       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
    3468             : 
    3469             :       // If this is a multiply by a power of two, turn it into a shl
    3470             :       // immediately.  This is a very common case.
    3471       46783 :       if (ElementSize != 1) {
    3472       41283 :         if (ElementSize.isPowerOf2()) {
    3473             :           unsigned Amt = ElementSize.logBase2();
    3474       79154 :           IdxN = DAG.getNode(ISD::SHL, dl,
    3475             :                              N.getValueType(), IdxN,
    3476       79154 :                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
    3477             :         } else {
    3478        3412 :           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
    3479        3412 :           IdxN = DAG.getNode(ISD::MUL, dl,
    3480        1706 :                              N.getValueType(), IdxN, Scale);
    3481             :         }
    3482             :       }
    3483             : 
    3484       93566 :       N = DAG.getNode(ISD::ADD, dl,
    3485       46783 :                       N.getValueType(), N, IdxN);
    3486             :     }
    3487             :   }
    3488             : 
    3489      358559 :   setValue(&I, N);
    3490      358559 : }
    3491             : 
    3492       40470 : void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
    3493             :   // If this is a fixed sized alloca in the entry block of the function,
    3494             :   // allocate it statically on the stack.
    3495       40470 :   if (FuncInfo.StaticAllocaMap.count(&I))
    3496       40034 :     return;   // getValue will auto-populate this.
    3497             : 
    3498         436 :   SDLoc dl = getCurSDLoc();
    3499         436 :   Type *Ty = I.getAllocatedType();
    3500         436 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3501         436 :   auto &DL = DAG.getDataLayout();
    3502         436 :   uint64_t TySize = DL.getTypeAllocSize(Ty);
    3503             :   unsigned Align =
    3504         872 :       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
    3505             : 
    3506         436 :   SDValue AllocSize = getValue(I.getArraySize());
    3507             : 
    3508         436 :   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
    3509           0 :   if (AllocSize.getValueType() != IntPtr)
    3510         107 :     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
    3511             : 
    3512         872 :   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
    3513             :                           AllocSize,
    3514         872 :                           DAG.getConstant(TySize, dl, IntPtr));
    3515             : 
    3516             :   // Handle alignment.  If the requested alignment is less than or equal to
    3517             :   // the stack alignment, ignore it.  If the size is greater than or equal to
    3518             :   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
    3519             :   unsigned StackAlign =
    3520         872 :       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
    3521         436 :   if (Align <= StackAlign)
    3522             :     Align = 0;
    3523             : 
    3524             :   // Round the size of the allocation up to the stack alignment size
    3525             :   // by add SA-1 to the size. This doesn't overflow because we're computing
    3526             :   // an address inside an alloca.
    3527             :   SDNodeFlags Flags;
    3528             :   Flags.setNoUnsignedWrap(true);
    3529         872 :   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
    3530         436 :                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
    3531             : 
    3532             :   // Mask out the low bits for alignment purposes.
    3533         436 :   AllocSize =
    3534        1308 :       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
    3535         872 :                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
    3536             : 
    3537         436 :   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
    3538         872 :   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
    3539         872 :   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
    3540         436 :   setValue(&I, DSA);
    3541         436 :   DAG.setRoot(DSA.getValue(1));
    3542             : 
    3543             :   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
    3544             : }
    3545             : 
    3546      318099 : void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
    3547      318099 :   if (I.isAtomic())
    3548        2574 :     return visitAtomicLoad(I);
    3549             : 
    3550      316840 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3551             :   const Value *SV = I.getOperand(0);
    3552      316840 :   if (TLI.supportSwiftError()) {
    3553             :     // Swifterror values can come from either a function parameter with
    3554             :     // swifterror attribute or an alloca with swifterror attribute.
    3555             :     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
    3556       23224 :       if (Arg->hasSwiftErrorAttr())
    3557           6 :         return visitLoadFromSwiftError(I);
    3558             :     }
    3559             : 
    3560             :     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
    3561       20846 :       if (Alloca->isSwiftError())
    3562          47 :         return visitLoadFromSwiftError(I);
    3563             :     }
    3564             :   }
    3565             : 
    3566      316787 :   SDValue Ptr = getValue(SV);
    3567             : 
    3568      316787 :   Type *Ty = I.getType();
    3569             : 
    3570             :   bool isVolatile = I.isVolatile();
    3571             :   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
    3572             :   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
    3573      633574 :   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
    3574             :   unsigned Alignment = I.getAlignment();
    3575             : 
    3576             :   AAMDNodes AAInfo;
    3577      316787 :   I.getAAMetadata(AAInfo);
    3578             :   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
    3579             : 
    3580             :   SmallVector<EVT, 4> ValueVTs;
    3581             :   SmallVector<uint64_t, 4> Offsets;
    3582      633574 :   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
    3583      316787 :   unsigned NumValues = ValueVTs.size();
    3584      316787 :   if (NumValues == 0)
    3585             :     return;
    3586             : 
    3587      316784 :   SDValue Root;
    3588             :   bool ConstantMemory = false;
    3589      316784 :   if (isVolatile || NumValues > MaxParallelChains)
    3590             :     // Serialize volatile loads with other side effects.
    3591        9204 :     Root = getRoot();
    3592      588286 :   else if (AA && AA->pointsToConstantMemory(MemoryLocation(
    3593      279125 :                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
    3594             :     // Do not serialize (non-volatile) loads of constant memory with anything.
    3595        3162 :     Root = DAG.getEntryNode();
    3596             :     ConstantMemory = true;
    3597             :   } else {
    3598             :     // Do not serialize non-volatile loads against each other.
    3599      305999 :     Root = DAG.getRoot();
    3600             :   }
    3601             : 
    3602      316784 :   SDLoc dl = getCurSDLoc();
    3603             : 
    3604      316784 :   if (isVolatile)
    3605        9204 :     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
    3606             : 
    3607             :   // An aggregate load cannot wrap around the address space, so offsets to its
    3608             :   // parts don't wrap either.
    3609             :   SDNodeFlags Flags;
    3610             :   Flags.setNoUnsignedWrap(true);
    3611             : 
    3612      633568 :   SmallVector<SDValue, 4> Values(NumValues);
    3613      950352 :   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
    3614      633568 :   EVT PtrVT = Ptr.getValueType();
    3615             :   unsigned ChainI = 0;
    3616      952010 :   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
    3617             :     // Serializing loads here may result in excessive register pressure, and
    3618             :     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
    3619             :     // could recover a bit by hoisting nodes upward in the chain by recognizing
    3620             :     // they are side-effect free or do not alias. The optimizer should really
    3621             :     // avoid this case by converting large object/array copies to llvm.memcpy
    3622             :     // (MaxParallelChains should always remain as failsafe).
    3623      317613 :     if (ChainI == MaxParallelChains) {
    3624             :       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
    3625           0 :       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
    3626           0 :                                   makeArrayRef(Chains.data(), ChainI));
    3627           0 :       Root = Chain;
    3628             :       ChainI = 0;
    3629             :     }
    3630      317613 :     SDValue A = DAG.getNode(ISD::ADD, dl,
    3631             :                             PtrVT, Ptr,
    3632      317613 :                             DAG.getConstant(Offsets[i], dl, PtrVT),
    3633      317613 :                             Flags);
    3634             :     auto MMOFlags = MachineMemOperand::MONone;
    3635      317613 :     if (isVolatile)
    3636             :       MMOFlags |= MachineMemOperand::MOVolatile;
    3637      317613 :     if (isNonTemporal)
    3638             :       MMOFlags |= MachineMemOperand::MONonTemporal;
    3639      317613 :     if (isInvariant)
    3640             :       MMOFlags |= MachineMemOperand::MOInvariant;
    3641      317613 :     if (isDereferenceable)
    3642             :       MMOFlags |= MachineMemOperand::MODereferenceable;
    3643      317613 :     MMOFlags |= TLI.getMMOFlags(I);
    3644             : 
    3645      317613 :     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
    3646             :                             MachinePointerInfo(SV, Offsets[i]), Alignment,
    3647      952839 :                             MMOFlags, AAInfo, Ranges);
    3648             : 
    3649      317613 :     Values[i] = L;
    3650      635226 :     Chains[ChainI] = L.getValue(1);
    3651             :   }
    3652             : 
    3653      316784 :   if (!ConstantMemory) {
    3654      315203 :     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
    3655      630406 :                                 makeArrayRef(Chains.data(), ChainI));
    3656      315203 :     if (isVolatile)
    3657        9204 :       DAG.setRoot(Chain);
    3658             :     else
    3659      305999 :       PendingLoads.push_back(Chain);
    3660             :   }
    3661             : 
    3662      950352 :   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
    3663             :                            DAG.getVTList(ValueVTs), Values));
    3664             : }
    3665             : 
    3666         108 : void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
    3667             :   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
    3668             :          "call visitStoreToSwiftError when backend supports swifterror");
    3669             : 
    3670             :   SmallVector<EVT, 4> ValueVTs;
    3671             :   SmallVector<uint64_t, 4> Offsets;
    3672             :   const Value *SrcV = I.getOperand(0);
    3673         216 :   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
    3674             :                   SrcV->getType(), ValueVTs, &Offsets);
    3675             :   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
    3676             :          "expect a single EVT for swifterror");
    3677             : 
    3678         108 :   SDValue Src = getValue(SrcV);
    3679             :   // Create a virtual register, then update the virtual register.
    3680             :   unsigned VReg; bool CreatedVReg;
    3681         216 :   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
    3682             :   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
    3683             :   // Chain can be getRoot or getControlRoot.
    3684         324 :   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
    3685         324 :                                       SDValue(Src.getNode(), Src.getResNo()));
    3686         108 :   DAG.setRoot(CopyNode);
    3687         108 :   if (CreatedVReg)
    3688         138 :     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
    3689         108 : }
    3690             : 
    3691          53 : void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
    3692             :   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
    3693             :          "call visitLoadFromSwiftError when backend supports swifterror");
    3694             : 
    3695             :   assert(!I.isVolatile() &&
    3696             :          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
    3697             :          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
    3698             :          "Support volatile, non temporal, invariant for load_from_swift_error");
    3699             : 
    3700             :   const Value *SV = I.getOperand(0);
    3701          53 :   Type *Ty = I.getType();
    3702             :   AAMDNodes AAInfo;
    3703          53 :   I.getAAMetadata(AAInfo);
    3704             :   assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
    3705             :              SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
    3706             :          "load_from_swift_error should not be constant memory");
    3707             : 
    3708             :   SmallVector<EVT, 4> ValueVTs;
    3709             :   SmallVector<uint64_t, 4> Offsets;
    3710         106 :   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
    3711             :                   ValueVTs, &Offsets);
    3712             :   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
    3713             :          "expect a single EVT for swifterror");
    3714             : 
    3715             :   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
    3716          53 :   SDValue L = DAG.getCopyFromReg(
    3717         106 :       getRoot(), getCurSDLoc(),
    3718          53 :       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
    3719         106 :       ValueVTs[0]);
    3720             : 
    3721          53 :   setValue(&I, L);
    3722          53 : }
    3723             : 
    3724      304395 : void SelectionDAGBuilder::visitStore(const StoreInst &I) {
    3725      304395 :   if (I.isAtomic())
    3726        1763 :     return visitAtomicStore(I);
    3727             : 
    3728             :   const Value *SrcV = I.getOperand(0);
    3729             :   const Value *PtrV = I.getOperand(1);
    3730             : 
    3731      303578 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3732      303578 :   if (TLI.supportSwiftError()) {
    3733             :     // Swifterror values can come from either a function parameter with
    3734             :     // swifterror attribute or an alloca with swifterror attribute.
    3735             :     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
    3736        7706 :       if (Arg->hasSwiftErrorAttr())
    3737          45 :         return visitStoreToSwiftError(I);
    3738             :     }
    3739             : 
    3740             :     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
    3741       14733 :       if (Alloca->isSwiftError())
    3742          63 :         return visitStoreToSwiftError(I);
    3743             :     }
    3744             :   }
    3745             : 
    3746             :   SmallVector<EVT, 4> ValueVTs;
    3747             :   SmallVector<uint64_t, 4> Offsets;
    3748      606940 :   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
    3749             :                   SrcV->getType(), ValueVTs, &Offsets);
    3750      303470 :   unsigned NumValues = ValueVTs.size();
    3751      303470 :   if (NumValues == 0)
    3752             :     return;
    3753             : 
    3754             :   // Get the lowered operands. Note that we do this after
    3755             :   // checking if NumResults is zero, because with zero results
    3756             :   // the operands won't have values in the map.
    3757      303449 :   SDValue Src = getValue(SrcV);
    3758      303449 :   SDValue Ptr = getValue(PtrV);
    3759             : 
    3760      303449 :   SDValue Root = getRoot();
    3761      910347 :   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
    3762      303449 :   SDLoc dl = getCurSDLoc();
    3763      606898 :   EVT PtrVT = Ptr.getValueType();
    3764             :   unsigned Alignment = I.getAlignment();
    3765             :   AAMDNodes AAInfo;
    3766      303449 :   I.getAAMetadata(AAInfo);
    3767             : 
    3768             :   auto MMOFlags = MachineMemOperand::MONone;
    3769      303449 :   if (I.isVolatile())
    3770             :     MMOFlags |= MachineMemOperand::MOVolatile;
    3771      238749 :   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
    3772             :     MMOFlags |= MachineMemOperand::MONonTemporal;
    3773      303449 :   MMOFlags |= TLI.getMMOFlags(I);
    3774             : 
    3775             :   // An aggregate load cannot wrap around the address space, so offsets to its
    3776             :   // parts don't wrap either.
    3777             :   SDNodeFlags Flags;
    3778             :   Flags.setNoUnsignedWrap(true);
    3779             : 
    3780             :   unsigned ChainI = 0;
    3781      911201 :   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
    3782             :     // See visitLoad comments.
    3783      303876 :     if (ChainI == MaxParallelChains) {
    3784           0 :       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
    3785           0 :                                   makeArrayRef(Chains.data(), ChainI));
    3786           0 :       Root = Chain;
    3787             :       ChainI = 0;
    3788             :     }
    3789      303876 :     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
    3790      607752 :                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
    3791      303876 :     SDValue St = DAG.getStore(
    3792      303876 :         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
    3793     1215504 :         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
    3794      607752 :     Chains[ChainI] = St;
    3795             :   }
    3796             : 
    3797      303449 :   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
    3798      606898 :                                   makeArrayRef(Chains.data(), ChainI));
    3799      303449 :   DAG.setRoot(StoreNode);
    3800             : }
    3801             : 
    3802         122 : void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
    3803             :                                            bool IsCompressing) {
    3804         122 :   SDLoc sdl = getCurSDLoc();
    3805             : 
    3806             :   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
    3807         102 :                            unsigned& Alignment) {
    3808             :     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
    3809         204 :     Src0 = I.getArgOperand(0);
    3810         102 :     Ptr = I.getArgOperand(1);
    3811         102 :     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
    3812         102 :     Mask = I.getArgOperand(3);
    3813         224 :   };
    3814             :   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
    3815             :                            unsigned& Alignment) {
    3816             :     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
    3817          20 :     Src0 = I.getArgOperand(0);
    3818          20 :     Ptr = I.getArgOperand(1);
    3819          20 :     Mask = I.getArgOperand(2);
    3820          20 :     Alignment = 0;
    3821             :   };
    3822             : 
    3823             :   Value  *PtrOperand, *MaskOperand, *Src0Operand;
    3824             :   unsigned Alignment;
    3825         122 :   if (IsCompressing)
    3826             :     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
    3827             :   else
    3828         102 :     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
    3829             : 
    3830         122 :   SDValue Ptr = getValue(PtrOperand);
    3831         122 :   SDValue Src0 = getValue(Src0Operand);
    3832         122 :   SDValue Mask = getValue(MaskOperand);
    3833             : 
    3834         244 :   EVT VT = Src0.getValueType();
    3835         122 :   if (!Alignment)
    3836          20 :     Alignment = DAG.getEVTAlignment(VT);
    3837             : 
    3838             :   AAMDNodes AAInfo;
    3839         122 :   I.getAAMetadata(AAInfo);
    3840             : 
    3841             :   MachineMemOperand *MMO =
    3842         122 :     DAG.getMachineFunction().
    3843         366 :     getMachineMemOperand(MachinePointerInfo(PtrOperand),
    3844             :                           MachineMemOperand::MOStore,  VT.getStoreSize(),
    3845         122 :                           Alignment, AAInfo);
    3846         122 :   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
    3847             :                                          MMO, false /* Truncating */,
    3848         122 :                                          IsCompressing);
    3849         122 :   DAG.setRoot(StoreNode);
    3850         122 :   setValue(&I, StoreNode);
    3851         122 : }
    3852             : 
    3853             : // Get a uniform base for the Gather/Scatter intrinsic.
    3854             : // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
    3855             : // We try to represent it as a base pointer + vector of indices.
    3856             : // Usually, the vector of pointers comes from a 'getelementptr' instruction.
    3857             : // The first operand of the GEP may be a single pointer or a vector of pointers
    3858             : // Example:
    3859             : //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
    3860             : //  or
    3861             : //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
    3862             : // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
    3863             : //
    3864             : // When the first GEP operand is a single pointer - it is the uniform base we
    3865             : // are looking for. If first operand of the GEP is a splat vector - we
    3866             : // extract the splat value and use it as a uniform base.
    3867             : // In all other cases the function returns 'false'.
    3868         373 : static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
    3869             :                            SDValue &Scale, SelectionDAGBuilder* SDB) {
    3870         373 :   SelectionDAG& DAG = SDB->DAG;
    3871         373 :   LLVMContext &Context = *DAG.getContext();
    3872             : 
    3873             :   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
    3874         373 :   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
    3875             :   if (!GEP)
    3876             :     return false;
    3877             : 
    3878             :   const Value *GEPPtr = GEP->getPointerOperand();
    3879         432 :   if (!GEPPtr->getType()->isVectorTy())
    3880         132 :     Ptr = GEPPtr;
    3881          84 :   else if (!(Ptr = getSplatValue(GEPPtr)))
    3882             :     return false;
    3883             : 
    3884         210 :   unsigned FinalIndex = GEP->getNumOperands() - 1;
    3885             :   Value *IndexVal = GEP->getOperand(FinalIndex);
    3886             : 
    3887             :   // Ensure all the other indices are 0.
    3888         222 :   for (unsigned i = 1; i < FinalIndex; ++i) {
    3889             :     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
    3890           6 :     if (!C || !C->isZero())
    3891             :       return false;
    3892             :   }
    3893             : 
    3894             :   // The operands of the GEP may be defined in another basic block.
    3895             :   // In this case we'll not find nodes for the operands.
    3896         198 :   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
    3897             :     return false;
    3898             : 
    3899             :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3900         182 :   const DataLayout &DL = DAG.getDataLayout();
    3901         182 :   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
    3902         546 :                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
    3903         182 :   Base = SDB->getValue(Ptr);
    3904         182 :   Index = SDB->getValue(IndexVal);
    3905             : 
    3906         546 :   if (!Index.getValueType().isVector()) {
    3907           6 :     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
    3908           6 :     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
    3909          12 :     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
    3910             :   }
    3911             :   return true;
    3912             : }
    3913             : 
    3914          85 : void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
    3915          85 :   SDLoc sdl = getCurSDLoc();
    3916             : 
    3917             :   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
    3918             :   const Value *Ptr = I.getArgOperand(1);
    3919          85 :   SDValue Src0 = getValue(I.getArgOperand(0));
    3920          85 :   SDValue Mask = getValue(I.getArgOperand(3));
    3921         170 :   EVT VT = Src0.getValueType();
    3922          85 :   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
    3923          85 :   if (!Alignment)
    3924           0 :     Alignment = DAG.getEVTAlignment(VT);
    3925             :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    3926             : 
    3927             :   AAMDNodes AAInfo;
    3928          85 :   I.getAAMetadata(AAInfo);
    3929             : 
    3930          85 :   SDValue Base;
    3931          85 :   SDValue Index;
    3932          85 :   SDValue Scale;
    3933          85 :   const Value *BasePtr = Ptr;
    3934          85 :   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
    3935             : 
    3936          85 :   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
    3937          85 :   MachineMemOperand *MMO = DAG.getMachineFunction().
    3938         170 :     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
    3939             :                          MachineMemOperand::MOStore,  VT.getStoreSize(),
    3940          85 :                          Alignment, AAInfo);
    3941          85 :   if (!UniformBase) {
    3942         112 :     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
    3943          56 :     Index = getValue(Ptr);
    3944         112 :     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
    3945             :   }
    3946          85 :   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
    3947          85 :   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
    3948          85 :                                          Ops, MMO);
    3949          85 :   DAG.setRoot(Scatter);
    3950          85 :   setValue(&I, Scatter);
    3951          85 : }
    3952             : 
    3953         238 : void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
    3954         238 :   SDLoc sdl = getCurSDLoc();
    3955             : 
    3956             :   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
    3957         222 :                            unsigned& Alignment) {
    3958             :     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
    3959         444 :     Ptr = I.getArgOperand(0);
    3960         222 :     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
    3961         222 :     Mask = I.getArgOperand(2);
    3962         222 :     Src0 = I.getArgOperand(3);
    3963         460 :   };
    3964             :   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
    3965             :                            unsigned& Alignment) {
    3966             :     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
    3967          16 :     Ptr = I.getArgOperand(0);
    3968          16 :     Alignment = 0;
    3969          16 :     Mask = I.getArgOperand(1);
    3970          16 :     Src0 = I.getArgOperand(2);
    3971             :   };
    3972             : 
    3973             :   Value  *PtrOperand, *MaskOperand, *Src0Operand;
    3974             :   unsigned Alignment;
    3975         238 :   if (IsExpanding)
    3976             :     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
    3977             :   else
    3978         222 :     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
    3979             : 
    3980         238 :   SDValue Ptr = getValue(PtrOperand);
    3981         238 :   SDValue Src0 = getValue(Src0Operand);
    3982         238 :   SDValue Mask = getValue(MaskOperand);
    3983             : 
    3984         476 :   EVT VT = Src0.getValueType();
    3985         238 :   if (!Alignment)
    3986          16 :     Alignment = DAG.getEVTAlignment(VT);
    3987             : 
    3988             :   AAMDNodes AAInfo;
    3989         238 :   I.getAAMetadata(AAInfo);
    3990             :   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
    3991             : 
    3992             :   // Do not serialize masked loads of constant memory with anything.
    3993         953 :   bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
    3994         238 :       PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
    3995         239 :   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
    3996             : 
    3997             :   MachineMemOperand *MMO =
    3998         238 :     DAG.getMachineFunction().
    3999         714 :     getMachineMemOperand(MachinePointerInfo(PtrOperand),
    4000             :                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
    4001         238 :                           Alignment, AAInfo, Ranges);
    4002             : 
    4003         238 :   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
    4004         238 :                                    ISD::NON_EXTLOAD, IsExpanding);
    4005         238 :   if (AddToChain) {
    4006         237 :     SDValue OutChain = Load.getValue(1);
    4007         237 :     DAG.setRoot(OutChain);
    4008             :   }
    4009         238 :   setValue(&I, Load);
    4010         238 : }
    4011             : 
    4012         288 : void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
    4013         288 :   SDLoc sdl = getCurSDLoc();
    4014             : 
    4015             :   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
    4016             :   const Value *Ptr = I.getArgOperand(0);
    4017         288 :   SDValue Src0 = getValue(I.getArgOperand(3));
    4018         288 :   SDValue Mask = getValue(I.getArgOperand(2));
    4019             : 
    4020         288 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    4021         576 :   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    4022         288 :   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
    4023         288 :   if (!Alignment)
    4024          36 :     Alignment = DAG.getEVTAlignment(VT);
    4025             : 
    4026             :   AAMDNodes AAInfo;
    4027         288 :   I.getAAMetadata(AAInfo);
    4028             :   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
    4029             : 
    4030         288 :   SDValue Root = DAG.getRoot();
    4031         288 :   SDValue Base;
    4032         288 :   SDValue Index;
    4033         288 :   SDValue Scale;
    4034         288 :   const Value *BasePtr = Ptr;
    4035         288 :   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
    4036             :   bool ConstantMemory = false;
    4037         153 :   if (UniformBase &&
    4038         991 :       AA && AA->pointsToConstantMemory(MemoryLocation(
    4039         140 :           BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
    4040             :           AAInfo))) {
    4041             :     // Do not serialize (non-volatile) loads of constant memory with anything.
    4042           5 :     Root = DAG.getEntryNode();
    4043             :     ConstantMemory = true;
    4044             :   }
    4045             : 
    4046             :   MachineMemOperand *MMO =
    4047         288 :     DAG.getMachineFunction().
    4048         576 :     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
    4049             :                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
    4050         288 :                          Alignment, AAInfo, Ranges);
    4051             : 
    4052         288 :   if (!UniformBase) {
    4053         270 :     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
    4054         135 :     Index = getValue(Ptr);
    4055         270 :     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
    4056             :   }
    4057         288 :   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
    4058         288 :   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
    4059         288 :                                        Ops, MMO);
    4060             : 
    4061         288 :   SDValue OutChain = Gather.getValue(1);
    4062         288 :   if (!ConstantMemory)
    4063         283 :     PendingLoads.push_back(OutChain);
    4064         288 :   setValue(&I, Gather);
    4065         288 : }
    4066             : 
    4067        1162 : void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
    4068        1162 :   SDLoc dl = getCurSDLoc();
    4069             :   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
    4070             :   AtomicOrdering FailureOrder = I.getFailureOrdering();
    4071        1162 :   SyncScope::ID SSID = I.getSyncScopeID();
    4072             : 
    4073        1162 :   SDValue InChain = getRoot();
    4074             : 
    4075        2324 :   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
    4076        2324 :   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
    4077        1162 :   SDValue L = DAG.getAtomicCmpSwap(
    4078             :       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
    4079             :       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
    4080             :       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
    4081        5810 :       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
    4082             : 
    4083        1162 :   SDValue OutChain = L.getValue(2);
    4084             : 
    4085        1162 :   setValue(&I, L);
    4086        1162 :   DAG.setRoot(OutChain);
    4087        1162 : }
    4088             : 
    4089        4707 : void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
    4090        4707 :   SDLoc dl = getCurSDLoc();
    4091             :   ISD::NodeType NT;
    4092        4707 :   switch (I.getOperation()) {
    4093           0 :   default: llvm_unreachable("Unknown atomicrmw operation");
    4094             :   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
    4095         714 :   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
    4096         677 :   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
    4097         458 :   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
    4098         122 :   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
    4099         427 :   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
    4100         412 :   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
    4101         344 :   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
    4102         357 :   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
    4103         348 :   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
    4104         348 :   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
    4105             :   }
    4106             :   AtomicOrdering Order = I.getOrdering();
    4107        4707 :   SyncScope::ID SSID = I.getSyncScopeID();
    4108             : 
    4109        4707 :   SDValue InChain = getRoot();
    4110             : 
    4111             :   SDValue L =
    4112        4707 :     DAG.getAtomic(NT, dl,
    4113        9414 :                   getValue(I.getValOperand()).getSimpleValueType(),
    4114             :                   InChain,
    4115             :                   getValue(I.getPointerOperand()),
    4116             :                   getValue(I.getValOperand()),
    4117             :                   I.getPointerOperand(),
    4118       18828 :                   /* Alignment=*/ 0, Order, SSID);
    4119             : 
    4120        4707 :   SDValue OutChain = L.getValue(1);
    4121             : 
    4122        4707 :   setValue(&I, L);
    4123        4707 :   DAG.setRoot(OutChain);
    4124        4707 : }
    4125             : 
    4126         325 : void SelectionDAGBuilder::visitFence(const FenceInst &I) {
    4127         325 :   SDLoc dl = getCurSDLoc();
    4128         325 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    4129         325 :   SDValue Ops[3];
    4130         325 :   Ops[0] = getRoot();
    4131         650 :   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
    4132        1300 :                            TLI.getFenceOperandTy(DAG.getDataLayout()));
    4133         975 :   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
    4134        1300 :                            TLI.getFenceOperandTy(DAG.getDataLayout()));
    4135         650 :   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
    4136         325 : }
    4137             : 
    4138        1259 : void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
    4139        1259 :   SDLoc dl = getCurSDLoc();
    4140             :   AtomicOrdering Order = I.getOrdering();
    4141        1259 :   SyncScope::ID SSID = I.getSyncScopeID();
    4142             : 
    4143        1259 :   SDValue InChain = getRoot();
    4144             : 
    4145        1259 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    4146        2518 :   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    4147             : 
    4148        2518 :   if (!TLI.supportsUnalignedAtomics() &&
    4149             :       I.getAlignment() < VT.getStoreSize())
    4150           0 :     report_fatal_error("Cannot generate unaligned atomic load");
    4151             : 
    4152             :   MachineMemOperand *MMO =
    4153        1259 :       DAG.getMachineFunction().
    4154        5036 :       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
    4155             :                            MachineMemOperand::MOVolatile |
    4156             :                            MachineMemOperand::MOLoad,
    4157             :                            VT.getStoreSize(),
    4158             :                            I.getAlignment() ? I.getAlignment() :
    4159             :                                               DAG.getEVTAlignment(VT),
    4160        2518 :                            AAMDNodes(), nullptr, SSID, Order);
    4161             : 
    4162        1259 :   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
    4163             :   SDValue L =
    4164        1259 :       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
    4165        1259 :                     getValue(I.getPointerOperand()), MMO);
    4166             : 
    4167        1259 :   SDValue OutChain = L.getValue(1);
    4168             : 
    4169        1259 :   setValue(&I, L);
    4170        1259 :   DAG.setRoot(OutChain);
    4171        1259 : }
    4172             : 
    4173         817 : void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
    4174         817 :   SDLoc dl = getCurSDLoc();
    4175             : 
    4176             :   AtomicOrdering Order = I.getOrdering();
    4177         817 :   SyncScope::ID SSID = I.getSyncScopeID();
    4178             : 
    4179         817 :   SDValue InChain = getRoot();
    4180             : 
    4181         817 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    4182             :   EVT VT =
    4183        2451 :       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
    4184             : 
    4185         817 :   if (I.getAlignment() < VT.getStoreSize())
    4186           0 :     report_fatal_error("Cannot generate unaligned atomic store");
    4187             : 
    4188             :   SDValue OutChain =
    4189         817 :     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
    4190             :                   InChain,
    4191             :                   getValue(I.getPointerOperand()),
    4192             :                   getValue(I.getValueOperand()),
    4193             :                   I.getPointerOperand(), I.getAlignment(),
    4194        2451 :                   Order, SSID);
    4195             : 
    4196         817 :   DAG.setRoot(OutChain);
    4197         817 : }
    4198             : 
    4199             : /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
    4200             : /// node.
    4201       39772 : void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
    4202             :                                                unsigned Intrinsic) {
    4203             :   // Ignore the callsite's attributes. A specific call site may be marked with
    4204             :   // readnone, but the lowering code will expect the chain based on the
    4205             :   // definition.
    4206             :   const Function *F = I.getCalledFunction();
    4207       39772 :   bool HasChain = !F->doesNotAccessMemory();
    4208       39772 :   bool OnlyLoad = HasChain && F->onlyReadsMemory();
    4209             : 
    4210             :   // Build the operand list.
    4211             :   SmallVector<SDValue, 8> Ops;
    4212       39772 :   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
    4213        9079 :     if (OnlyLoad) {
    4214             :       // We don't need to serialize loads against other loads.
    4215        4100 :       Ops.push_back(DAG.getRoot());
    4216             :     } else {
    4217        7029 :       Ops.push_back(getRoot());
    4218             :     }
    4219             :   }
    4220             : 
    4221             :   // Info is set by getTgtMemInstrinsic
    4222       39772 :   TargetLowering::IntrinsicInfo Info;
    4223       39772 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    4224       79544 :   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
    4225             :                                                DAG.getMachineFunction(),
    4226       79544 :                                                Intrinsic);
    4227             : 
    4228             :   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
    4229       39772 :   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
    4230             :       Info.opc == ISD::INTRINSIC_W_CHAIN)
    4231      159048 :     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
    4232       79524 :                                         TLI.getPointerTy(DAG.getDataLayout())));
    4233             : 
    4234             :   // Add all operands of the call to the operand list.
    4235      217078 :   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
    4236       88653 :     SDValue Op = getValue(I.getArgOperand(i));
    4237       88653 :     Ops.push_back(Op);
    4238             :   }
    4239             : 
    4240             :   SmallVector<EVT, 4> ValueVTs;
    4241       79544 :   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
    4242             : 
    4243       39772 :   if (HasChain)
    4244        9079 :     ValueVTs.push_back(MVT::Other);
    4245             : 
    4246       79544 :   SDVTList VTs = DAG.getVTList(ValueVTs);
    4247             : 
    4248             :   // Create the node.
    4249             :   SDValue Result;
    4250       39772 :   if (IsTgtIntrinsic) {
    4251             :     // This is target intrinsic that touches memory
    4252       14832 :     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
    4253             :       Ops, Info.memVT,
    4254        3708 :       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
    4255       14832 :       Info.flags, Info.size);
    4256       36064 :   } else if (!HasChain) {
    4257      122772 :     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
    4258       10742 :   } else if (!I.getType()->isVoidTy()) {
    4259        7296 :     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
    4260             :   } else {
    4261       14188 :     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
    4262             :   }
    4263             : 
    4264       39772 :   if (HasChain) {
    4265       18158 :     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
    4266        9079 :     if (OnlyLoad)
    4267        2050 :       PendingLoads.push_back(Chain);
    4268             :     else
    4269        7029 :       DAG.setRoot(Chain);
    4270             :   }
    4271             : 
    4272       79544 :   if (!I.getType()->isVoidTy()) {
    4273             :     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
    4274       38052 :       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
    4275       76104 :       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
    4276             :     } else
    4277       16277 :       Result = lowerRangeToAssertZExt(DAG, I, Result);
    4278             : 
    4279       35303 :     setValue(&I, Result);
    4280             :   }
    4281       39772 : }
    4282             : 
    4283             : /// GetSignificand - Get the significand and build it into a floating-point
    4284             : /// number with exponent of 1:
    4285             : ///
    4286             : ///   Op = (Op & 0x007fffff) | 0x3f800000;
    4287             : ///
    4288             : /// where Op is the hexadecimal representation of floating point value.
    4289           9 : static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
    4290             :   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
    4291          18 :                            DAG.getConstant(0x007fffff, dl, MVT::i32));
    4292             :   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
    4293          18 :                            DAG.getConstant(0x3f800000, dl, MVT::i32));
    4294           9 :   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
    4295             : }
    4296             : 
    4297             : /// GetExponent - Get the exponent:
    4298             : ///
    4299             : ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
    4300             : ///
    4301             : /// where Op is the hexadecimal representation of floating point value.
    4302           9 : static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
    4303             :                            const TargetLowering &TLI, const SDLoc &dl) {
    4304             :   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
    4305          18 :                            DAG.getConstant(0x7f800000, dl, MVT::i32));
    4306             :   SDValue t1 = DAG.getNode(
    4307             :       ISD::SRL, dl, MVT::i32, t0,
    4308          27 :       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
    4309             :   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
    4310          18 :                            DAG.getConstant(127, dl, MVT::i32));
    4311           9 :   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
    4312             : }
    4313             : 
    4314             : /// getF32Constant - Get 32-bit floating point constant.
    4315          97 : static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
    4316             :                               const SDLoc &dl) {
    4317         388 :   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
    4318         194 :                            MVT::f32);
    4319             : }
    4320             : 
    4321           9 : static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
    4322             :                                        SelectionDAG &DAG) {
    4323             :   // TODO: What fast-math-flags should be set on the floating-point nodes?
    4324             : 
    4325             :   //   IntegerPartOfX = ((int32_t)(t0);
    4326           9 :   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
    4327             : 
    4328             :   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
    4329           9 :   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
    4330           9 :   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
    4331             : 
    4332             :   //   IntegerPartOfX <<= 23;
    4333           9 :   IntegerPartOfX = DAG.getNode(
    4334             :       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
    4335             :       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
    4336          27 :                                   DAG.getDataLayout())));
    4337             : 
    4338           9 :   SDValue TwoToFractionalPartOfX;
    4339           9 :   if (LimitFloatPrecision <= 6) {
    4340             :     // For floating-point precision of 6:
    4341             :     //
    4342             :     //   TwoToFractionalPartOfX =
    4343             :     //     0.997535578f +
    4344             :     //       (0.735607626f + 0.252464424f * x) * x;
    4345             :     //
    4346             :     // error 0.0144103317, which is 6 bits
    4347             :     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4348           6 :                              getF32Constant(DAG, 0x3e814304, dl));
    4349             :     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
    4350           6 :                              getF32Constant(DAG, 0x3f3c50c8, dl));
    4351           3 :     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4352           3 :     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4353           6 :                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
    4354           6 :   } else if (LimitFloatPrecision <= 12) {
    4355             :     // For floating-point precision of 12:
    4356             :     //
    4357             :     //   TwoToFractionalPartOfX =
    4358             :     //     0.999892986f +
    4359             :     //       (0.696457318f +
    4360             :     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
    4361             :     //
    4362             :     // error 0.000107046256, which is 13 to 14 bits
    4363             :     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4364           6 :                              getF32Constant(DAG, 0x3da235e3, dl));
    4365             :     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
    4366           6 :                              getF32Constant(DAG, 0x3e65b8f3, dl));
    4367           3 :     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4368             :     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4369           6 :                              getF32Constant(DAG, 0x3f324b07, dl));
    4370           3 :     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4371           3 :     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
    4372           6 :                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
    4373             :   } else { // LimitFloatPrecision <= 18
    4374             :     // For floating-point precision of 18:
    4375             :     //
    4376             :     //   TwoToFractionalPartOfX =
    4377             :     //     0.999999982f +
    4378             :     //       (0.693148872f +
    4379             :     //         (0.240227044f +
    4380             :     //           (0.554906021e-1f +
    4381             :     //             (0.961591928e-2f +
    4382             :     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
    4383             :     // error 2.47208000*10^(-7), which is better than 18 bits
    4384             :     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4385           6 :                              getF32Constant(DAG, 0x3924b03e, dl));
    4386             :     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
    4387           6 :                              getF32Constant(DAG, 0x3ab24b87, dl));
    4388           3 :     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4389             :     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4390           6 :                              getF32Constant(DAG, 0x3c1d8c17, dl));
    4391           3 :     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4392             :     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
    4393           6 :                              getF32Constant(DAG, 0x3d634a1d, dl));
    4394           3 :     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
    4395             :     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
    4396           6 :                              getF32Constant(DAG, 0x3e75fe14, dl));
    4397           3 :     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
    4398             :     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
    4399           6 :                               getF32Constant(DAG, 0x3f317234, dl));
    4400           3 :     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
    4401           3 :     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
    4402           6 :                                          getF32Constant(DAG, 0x3f800000, dl));
    4403             :   }
    4404             : 
    4405             :   // Add the exponent into the result in integer domain.
    4406           9 :   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
    4407             :   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
    4408          18 :                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
    4409             : }
    4410             : 
    4411             : /// expandExp - Lower an exp intrinsic. Handles the special sequences for
    4412             : /// limited-precision mode.
    4413          71 : static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
    4414             :                          const TargetLowering &TLI) {
    4415          24 :   if (Op.getValueType() == MVT::f32 &&
    4416          27 :       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
    4417             : 
    4418             :     // Put the exponent in the right bit position for later addition to the
    4419             :     // final result:
    4420             :     //
    4421             :     //   #define LOG2OFe 1.4426950f
    4422             :     //   t0 = Op * LOG2OFe
    4423             : 
    4424             :     // TODO: What fast-math-flags should be set here?
    4425             :     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
    4426           6 :                              getF32Constant(DAG, 0x3fb8aa3b, dl));
    4427           3 :     return getLimitedPrecisionExp2(t0, dl, DAG);
    4428             :   }
    4429             : 
    4430             :   // No special expansion.
    4431          68 :   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
    4432             : }
    4433             : 
    4434             : /// expandLog - Lower a log intrinsic. Handles the special sequences for
    4435             : /// limited-precision mode.
    4436          75 : static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
    4437             :                          const TargetLowering &TLI) {
    4438             :   // TODO: What fast-math-flags should be set on the floating-point nodes?
    4439             : 
    4440          22 :   if (Op.getValueType() == MVT::f32 &&
    4441          25 :       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
    4442           3 :     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
    4443             : 
    4444             :     // Scale the exponent by log(2) [0.69314718f].
    4445           3 :     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
    4446             :     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
    4447           6 :                                         getF32Constant(DAG, 0x3f317218, dl));
    4448             : 
    4449             :     // Get the significand and build it into a floating-point number with
    4450             :     // exponent of 1.
    4451           3 :     SDValue X = GetSignificand(DAG, Op1, dl);
    4452             : 
    4453           3 :     SDValue LogOfMantissa;
    4454           3 :     if (LimitFloatPrecision <= 6) {
    4455             :       // For floating-point precision of 6:
    4456             :       //
    4457             :       //   LogofMantissa =
    4458             :       //     -1.1609546f +
    4459             :       //       (1.4034025f - 0.23903021f * x) * x;
    4460             :       //
    4461             :       // error 0.0034276066, which is better than 8 bits
    4462             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4463           2 :                                getF32Constant(DAG, 0xbe74c456, dl));
    4464             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4465           2 :                                getF32Constant(DAG, 0x3fb3a2b1, dl));
    4466           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4467           1 :       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4468           2 :                                   getF32Constant(DAG, 0x3f949a29, dl));
    4469           2 :     } else if (LimitFloatPrecision <= 12) {
    4470             :       // For floating-point precision of 12:
    4471             :       //
    4472             :       //   LogOfMantissa =
    4473             :       //     -1.7417939f +
    4474             :       //       (2.8212026f +
    4475             :       //         (-1.4699568f +
    4476             :       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
    4477             :       //
    4478             :       // error 0.000061011436, which is 14 bits
    4479             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4480           2 :                                getF32Constant(DAG, 0xbd67b6d6, dl));
    4481             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4482           2 :                                getF32Constant(DAG, 0x3ee4f4b8, dl));
    4483           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4484             :       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4485           2 :                                getF32Constant(DAG, 0x3fbc278b, dl));
    4486           1 :       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4487             :       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4488           2 :                                getF32Constant(DAG, 0x40348e95, dl));
    4489           1 :       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4490           1 :       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
    4491           2 :                                   getF32Constant(DAG, 0x3fdef31a, dl));
    4492             :     } else { // LimitFloatPrecision <= 18
    4493             :       // For floating-point precision of 18:
    4494             :       //
    4495             :       //   LogOfMantissa =
    4496             :       //     -2.1072184f +
    4497             :       //       (4.2372794f +
    4498             :       //         (-3.7029485f +
    4499             :       //           (2.2781945f +
    4500             :       //             (-0.87823314f +
    4501             :       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
    4502             :       //
    4503             :       // error 0.0000023660568, which is better than 18 bits
    4504             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4505           2 :                                getF32Constant(DAG, 0xbc91e5ac, dl));
    4506             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4507           2 :                                getF32Constant(DAG, 0x3e4350aa, dl));
    4508           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4509             :       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4510           2 :                                getF32Constant(DAG, 0x3f60d3e3, dl));
    4511           1 :       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4512             :       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4513           2 :                                getF32Constant(DAG, 0x4011cdf0, dl));
    4514           1 :       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4515             :       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
    4516           2 :                                getF32Constant(DAG, 0x406cfd1c, dl));
    4517           1 :       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
    4518             :       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
    4519           2 :                                getF32Constant(DAG, 0x408797cb, dl));
    4520           1 :       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
    4521           1 :       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
    4522           2 :                                   getF32Constant(DAG, 0x4006dcab, dl));
    4523             :     }
    4524             : 
    4525           3 :     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
    4526             :   }
    4527             : 
    4528             :   // No special expansion.
    4529          72 :   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
    4530             : }
    4531             : 
    4532             : /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
    4533             : /// limited-precision mode.
    4534          81 : static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
    4535             :                           const TargetLowering &TLI) {
    4536             :   // TODO: What fast-math-flags should be set on the floating-point nodes?
    4537             : 
    4538          27 :   if (Op.getValueType() == MVT::f32 &&
    4539          30 :       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
    4540           3 :     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
    4541             : 
    4542             :     // Get the exponent.
    4543           3 :     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
    4544             : 
    4545             :     // Get the significand and build it into a floating-point number with
    4546             :     // exponent of 1.
    4547           3 :     SDValue X = GetSignificand(DAG, Op1, dl);
    4548             : 
    4549             :     // Different possible minimax approximations of significand in
    4550             :     // floating-point for various degrees of accuracy over [1,2].
    4551           3 :     SDValue Log2ofMantissa;
    4552           3 :     if (LimitFloatPrecision <= 6) {
    4553             :       // For floating-point precision of 6:
    4554             :       //
    4555             :       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
    4556             :       //
    4557             :       // error 0.0049451742, which is more than 7 bits
    4558             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4559           2 :                                getF32Constant(DAG, 0xbeb08fe0, dl));
    4560             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4561           2 :                                getF32Constant(DAG, 0x40019463, dl));
    4562           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4563           1 :       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4564           2 :                                    getF32Constant(DAG, 0x3fd6633d, dl));
    4565           2 :     } else if (LimitFloatPrecision <= 12) {
    4566             :       // For floating-point precision of 12:
    4567             :       //
    4568             :       //   Log2ofMantissa =
    4569             :       //     -2.51285454f +
    4570             :       //       (4.07009056f +
    4571             :       //         (-2.12067489f +
    4572             :       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
    4573             :       //
    4574             :       // error 0.0000876136000, which is better than 13 bits
    4575             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4576           2 :                                getF32Constant(DAG, 0xbda7262e, dl));
    4577             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4578           2 :                                getF32Constant(DAG, 0x3f25280b, dl));
    4579           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4580             :       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4581           2 :                                getF32Constant(DAG, 0x4007b923, dl));
    4582           1 :       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4583             :       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4584           2 :                                getF32Constant(DAG, 0x40823e2f, dl));
    4585           1 :       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4586           1 :       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
    4587           2 :                                    getF32Constant(DAG, 0x4020d29c, dl));
    4588             :     } else { // LimitFloatPrecision <= 18
    4589             :       // For floating-point precision of 18:
    4590             :       //
    4591             :       //   Log2ofMantissa =
    4592             :       //     -3.0400495f +
    4593             :       //       (6.1129976f +
    4594             :       //         (-5.3420409f +
    4595             :       //           (3.2865683f +
    4596             :       //             (-1.2669343f +
    4597             :       //               (0.27515199f -
    4598             :       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
    4599             :       //
    4600             :       // error 0.0000018516, which is better than 18 bits
    4601             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4602           2 :                                getF32Constant(DAG, 0xbcd2769e, dl));
    4603             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4604           2 :                                getF32Constant(DAG, 0x3e8ce0b9, dl));
    4605           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4606             :       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4607           2 :                                getF32Constant(DAG, 0x3fa22ae7, dl));
    4608           1 :       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4609             :       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
    4610           2 :                                getF32Constant(DAG, 0x40525723, dl));
    4611           1 :       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4612             :       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
    4613           2 :                                getF32Constant(DAG, 0x40aaf200, dl));
    4614           1 :       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
    4615             :       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
    4616           2 :                                getF32Constant(DAG, 0x40c39dad, dl));
    4617           1 :       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
    4618           1 :       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
    4619           2 :                                    getF32Constant(DAG, 0x4042902c, dl));
    4620             :     }
    4621             : 
    4622           3 :     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
    4623             :   }
    4624             : 
    4625             :   // No special expansion.
    4626          78 :   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
    4627             : }
    4628             : 
    4629             : /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
    4630             : /// limited-precision mode.
    4631          80 : static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
    4632             :                            const TargetLowering &TLI) {
    4633             :   // TODO: What fast-math-flags should be set on the floating-point nodes?
    4634             : 
    4635          28 :   if (Op.getValueType() == MVT::f32 &&
    4636          31 :       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
    4637           3 :     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
    4638             : 
    4639             :     // Scale the exponent by log10(2) [0.30102999f].
    4640           3 :     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
    4641             :     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
    4642           6 :                                         getF32Constant(DAG, 0x3e9a209a, dl));
    4643             : 
    4644             :     // Get the significand and build it into a floating-point number with
    4645             :     // exponent of 1.
    4646           3 :     SDValue X = GetSignificand(DAG, Op1, dl);
    4647             : 
    4648           3 :     SDValue Log10ofMantissa;
    4649           3 :     if (LimitFloatPrecision <= 6) {
    4650             :       // For floating-point precision of 6:
    4651             :       //
    4652             :       //   Log10ofMantissa =
    4653             :       //     -0.50419619f +
    4654             :       //       (0.60948995f - 0.10380950f * x) * x;
    4655             :       //
    4656             :       // error 0.0014886165, which is 6 bits
    4657             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4658           2 :                                getF32Constant(DAG, 0xbdd49a13, dl));
    4659             :       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
    4660           2 :                                getF32Constant(DAG, 0x3f1c0789, dl));
    4661           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4662           1 :       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
    4663           2 :                                     getF32Constant(DAG, 0x3f011300, dl));
    4664           2 :     } else if (LimitFloatPrecision <= 12) {
    4665             :       // For floating-point precision of 12:
    4666             :       //
    4667             :       //   Log10ofMantissa =
    4668             :       //     -0.64831180f +
    4669             :       //       (0.91751397f +
    4670             :       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
    4671             :       //
    4672             :       // error 0.00019228036, which is better than 12 bits
    4673             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4674           2 :                                getF32Constant(DAG, 0x3d431f31, dl));
    4675             :       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
    4676           2 :                                getF32Constant(DAG, 0x3ea21fb2, dl));
    4677           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4678             :       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
    4679           2 :                                getF32Constant(DAG, 0x3f6ae232, dl));
    4680           1 :       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4681           1 :       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
    4682           2 :                                     getF32Constant(DAG, 0x3f25f7c3, dl));
    4683             :     } else { // LimitFloatPrecision <= 18
    4684             :       // For floating-point precision of 18:
    4685             :       //
    4686             :       //   Log10ofMantissa =
    4687             :       //     -0.84299375f +
    4688             :       //       (1.5327582f +
    4689             :       //         (-1.0688956f +
    4690             :       //           (0.49102474f +
    4691             :       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
    4692             :       //
    4693             :       // error 0.0000037995730, which is better than 18 bits
    4694             :       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
    4695           2 :                                getF32Constant(DAG, 0x3c5d51ce, dl));
    4696             :       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
    4697           2 :                                getF32Constant(DAG, 0x3e00685a, dl));
    4698           1 :       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
    4699             :       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
    4700           2 :                                getF32Constant(DAG, 0x3efb6798, dl));
    4701           1 :       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
    4702             :       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
    4703           2 :                                getF32Constant(DAG, 0x3f88d192, dl));
    4704           1 :       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
    4705             :       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
    4706           2 :                                getF32Constant(DAG, 0x3fc4316c, dl));
    4707           1 :       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
    4708           1 :       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
    4709           2 :                                     getF32Constant(DAG, 0x3f57ce70, dl));
    4710             :     }
    4711             : 
    4712           3 :     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
    4713             :   }
    4714             : 
    4715             :   // No special expansion.
    4716          77 :   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
    4717             : }
    4718             : 
    4719             : /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
    4720             : /// limited-precision mode.
    4721          95 : static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
    4722             :                           const TargetLowering &TLI) {
    4723          37 :   if (Op.getValueType() == MVT::f32 &&
    4724          40 :       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
    4725           3 :     return getLimitedPrecisionExp2(Op, dl, DAG);
    4726             : 
    4727             :   // No special expansion.
    4728          92 :   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
    4729             : }
    4730             : 
    4731             : /// visitPow - Lower a pow intrinsic. Handles the special sequences for
    4732             : /// limited-precision mode with x == 10.0f.
    4733          90 : static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
    4734             :                          SelectionDAG &DAG, const TargetLowering &TLI) {
    4735             :   bool IsExp10 = false;
    4736          68 :   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
    4737          37 :       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
    4738             :     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
    4739           3 :       APFloat Ten(10.0f);
    4740           3 :       IsExp10 = LHSC->isExactlyValue(Ten);
    4741             :     }
    4742             :   }
    4743             : 
    4744             :   // TODO: What fast-math-flags should be set on the FMUL node?
    4745           3 :   if (IsExp10) {
    4746             :     // Put the exponent in the right bit position for later addition to the
    4747             :     // final result:
    4748             :     //
    4749             :     //   #define LOG2OF10 3.3219281f
    4750             :     //   t0 = Op * LOG2OF10;
    4751             :     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
    4752           6 :                              getF32Constant(DAG, 0x40549a78, dl));
    4753           3 :     return getLimitedPrecisionExp2(t0, dl, DAG);
    4754             :   }
    4755             : 
    4756             :   // No special expansion.
    4757          87 :   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
    4758             : }
    4759             : 
    4760             : /// ExpandPowI - Expand a llvm.powi intrinsic.
    4761         104 : static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
    4762             :                           SelectionDAG &DAG) {
    4763             :   // If RHS is a constant, we can expand this out to a multiplication tree,
    4764             :   // otherwise we end up lowering to a call to __powidf2 (for example).  When
    4765             :   // optimizing for size, we only want to do this if the expansion would produce
    4766             :   // a small number of multiplies, otherwise we do the full expansion.
    4767             :   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
    4768             :     // Get the exponent as a positive value.
    4769          24 :     unsigned Val = RHSC->getSExtValue();
    4770          12 :     if ((int)Val < 0) Val = -Val;
    4771             : 
    4772             :     // powi(x, 0) -> 1.0
    4773          12 :     if (Val == 0)
    4774           0 :       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
    4775             : 
    4776          12 :     const Function &F = DAG.getMachineFunction().getFunction();
    4777          14 :     if (!F.optForSize() ||
    4778             :         // If optimizing for size, don't insert too many multiplies.
    4779             :         // This inserts up to 5 multiplies.
    4780           2 :         countPopulation(Val) + Log2_32(Val) < 7) {
    4781             :       // We use the simple binary decomposition method to generate the multiply
    4782             :       // sequence.  There are more optimal ways to do this (for example,
    4783             :       // powi(x,15) generates one more multiply than it should), but this has
    4784             :       // the benefit of being both really simple and much better than a libcall.
    4785             :       SDValue Res;  // Logically starts equal to 1.0
    4786          10 :       SDValue CurSquare = LHS;
    4787             :       // TODO: Intrinsics should have fast-math-flags that propagate to these
    4788             :       // nodes.
    4789          64 :       while (Val) {
    4790          27 :         if (Val & 1) {
    4791          14 :           if (Res.getNode())
    4792           4 :             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
    4793             :           else
    4794             :             Res = CurSquare;  // 1.0*CurSquare.
    4795             :         }
    4796             : 
    4797          27 :         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
    4798          27 :                                 CurSquare, CurSquare);
    4799          27 :         Val >>= 1;
    4800             :       }
    4801             : 
    4802             :       // If the original was negative, invert the result, producing 1/(x*x*x).
    4803          20 :       if (RHSC->getSExtValue() < 0)
    4804           1 :         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
    4805           2 :                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
    4806          10 :       return Res;
    4807             :     }
    4808             :   }
    4809             : 
    4810             :   // Otherwise, expand to a libcall.
    4811          94 :   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
    4812             : }
    4813             : 
    4814             : // getUnderlyingArgReg - Find underlying register used for a truncated or
    4815             : // bitcasted argument.
    4816             : static unsigned getUnderlyingArgReg(const SDValue &N) {
    4817        5860 :   switch (N.getOpcode()) {
    4818        2762 :   case ISD::CopyFromReg:
    4819        2762 :     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
    4820         126 :   case ISD::BITCAST:
    4821             :   case ISD::AssertZext:
    4822             :   case ISD::AssertSext:
    4823             :   case ISD::TRUNCATE:
    4824             :     return getUnderlyingArgReg(N.getOperand(0));
    4825             :   default:
    4826             :     return 0;
    4827             :   }
    4828             : }
    4829             : 
    4830             : /// If the DbgValueInst is a dbg_value of a function argument, create the
    4831             : /// corresponding DBG_VALUE machine instruction for it now.  At the end of
    4832             : /// instruction selection, they will be inserted to the entry BB.
    4833       18818 : bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
    4834             :     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
    4835             :     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
    4836             :   const Argument *Arg = dyn_cast<Argument>(V);
    4837             :   if (!Arg)
    4838             :     return false;
    4839             : 
    4840        2843 :   MachineFunction &MF = DAG.getMachineFunction();
    4841        2843 :   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
    4842             : 
    4843             :   bool IsIndirect = false;
    4844             :   Optional<MachineOperand> Op;
    4845             :   // Some arguments' frame index is recorded during argument lowering.
    4846        2843 :   int FI = FuncInfo.getArgumentFrameIndex(Arg);
    4847        2843 :   if (FI != std::numeric_limits<int>::max())
    4848             :     Op = MachineOperand::CreateFI(FI);
    4849             : 
    4850        2843 :   if (!Op && N.getNode()) {
    4851             :     unsigned Reg = getUnderlyingArgReg(N);
    4852        5566 :     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
    4853        2762 :       MachineRegisterInfo &RegInfo = MF.getRegInfo();
    4854        2762 :       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
    4855        2762 :       if (PR)
    4856             :         Reg = PR;
    4857             :     }
    4858        2804 :     if (Reg) {
    4859             :       Op = MachineOperand::CreateReg(Reg, false);
    4860             :       IsIndirect = IsDbgDeclare;
    4861             :     }
    4862             :   }
    4863             : 
    4864        2843 :   if (!Op && N.getNode())
    4865             :     // Check if frame index is available.
    4866             :     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
    4867             :       if (FrameIndexSDNode *FINode =
    4868          23 :           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
    4869          23 :         Op = MachineOperand::CreateFI(FINode->getIndex());
    4870             : 
    4871        2843 :   if (!Op) {
    4872             :     // Check if ValueMap has reg number.
    4873          49 :     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
    4874          98 :     if (VMI != FuncInfo.ValueMap.end()) {
    4875          39 :       const auto &TLI = DAG.getTargetLoweringInfo();
    4876             :       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
    4877         114 :                        V->getType(), isABIRegCopy(V));
    4878             :       unsigned NumRegs =
    4879          39 :           std::accumulate(RFV.RegCount.begin(), RFV.RegCount.end(), 0);
    4880          39 :       if (NumRegs > 1) {
    4881             :         unsigned I = 0;
    4882             :         unsigned Offset = 0;
    4883             :         auto RegisterVT = RFV.RegVTs.begin();
    4884          17 :         for (auto RegCount : RFV.RegCount) {
    4885           7 :           unsigned RegisterSize = (RegisterVT++)->getSizeInBits();
    4886          16 :           for (unsigned E = I + RegCount; I != E; ++I) {
    4887             :             // The vregs are guaranteed to be allocated in sequence.
    4888           9 :             Op = MachineOperand::CreateReg(VMI->second + I, false);
    4889             :             auto FragmentExpr = DIExpression::createFragmentExpression(
    4890           9 :                 Expr, Offset, RegisterSize);
    4891           9 :             if (!FragmentExpr)
    4892             :               continue;
    4893          18 :             FuncInfo.ArgDbgValues.push_back(
    4894          18 :                 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
    4895          45 :                         Op->getReg(), Variable, *FragmentExpr));
    4896           9 :             Offset += RegisterSize;
    4897             :           }
    4898             :         }
    4899           3 :         return true;
    4900             :       }
    4901          36 :       Op = MachineOperand::CreateReg(VMI->second, false);
    4902             :       IsIndirect = IsDbgDeclare;
    4903             :     }
    4904             :   }
    4905             : 
    4906        2840 :   if (!Op)
    4907             :     return false;
    4908             : 
    4909             :   assert(Variable->isValidLocationForIntrinsic(DL) &&
    4910             :          "Expected inlined-at fields to agree");
    4911        2830 :   if (Op->isReg())
    4912        5596 :     FuncInfo.ArgDbgValues.push_back(
    4913        5596 :         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
    4914       13990 :                 Op->getReg(), Variable, Expr));
    4915             :   else
    4916          64 :     FuncInfo.ArgDbgValues.push_back(
    4917          96 :         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
    4918             :             .add(*Op)
    4919             :             .addImm(0)
    4920             :             .addMetadata(Variable)
    4921          64 :             .addMetadata(Expr));
    4922             : 
    4923             :   return true;
    4924             : }
    4925             : 
    4926             : /// Return the appropriate SDDbgValue based on N.
    4927       15984 : SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
    4928             :                                              DILocalVariable *Variable,
    4929             :                                              DIExpression *Expr,
    4930             :                                              const DebugLoc &dl,
    4931             :                                              unsigned DbgSDNodeOrder) {
    4932             :   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
    4933             :     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
    4934             :     // stack slot locations as such instead of as indirectly addressed
    4935             :     // locations.
    4936        4013 :     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), dl,
    4937        4013 :                                      DbgSDNodeOrder);
    4938             :   }
    4939       11971 :   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, dl,
    4940       11971 :                          DbgSDNodeOrder);
    4941             : }
    4942             : 
    4943             : // VisualStudio defines setjmp as _setjmp
    4944             : #if defined(_MSC_VER) && defined(setjmp) && \
    4945             :                          !defined(setjmp_undefined_for_msvc)
    4946             : #  pragma push_macro("setjmp")
    4947             : #  undef setjmp
    4948             : #  define setjmp_undefined_for_msvc
    4949             : #endif
    4950             : 
    4951             : /// Lower the call to the specified intrinsic function. If we want to emit this
    4952             : /// as a call to a named external function, return the name. Otherwise, lower it
    4953             : /// and return null.
    4954             : const char *
    4955      170131 : SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
    4956      170131 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    4957      170131 :   SDLoc sdl = getCurSDLoc();
    4958      170131 :   DebugLoc dl = getCurDebugLoc();
    4959             :   SDValue Res;
    4960             : 
    4961      170131 :   switch (Intrinsic) {
    4962       39643 :   default:
    4963             :     // By default, turn this into a target intrinsic node.
    4964       39643 :     visitTargetIntrinsic(I, Intrinsic);
    4965       39643 :     return nullptr;
    4966         225 :   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
    4967         152 :   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
    4968           8 :   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
    4969          76 :   case Intrinsic::returnaddress:
    4970         380 :     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
    4971          76 :                              TLI.getPointerTy(DAG.getDataLayout()),
    4972             :                              getValue(I.getArgOperand(0))));
    4973          76 :     return nullptr;
    4974           6 :   case Intrinsic::addressofreturnaddress:
    4975          18 :     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
    4976             :                              TLI.getPointerTy(DAG.getDataLayout())));
    4977           6 :     return nullptr;
    4978         115 :   case Intrinsic::frameaddress:
    4979         575 :     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
    4980         115 :                              TLI.getPointerTy(DAG.getDataLayout()),
    4981             :                              getValue(I.getArgOperand(0))));
    4982         115 :     return nullptr;
    4983             :   case Intrinsic::read_register: {
    4984             :     Value *Reg = I.getArgOperand(0);
    4985         195 :     SDValue Chain = getRoot();
    4986             :     SDValue RegName =
    4987         195 :         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
    4988         390 :     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    4989         390 :     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
    4990         390 :       DAG.getVTList(VT, MVT::Other), Chain, RegName);
    4991         195 :     setValue(&I, Res);
    4992         195 :     DAG.setRoot(Res.getValue(1));
    4993             :     return nullptr;
    4994             :   }
    4995             :   case Intrinsic::write_register: {
    4996             :     Value *Reg = I.getArgOperand(0);
    4997             :     Value *RegValue = I.getArgOperand(1);
    4998         181 :     SDValue Chain = getRoot();
    4999             :     SDValue RegName =
    5000         181 :         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
    5001         362 :     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
    5002         543 :                             RegName, getValue(RegValue)));
    5003             :     return nullptr;
    5004             :   }
    5005           0 :   case Intrinsic::setjmp:
    5006           0 :     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
    5007           0 :   case Intrinsic::longjmp:
    5008           0 :     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
    5009             :   case Intrinsic::memcpy: {
    5010             :     const auto &MCI = cast<MemCpyInst>(I);
    5011        2126 :     SDValue Op1 = getValue(I.getArgOperand(0));
    5012        2126 :     SDValue Op2 = getValue(I.getArgOperand(1));
    5013        2126 :     SDValue Op3 = getValue(I.getArgOperand(2));
    5014        2126 :     unsigned Align = MCI.getAlignment();
    5015        2126 :     if (!Align)
    5016             :       Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
    5017        2126 :     bool isVol = MCI.isVolatile();
    5018        2338 :     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
    5019             :     // FIXME: Support passing different dest/src alignments to the memcpy DAG
    5020             :     // node.
    5021        2126 :     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
    5022             :                                false, isTC,
    5023             :                                MachinePointerInfo(I.getArgOperand(0)),
    5024        2126 :                                MachinePointerInfo(I.getArgOperand(1)));
    5025        2126 :     updateDAGForMaybeTailCall(MC);
    5026             :     return nullptr;
    5027             :   }
    5028             :   case Intrinsic::memset: {
    5029             :     const auto &MSI = cast<MemSetInst>(I);
    5030       23116 :     SDValue Op1 = getValue(I.getArgOperand(0));
    5031       23116 :     SDValue Op2 = getValue(I.getArgOperand(1));
    5032       23116 :     SDValue Op3 = getValue(I.getArgOperand(2));
    5033       23116 :     unsigned Align = MSI.getAlignment();
    5034       23116 :     if (!Align)
    5035             :       Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
    5036       23116 :     bool isVol = MSI.isVolatile();
    5037       23312 :     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
    5038       23116 :     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
    5039       23116 :                                isTC, MachinePointerInfo(I.getArgOperand(0)));
    5040       23116 :     updateDAGForMaybeTailCall(MS);
    5041             :     return nullptr;
    5042             :   }
    5043             :   case Intrinsic::memmove: {
    5044             :     const auto &MMI = cast<MemMoveInst>(I);
    5045         363 :     SDValue Op1 = getValue(I.getArgOperand(0));
    5046         363 :     SDValue Op2 = getValue(I.getArgOperand(1));
    5047         363 :     SDValue Op3 = getValue(I.getArgOperand(2));
    5048         363 :     unsigned Align = MMI.getAlignment();
    5049         363 :     if (!Align)
    5050             :       Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
    5051         363 :     bool isVol = MMI.isVolatile();
    5052         454 :     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
    5053             :     // FIXME: Support passing different dest/src alignments to the memmove DAG
    5054             :     // node.
    5055         363 :     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
    5056             :                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
    5057         363 :                                 MachinePointerInfo(I.getArgOperand(1)));
    5058         363 :     updateDAGForMaybeTailCall(MM);
    5059             :     return nullptr;
    5060             :   }
    5061             :   case Intrinsic::memcpy_element_unordered_atomic: {
    5062             :     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
    5063           6 :     SDValue Dst = getValue(MI.getRawDest());
    5064           6 :     SDValue Src = getValue(MI.getRawSource());
    5065           6 :     SDValue Length = getValue(MI.getLength());
    5066             : 
    5067             :     // Emit a library call.
    5068             :     TargetLowering::ArgListTy Args;
    5069             :     TargetLowering::ArgListEntry Entry;
    5070          12 :     Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
    5071           6 :     Entry.Node = Dst;
    5072           6 :     Args.push_back(Entry);
    5073             : 
    5074           6 :     Entry.Node = Src;
    5075           6 :     Args.push_back(Entry);
    5076             : 
    5077           6 :     Entry.Ty = MI.getLength()->getType();
    5078           6 :     Entry.Node = Length;
    5079           6 :     Args.push_back(Entry);
    5080             : 
    5081             :     uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
    5082             :     RTLIB::Libcall LibraryCall =
    5083           6 :         RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
    5084           6 :     if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
    5085           0 :       report_fatal_error("Unsupported element size");
    5086             : 
    5087          12 :     TargetLowering::CallLoweringInfo CLI(DAG);
    5088          12 :     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
    5089             :         TLI.getLibcallCallingConv(LibraryCall),
    5090           6 :         Type::getVoidTy(*DAG.getContext()),
    5091           6 :         DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
    5092             :                               TLI.getPointerTy(DAG.getDataLayout())),
    5093          24 :         std::move(Args));
    5094             : 
    5095           6 :     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
    5096           6 :     DAG.setRoot(CallResult.second);
    5097             :     return nullptr;
    5098             :   }
    5099             :   case Intrinsic::memmove_element_unordered_atomic: {
    5100             :     auto &MI = cast<AtomicMemMoveInst>(I);
    5101           6 :     SDValue Dst = getValue(MI.getRawDest());
    5102           6 :     SDValue Src = getValue(MI.getRawSource());
    5103           6 :     SDValue Length = getValue(MI.getLength());
    5104             : 
    5105             :     // Emit a library call.
    5106             :     TargetLowering::ArgListTy Args;
    5107             :     TargetLowering::ArgListEntry Entry;
    5108          12 :     Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
    5109           6 :     Entry.Node = Dst;
    5110           6 :     Args.push_back(Entry);
    5111             : 
    5112           6 :     Entry.Node = Src;
    5113           6 :     Args.push_back(Entry);
    5114             : 
    5115           6 :     Entry.Ty = MI.getLength()->getType();
    5116           6 :     Entry.Node = Length;
    5117           6 :     Args.push_back(Entry);
    5118             : 
    5119             :     uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
    5120             :     RTLIB::Libcall LibraryCall =
    5121           6 :         RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
    5122           6 :     if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
    5123           0 :       report_fatal_error("Unsupported element size");
    5124             : 
    5125          12 :     TargetLowering::CallLoweringInfo CLI(DAG);
    5126          12 :     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
    5127             :         TLI.getLibcallCallingConv(LibraryCall),
    5128           6 :         Type::getVoidTy(*DAG.getContext()),
    5129           6 :         DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
    5130             :                               TLI.getPointerTy(DAG.getDataLayout())),
    5131          24 :         std::move(Args));
    5132             : 
    5133           6 :     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
    5134           6 :     DAG.setRoot(CallResult.second);
    5135             :     return nullptr;
    5136             :   }
    5137             :   case Intrinsic::memset_element_unordered_atomic: {
    5138             :     auto &MI = cast<AtomicMemSetInst>(I);
    5139           6 :     SDValue Dst = getValue(MI.getRawDest());
    5140           6 :     SDValue Val = getValue(MI.getValue());
    5141           6 :     SDValue Length = getValue(MI.getLength());
    5142             : 
    5143             :     // Emit a library call.
    5144             :     TargetLowering::ArgListTy Args;
    5145             :     TargetLowering::ArgListEntry Entry;
    5146          12 :     Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
    5147           6 :     Entry.Node = Dst;
    5148           6 :     Args.push_back(Entry);
    5149             : 
    5150           6 :     Entry.Ty = Type::getInt8Ty(*DAG.getContext());
    5151           6 :     Entry.Node = Val;
    5152           6 :     Args.push_back(Entry);
    5153             : 
    5154           6 :     Entry.Ty = MI.getLength()->getType();
    5155           6 :     Entry.Node = Length;
    5156           6 :     Args.push_back(Entry);
    5157             : 
    5158             :     uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
    5159             :     RTLIB::Libcall LibraryCall =
    5160           6 :         RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
    5161           6 :     if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
    5162           0 :       report_fatal_error("Unsupported element size");
    5163             : 
    5164          12 :     TargetLowering::CallLoweringInfo CLI(DAG);
    5165          12 :     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
    5166             :         TLI.getLibcallCallingConv(LibraryCall),
    5167           6 :         Type::getVoidTy(*DAG.getContext()),
    5168           6 :         DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
    5169             :                               TLI.getPointerTy(DAG.getDataLayout())),
    5170          24 :         std::move(Args));
    5171             : 
    5172           6 :     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
    5173           6 :     DAG.setRoot(CallResult.second);
    5174             :     return nullptr;
    5175             :   }
    5176             :   case Intrinsic::dbg_addr:
    5177             :   case Intrinsic::dbg_declare: {
    5178             :     const DbgInfoIntrinsic &DI = cast<DbgInfoIntrinsic>(I);
    5179             :     DILocalVariable *Variable = DI.getVariable();
    5180             :     DIExpression *Expression = DI.getExpression();
    5181             :     assert(Variable && "Missing variable");
    5182             : 
    5183             :     // Check if address has undef value.
    5184        9899 :     const Value *Address = DI.getVariableLocation();
    5185       29660 :     if (!Address || isa<UndefValue>(Address) ||
    5186        9915 :         (Address->use_empty() && !isa<Argument>(Address))) {
    5187             :       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
    5188             :       return nullptr;
    5189             :     }
    5190             : 
    5191        9830 :     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
    5192             : 
    5193             :     // Check if this variable can be described by a frame index, typically
    5194             :     // either as a static alloca or a byval parameter.
    5195             :     int FI = std::numeric_limits<int>::max();
    5196             :     if (const auto *AI =
    5197        9830 :             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
    5198        9751 :       if (AI->isStaticAlloca()) {
    5199        9746 :         auto I = FuncInfo.StaticAllocaMap.find(AI);
    5200       19492 :         if (I != FuncInfo.StaticAllocaMap.end())
    5201        9746 :           FI = I->second;
    5202             :       }
    5203          79 :     } else if (const auto *Arg = dyn_cast<Argument>(
    5204             :                    Address->stripInBoundsConstantOffsets())) {
    5205          72 :       FI = FuncInfo.getArgumentFrameIndex(Arg);
    5206             :     }
    5207             : 
    5208             :     // llvm.dbg.addr is control dependent and always generates indirect
    5209             :     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
    5210             :     // the MachineFunction variable table.
    5211        9818 :     if (FI != std::numeric_limits<int>::max()) {
    5212        9764 :       if (Intrinsic == Intrinsic::dbg_addr)
    5213           6 :         DAG.AddDbgValue(DAG.getFrameIndexDbgValue(Variable, Expression, FI, dl,
    5214             :                                                   SDNodeOrder),
    5215           6 :                         getRoot().getNode(), isParameter);
    5216             :       return nullptr;
    5217             :     }
    5218             : 
    5219          66 :     SDValue &N = NodeMap[Address];
    5220          97 :     if (!N.getNode() && isa<Argument>(Address))
    5221             :       // Check unused arguments map.
    5222          60 :       N = UnusedArgNodeMap[Address];
    5223             :     SDDbgValue *SDV;
    5224          66 :     if (N.getNode()) {
    5225          35 :       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
    5226           2 :         Address = BCI->getOperand(0);
    5227             :       // Parameters are handled specially.
    5228             :       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
    5229          35 :       if (isParameter && FINode) {
    5230             :         // Byval parameter. We have a frame index at this point.
    5231           0 :         SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
    5232           0 :                                         FINode->getIndex(), dl, SDNodeOrder);
    5233          70 :       } else if (isa<Argument>(Address)) {
    5234             :         // Address is an argument, so try to emit its dbg value using
    5235             :         // virtual register info from the FuncInfo.ValueMap.
    5236          24 :         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
    5237          24 :         return nullptr;
    5238             :       } else {
    5239          11 :         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
    5240             :                               true, dl, SDNodeOrder);
    5241             :       }
    5242          11 :       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
    5243             :     } else {
    5244             :       // If Address is an argument then try to emit its dbg value using
    5245             :       // virtual register info from the FuncInfo.ValueMap.
    5246          31 :       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
    5247             :                                     N)) {
    5248             :         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
    5249             :       }
    5250             :     }
    5251             :     return nullptr;
    5252             :   }
    5253             :   case Intrinsic::dbg_value: {
    5254             :     const DbgValueInst &DI = cast<DbgValueInst>(I);
    5255             :     assert(DI.getVariable() && "Missing variable");
    5256             : 
    5257             :     DILocalVariable *Variable = DI.getVariable();
    5258             :     DIExpression *Expression = DI.getExpression();
    5259       38361 :     const Value *V = DI.getValue();
    5260       38361 :     if (!V)
    5261             :       return nullptr;
    5262             : 
    5263             :     SDDbgValue *SDV;
    5264       35859 :     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
    5265        9109 :       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
    5266        9109 :       DAG.AddDbgValue(SDV, nullptr, false);
    5267        9109 :       return nullptr;
    5268             :     }
    5269             : 
    5270             :     // Do not use getValue() in here; we don't want to generate code at
    5271             :     // this point if it hasn't been done yet.
    5272       53500 :     SDValue N = NodeMap[V];
    5273       50452 :     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
    5274        5922 :       N = UnusedArgNodeMap[V];
    5275       26750 :     if (N.getNode()) {
    5276       14991 :       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
    5277             :         return nullptr;
    5278       13260 :       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
    5279       13260 :       DAG.AddDbgValue(SDV, N.getNode(), false);
    5280       13260 :       return nullptr;
    5281             :     }
    5282             : 
    5283       11759 :     if (!V->use_empty() ) {
    5284             :       // Do not call getValue(V) yet, as we don't want to generate code.
    5285             :       // Remember it for later.
    5286       23404 :       DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
    5287       11702 :       DanglingDebugInfoMap[V] = DDI;
    5288             :       return nullptr;
    5289             :     }
    5290             : 
    5291             :     DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
    5292             :     DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
    5293             :     return nullptr;
    5294             :   }
    5295             : 
    5296             :   case Intrinsic::eh_typeid_for: {
    5297             :     // Find the type id for the given typeinfo.
    5298          76 :     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
    5299          76 :     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
    5300         152 :     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
    5301          76 :     setValue(&I, Res);
    5302          76 :     return nullptr;
    5303             :   }
    5304             : 
    5305          29 :   case Intrinsic::eh_return_i32:
    5306             :   case Intrinsic::eh_return_i64:
    5307          29 :     DAG.getMachineFunction().setCallsEHReturn(true);
    5308          58 :     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
    5309             :                             MVT::Other,
    5310             :                             getControlRoot(),
    5311             :                             getValue(I.getArgOperand(0)),
    5312         116 :                             getValue(I.getArgOperand(1))));
    5313          29 :     return nullptr;
    5314          15 :   case Intrinsic::eh_unwind_init:
    5315          15 :     DAG.getMachineFunction().setCallsUnwindInit(true);
    5316          15 :     return nullptr;
    5317          19 :   case Intrinsic::eh_dwarf_cfa:
    5318          95 :     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
    5319          19 :                              TLI.getPointerTy(DAG.getDataLayout()),
    5320             :                              getValue(I.getArgOperand(0))));
    5321          19 :     return nullptr;
    5322         174 :   case Intrinsic::eh_sjlj_callsite: {
    5323         174 :     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
    5324             :     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
    5325             :     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
    5326             :     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
    5327             : 
    5328         174 :     MMI.setCurrentCallSite(CI->getZExtValue());
    5329         174 :     return nullptr;
    5330             :   }
    5331          35 :   case Intrinsic::eh_sjlj_functioncontext: {
    5332             :     // Get and store the index of the function context.
    5333          35 :     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
    5334             :     AllocaInst *FnCtx =
    5335             :       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
    5336          70 :     int FI = FuncInfo.StaticAllocaMap[FnCtx];
    5337             :     MFI.setFunctionContextIndex(FI);
    5338          35 :     return nullptr;
    5339             :   }
    5340          30 :   case Intrinsic::eh_sjlj_setjmp: {
    5341          30 :     SDValue Ops[2];
    5342          30 :     Ops[0] = getRoot();
    5343          30 :     Ops[1] = getValue(I.getArgOperand(0));
    5344          30 :     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
    5345          30 :                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
    5346          30 :     setValue(&I, Op.getValue(0));
    5347          30 :     DAG.setRoot(Op.getValue(1));
    5348             :     return nullptr;
    5349             :   }
    5350          22 :   case Intrinsic::eh_sjlj_longjmp:
    5351          44 :     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
    5352          66 :                             getRoot(), getValue(I.getArgOperand(0))));
    5353          22 :     return nullptr;
    5354          35 :   case Intrinsic::eh_sjlj_setup_dispatch:
    5355          70 :     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
    5356         105 :                             getRoot()));
    5357          35 :     return nullptr;
    5358         288 :   case Intrinsic::masked_gather:
    5359         288 :     visitMaskedGather(I);
    5360         288 :     return nullptr;
    5361         222 :   case Intrinsic::masked_load:
    5362         222 :     visitMaskedLoad(I);
    5363         222 :     return nullptr;
    5364          85 :   case Intrinsic::masked_scatter:
    5365          85 :     visitMaskedScatter(I);
    5366          85 :     return nullptr;
    5367         102 :   case Intrinsic::masked_store:
    5368         102 :     visitMaskedStore(I);
    5369         102 :     return nullptr;
    5370          16 :   case Intrinsic::masked_expandload:
    5371          16 :     visitMaskedLoad(I, true /* IsExpanding */);
    5372          16 :     return nullptr;
    5373          20 :   case Intrinsic::masked_compressstore:
    5374          20 :     visitMaskedStore(I, true /* IsCompressing */);
    5375          20 :     return nullptr;
    5376             :   case Intrinsic::x86_mmx_pslli_w:
    5377             :   case Intrinsic::x86_mmx_pslli_d:
    5378             :   case Intrinsic::x86_mmx_pslli_q:
    5379             :   case Intrinsic::x86_mmx_psrli_w:
    5380             :   case Intrinsic::x86_mmx_psrli_d:
    5381             :   case Intrinsic::x86_mmx_psrli_q:
    5382             :   case Intrinsic::x86_mmx_psrai_w:
    5383             :   case Intrinsic::x86_mmx_psrai_d: {
    5384         154 :     SDValue ShAmt = getValue(I.getArgOperand(1));
    5385             :     if (isa<ConstantSDNode>(ShAmt)) {
    5386         129 :       visitTargetIntrinsic(I, Intrinsic);
    5387         129 :       return nullptr;
    5388             :     }
    5389             :     unsigned NewIntrinsic = 0;
    5390          25 :     EVT ShAmtVT = MVT::v2i32;
    5391          25 :     switch (Intrinsic) {
    5392             :     case Intrinsic::x86_mmx_pslli_w:
    5393             :       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
    5394             :       break;
    5395           2 :     case Intrinsic::x86_mmx_pslli_d:
    5396             :       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
    5397           2 :       break;
    5398           9 :     case Intrinsic::x86_mmx_pslli_q:
    5399             :       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
    5400           9 :       break;
    5401           2 :     case Intrinsic::x86_mmx_psrli_w:
    5402             :       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
    5403           2 :       break;
    5404           2 :     case Intrinsic::x86_mmx_psrli_d:
    5405             :       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
    5406           2 :       break;
    5407           4 :     case Intrinsic::x86_mmx_psrli_q:
    5408             :       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
    5409           4 :       break;
    5410           2 :     case Intrinsic::x86_mmx_psrai_w:
    5411             :       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
    5412           2 :       break;
    5413           2 :     case Intrinsic::x86_mmx_psrai_d:
    5414             :       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
    5415           2 :       break;
    5416           0 :     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
    5417             :     }
    5418             : 
    5419             :     // The vector shift intrinsics with scalars uses 32b shift amounts but
    5420             :     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
    5421             :     // to be zero.
    5422             :     // We must do this early because v2i32 is not a legal type.
    5423          25 :     SDValue ShOps[2];
    5424          25 :     ShOps[0] = ShAmt;
    5425          50 :     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
    5426          50 :     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
    5427          50 :     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    5428          50 :     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
    5429          50 :     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
    5430          25 :                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
    5431          75 :                        getValue(I.getArgOperand(0)), ShAmt);
    5432          25 :     setValue(&I, Res);
    5433          25 :     return nullptr;
    5434             :   }
    5435         104 :   case Intrinsic::powi:
    5436         312 :     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
    5437             :                             getValue(I.getArgOperand(1)), DAG));
    5438         104 :     return nullptr;
    5439          75 :   case Intrinsic::log:
    5440         150 :     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
    5441          75 :     return nullptr;
    5442          81 :   case Intrinsic::log2:
    5443         162 :     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
    5444          81 :     return nullptr;
    5445          80 :   case Intrinsic::log10:
    5446         160 :     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
    5447          80 :     return nullptr;
    5448          71 :   case Intrinsic::exp:
    5449         142 :     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
    5450          71 :     return nullptr;
    5451          95 :   case Intrinsic::exp2:
    5452         190 :     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
    5453          95 :     return nullptr;
    5454          90 :   case Intrinsic::pow:
    5455         270 :     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
    5456             :                            getValue(I.getArgOperand(1)), DAG, TLI));
    5457          90 :     return nullptr;
    5458        2513 :   case Intrinsic::sqrt:
    5459             :   case Intrinsic::fabs:
    5460             :   case Intrinsic::sin:
    5461             :   case Intrinsic::cos:
    5462             :   case Intrinsic::floor:
    5463             :   case Intrinsic::ceil:
    5464             :   case Intrinsic::trunc:
    5465             :   case Intrinsic::rint:
    5466             :   case Intrinsic::nearbyint:
    5467             :   case Intrinsic::round:
    5468             :   case Intrinsic::canonicalize: {
    5469             :     unsigned Opcode;
    5470        2513 :     switch (Intrinsic) {
    5471           0 :     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
    5472             :     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
    5473         759 :     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
    5474          90 :     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
    5475          79 :     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
    5476         246 :     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
    5477         145 :     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
    5478         148 :     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
    5479         118 :     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
    5480         111 :     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
    5481          82 :     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
    5482         279 :     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
    5483             :     }
    5484             : 
    5485       12565 :     setValue(&I, DAG.getNode(Opcode, sdl,
    5486        5026 :                              getValue(I.getArgOperand(0)).getValueType(),
    5487             :                              getValue(I.getArgOperand(0))));
    5488        2513 :     return nullptr;
    5489             :   }
    5490             :   case Intrinsic::minnum: {
    5491        1730 :     auto VT = getValue(I.getArgOperand(0)).getValueType();
    5492             :     unsigned Opc =
    5493         865 :         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
    5494         865 :             ? ISD::FMINNAN
    5495             :             : ISD::FMINNUM;
    5496        3460 :     setValue(&I, DAG.getNode(Opc, sdl, VT,
    5497             :                              getValue(I.getArgOperand(0)),
    5498             :                              getValue(I.getArgOperand(1))));
    5499             :     return nullptr;
    5500             :   }
    5501             :   case Intrinsic::maxnum: {
    5502        1720 :     auto VT = getValue(I.getArgOperand(0)).getValueType();
    5503             :     unsigned Opc =
    5504         860 :         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
    5505         860 :             ? ISD::FMAXNAN
    5506             :             : ISD::FMAXNUM;
    5507        3440 :     setValue(&I, DAG.getNode(Opc, sdl, VT,
    5508             :                              getValue(I.getArgOperand(0)),
    5509             :                              getValue(I.getArgOperand(1))));
    5510             :     return nullptr;
    5511             :   }
    5512         189 :   case Intrinsic::copysign:
    5513        1134 :     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
    5514         378 :                              getValue(I.getArgOperand(0)).getValueType(),
    5515             :                              getValue(I.getArgOperand(0)),
    5516             :                              getValue(I.getArgOperand(1))));
    5517         189 :     return nullptr;
    5518         685 :   case Intrinsic::fma:
    5519        4110 :     setValue(&I, DAG.getNode(ISD::FMA, sdl,
    5520        1370 :                              getValue(I.getArgOperand(0)).getValueType(),
    5521             :                              getValue(I.getArgOperand(0)),
    5522             :                              getValue(I.getArgOperand(1)),
    5523             :                              getValue(I.getArgOperand(2))));
    5524         685 :     return nullptr;
    5525             :   case Intrinsic::experimental_constrained_fadd:
    5526             :   case Intrinsic::experimental_constrained_fsub:
    5527             :   case Intrinsic::experimental_constrained_fmul:
    5528             :   case Intrinsic::experimental_constrained_fdiv:
    5529             :   case Intrinsic::experimental_constrained_frem:
    5530             :   case Intrinsic::experimental_constrained_fma:
    5531             :   case Intrinsic::experimental_constrained_sqrt:
    5532             :   case Intrinsic::experimental_constrained_pow:
    5533             :   case Intrinsic::experimental_constrained_powi:
    5534             :   case Intrinsic::experimental_constrained_sin:
    5535             :   case Intrinsic::experimental_constrained_cos:
    5536             :   case Intrinsic::experimental_constrained_exp:
    5537             :   case Intrinsic::experimental_constrained_exp2:
    5538             :   case Intrinsic::experimental_constrained_log:
    5539             :   case Intrinsic::experimental_constrained_log10:
    5540             :   case Intrinsic::experimental_constrained_log2:
    5541             :   case Intrinsic::experimental_constrained_rint:
    5542             :   case Intrinsic::experimental_constrained_nearbyint:
    5543          40 :     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
    5544          40 :     return nullptr;
    5545         874 :   case Intrinsic::fmuladd: {
    5546        1748 :     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    5547        1748 :     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
    5548         874 :         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
    5549         726 :       setValue(&I, DAG.getNode(ISD::FMA, sdl,
    5550         242 :                                getValue(I.getArgOperand(0)).getValueType(),
    5551             :                                getValue(I.getArgOperand(0)),
    5552             :                                getValue(I.getArgOperand(1)),
    5553             :                                getValue(I.getArgOperand(2))));
    5554             :     } else {
    5555             :       // TODO: Intrinsic calls should have fast-math-flags.
    5556         753 :       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
    5557        1506 :                                 getValue(I.getArgOperand(0)).getValueType(),
    5558             :                                 getValue(I.getArgOperand(0)),
    5559        3765 :                                 getValue(I.getArgOperand(1)));
    5560         753 :       SDValue Add = DAG.getNode(ISD::FADD, sdl,
    5561        1506 :                                 getValue(I.getArgOperand(0)).getValueType(),
    5562             :                                 Mul,
    5563        3012 :                                 getValue(I.getArgOperand(2)));
    5564         753 :       setValue(&I, Add);
    5565             :     }
    5566             :     return nullptr;
    5567             :   }
    5568         229 :   case Intrinsic::convert_to_fp16:
    5569        1145 :     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
    5570             :                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
    5571             :                                          getValue(I.getArgOperand(0)),
    5572             :                                          DAG.getTargetConstant(0, sdl,
    5573             :                                                                MVT::i32))));
    5574         229 :     return nullptr;
    5575         275 :   case Intrinsic::convert_from_fp16:
    5576        1650 :     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
    5577         275 :                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
    5578             :                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
    5579             :                                          getValue(I.getArgOperand(0)))));
    5580         275 :     return nullptr;
    5581             :   case Intrinsic::pcmarker: {
    5582           0 :     SDValue Tmp = getValue(I.getArgOperand(0));
    5583           0 :     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
    5584             :     return nullptr;
    5585             :   }
    5586          22 :   case Intrinsic::readcyclecounter: {
    5587          22 :     SDValue Op = getRoot();
    5588          44 :     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
    5589          44 :                       DAG.getVTList(MVT::i64, MVT::Other), Op);
    5590          22 :     setValue(&I, Res);
    5591          22 :     DAG.setRoot(Res.getValue(1));
    5592             :     return nullptr;
    5593             :   }
    5594         279 :   case Intrinsic::bitreverse:
    5595        1395 :     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
    5596         558 :                              getValue(I.getArgOperand(0)).getValueType(),
    5597             :                              getValue(I.getArgOperand(0))));
    5598         279 :     return nullptr;
    5599         641 :   case Intrinsic::bswap:
    5600        3205 :     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
    5601        1282 :                              getValue(I.getArgOperand(0)).getValueType(),
    5602             :                              getValue(I.getArgOperand(0))));
    5603         641 :     return nullptr;
    5604             :   case Intrinsic::cttz: {
    5605         724 :     SDValue Arg = getValue(I.getArgOperand(0));
    5606             :     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
    5607        1448 :     EVT Ty = Arg.getValueType();
    5608        2172 :     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
    5609             :                              sdl, Ty, Arg));
    5610             :     return nullptr;
    5611             :   }
    5612             :   case Intrinsic::ctlz: {
    5613         813 :     SDValue Arg = getValue(I.getArgOperand(0));
    5614             :     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
    5615        1626 :     EVT Ty = Arg.getValueType();
    5616        2439 :     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
    5617             :                              sdl, Ty, Arg));
    5618             :     return nullptr;
    5619             :   }
    5620             :   case Intrinsic::ctpop: {
    5621         495 :     SDValue Arg = getValue(I.getArgOperand(0));
    5622         990 :     EVT Ty = Arg.getValueType();
    5623        1485 :     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
    5624             :     return nullptr;
    5625             :   }
    5626         114 :   case Intrinsic::stacksave: {
    5627         114 :     SDValue Op = getRoot();
    5628         228 :     Res = DAG.getNode(
    5629             :         ISD::STACKSAVE, sdl,
    5630         342 :         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
    5631         114 :     setValue(&I, Res);
    5632         114 :     DAG.setRoot(Res.getValue(1));
    5633             :     return nullptr;
    5634             :   }
    5635             :   case Intrinsic::stackrestore:
    5636          24 :     Res = getValue(I.getArgOperand(0));
    5637          72 :     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
    5638          24 :     return nullptr;
    5639           4 :   case Intrinsic::get_dynamic_area_offset: {
    5640           4 :     SDValue Op = getRoot();
    5641           4 :     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
    5642           8 :     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
    5643             :     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
    5644             :     // target.
    5645           4 :     if (PtrTy != ResTy)
    5646           0 :       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
    5647             :                          " intrinsic!");
    5648           8 :     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
    5649           4 :                       Op);
    5650           4 :     DAG.setRoot(Op);
    5651           4 :     setValue(&I, Res);
    5652             :     return nullptr;
    5653             :   }
    5654         286 :   case Intrinsic::stackguard: {
    5655         286 :     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
    5656         286 :     MachineFunction &MF = DAG.getMachineFunction();
    5657         286 :     const Module &M = *MF.getFunction().getParent();
    5658         286 :     SDValue Chain = getRoot();
    5659         286 :     if (TLI.useLoadStackGuardNode()) {
    5660         152 :       Res = getLoadStackGuard(DAG, sdl, Chain);
    5661             :     } else {
    5662         134 :       const Value *Global = TLI.getSDagStackGuard(M);
    5663         134 :       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
    5664         268 :       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
    5665             :                         MachinePointerInfo(Global, 0), Align,
    5666         268 :                         MachineMemOperand::MOVolatile);
    5667             :     }
    5668         286 :     if (TLI.useStackGuardXorFP())
    5669          74 :       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
    5670         286 :     DAG.setRoot(Chain);
    5671         286 :     setValue(&I, Res);
    5672             :     return nullptr;
    5673             :   }
    5674         638 :   case Intrinsic::stackprotector: {
    5675             :     // Emit code into the DAG to store the stack guard onto the stack.
    5676         638 :     MachineFunction &MF = DAG.getMachineFunction();
    5677         638 :     MachineFrameInfo &MFI = MF.getFrameInfo();
    5678             :     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
    5679         638 :     SDValue Src, Chain = getRoot();
    5680             : 
    5681         638 :     if (TLI.useLoadStackGuardNode())
    5682         140 :       Src = getLoadStackGuard(DAG, sdl, Chain);
    5683             :     else
    5684         498 :       Src = getValue(I.getArgOperand(0));   // The guard's value.
    5685             : 
    5686             :     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
    5687             : 
    5688        1276 :     int FI = FuncInfo.StaticAllocaMap[Slot];
    5689             :     MFI.setStackProtectorIndex(FI);
    5690             : 
    5691         638 :     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
    5692             : 
    5693             :     // Store the stack protector onto the stack.
    5694        1276 :     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
    5695             :                                                  DAG.getMachineFunction(), FI),
    5696        1276 :                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
    5697         638 :     setValue(&I, Res);
    5698         638 :     DAG.setRoot(Res);
    5699             :     return nullptr;
    5700             :   }
    5701             :   case Intrinsic::objectsize: {
    5702             :     // If we don't know by now, we're never going to know.
    5703             :     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
    5704             : 
    5705             :     assert(CI && "Non-constant type in __builtin_object_size?");
    5706             : 
    5707           0 :     SDValue Arg = getValue(I.getCalledValue());
    5708           0 :     EVT Ty = Arg.getValueType();
    5709             : 
    5710           0 :     if (CI->isZero())
    5711           0 :       Res = DAG.getConstant(-1ULL, sdl, Ty);
    5712             :     else
    5713           0 :       Res = DAG.getConstant(0, sdl, Ty);
    5714             : 
    5715           0 :     setValue(&I, Res);
    5716             :     return nullptr;
    5717             :   }
    5718             :   case Intrinsic::annotation:
    5719             :   case Intrinsic::ptr_annotation:
    5720             :   case Intrinsic::invariant_group_barrier:
    5721             :     // Drop the intrinsic, but forward the value
    5722           3 :     setValue(&I, getValue(I.getOperand(0)));
    5723           3 :     return nullptr;
    5724             :   case Intrinsic::assume:
    5725             :   case Intrinsic::var_annotation:
    5726             :   case Intrinsic::sideeffect:
    5727             :     // Discard annotate attributes, assumptions, and artificial side-effects.
    5728             :     return nullptr;
    5729             : 
    5730           1 :   case Intrinsic::codeview_annotation: {
    5731             :     // Emit a label associated with this metadata.
    5732           1 :     MachineFunction &MF = DAG.getMachineFunction();
    5733             :     MCSymbol *Label =
    5734           2 :         MF.getMMI().getContext().createTempSymbol("annotation", true);
    5735           1 :     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
    5736             :     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
    5737           1 :     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
    5738           1 :     DAG.setRoot(Res);
    5739           1 :     return nullptr;
    5740             :   }
    5741             : 
    5742             :   case Intrinsic::init_trampoline: {
    5743             :     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
    5744             : 
    5745           4 :     SDValue Ops[6];
    5746           4 :     Ops[0] = getRoot();
    5747           4 :     Ops[1] = getValue(I.getArgOperand(0));
    5748           4 :     Ops[2] = getValue(I.getArgOperand(1));
    5749           4 :     Ops[3] = getValue(I.getArgOperand(2));
    5750           8 :     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
    5751           4 :     Ops[5] = DAG.getSrcValue(F);
    5752             : 
    5753           8 :     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
    5754             : 
    5755           4 :     DAG.setRoot(Res);
    5756             :     return nullptr;
    5757             :   }
    5758           4 :   case Intrinsic::adjust_trampoline:
    5759          20 :     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
    5760           4 :                              TLI.getPointerTy(DAG.getDataLayout()),
    5761             :                              getValue(I.getArgOperand(0))));
    5762           4 :     return nullptr;
    5763             :   case Intrinsic::gcroot: {
    5764             :     assert(DAG.getMachineFunction().getFunction().hasGC() &&
    5765             :            "only valid in functions with gc specified, enforced by Verifier");
    5766             :     assert(GFI && "implied by previous");
    5767             :     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
    5768             :     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
    5769             : 
    5770           2 :     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
    5771           2 :     GFI->addStackRoot(FI->getIndex(), TypeMap);
    5772           2 :     return nullptr;
    5773             :   }
    5774           0 :   case Intrinsic::gcread:
    5775             :   case Intrinsic::gcwrite:
    5776           0 :     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
    5777           6 :   case Intrinsic::flt_rounds:
    5778          18 :     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
    5779           6 :     return nullptr;
    5780             : 
    5781             :   case Intrinsic::expect:
    5782             :     // Just replace __builtin_expect(exp, c) with EXP.
    5783          10 :     setValue(&I, getValue(I.getArgOperand(0)));
    5784          10 :     return nullptr;
    5785             : 
    5786         208 :   case Intrinsic::debugtrap:
    5787             :   case Intrinsic::trap: {
    5788             :     StringRef TrapFuncName =
    5789         416 :         I.getAttributes()
    5790         416 :             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
    5791         208 :             .getValueAsString();
    5792         208 :     if (TrapFuncName.empty()) {
    5793         199 :       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
    5794             :         ISD::TRAP : ISD::DEBUGTRAP;
    5795         597 :       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
    5796         199 :       return nullptr;
    5797             :     }
    5798             :     TargetLowering::ArgListTy Args;
    5799             : 
    5800          18 :     TargetLowering::CallLoweringInfo CLI(DAG);
    5801          18 :     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
    5802             :         CallingConv::C, I.getType(),
    5803           9 :         DAG.getExternalSymbol(TrapFuncName.data(),
    5804             :                               TLI.getPointerTy(DAG.getDataLayout())),
    5805          27 :         std::move(Args));
    5806             : 
    5807           9 :     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
    5808           9 :     DAG.setRoot(Result.second);
    5809             :     return nullptr;
    5810             :   }
    5811             : 
    5812         481 :   case Intrinsic::uadd_with_overflow:
    5813             :   case Intrinsic::sadd_with_overflow:
    5814             :   case Intrinsic::usub_with_overflow:
    5815             :   case Intrinsic::ssub_with_overflow:
    5816             :   case Intrinsic::umul_with_overflow:
    5817             :   case Intrinsic::smul_with_overflow: {
    5818             :     ISD::NodeType Op;
    5819         481 :     switch (Intrinsic) {
    5820           0 :     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
    5821             :     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
    5822         108 :     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
    5823          71 :     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
    5824          59 :     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
    5825          65 :     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
    5826          52 :     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
    5827             :     }
    5828         481 :     SDValue Op1 = getValue(I.getArgOperand(0));
    5829         481 :     SDValue Op2 = getValue(I.getArgOperand(1));
    5830             : 
    5831        1443 :     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
    5832         481 :     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
    5833             :     return nullptr;
    5834             :   }
    5835         204 :   case Intrinsic::prefetch: {
    5836         204 :     SDValue Ops[5];
    5837         204 :     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
    5838         204 :     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
    5839         204 :     Ops[0] = DAG.getRoot();
    5840         204 :     Ops[1] = getValue(I.getArgOperand(0));
    5841         204 :     Ops[2] = getValue(I.getArgOperand(1));
    5842         204 :     Ops[3] = getValue(I.getArgOperand(2));
    5843         204 :     Ops[4] = getValue(I.getArgOperand(3));
    5844         204 :     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
    5845         204 :                                              DAG.getVTList(MVT::Other), Ops,
    5846         204 :                                              EVT::getIntegerVT(*Context, 8),
    5847             :                                              MachinePointerInfo(I.getArgOperand(0)),
    5848             :                                              0, /* align */
    5849         612 :                                              Flags);
    5850             : 
    5851             :     // Chain the prefetch in parallell with any pending loads, to stay out of
    5852             :     // the way of later optimizations.
    5853         204 :     PendingLoads.push_back(Result);
    5854         204 :     Result = getRoot();
    5855         204 :     DAG.setRoot(Result);
    5856             :     return nullptr;
    5857             :   }
    5858       41470 :   case Intrinsic::lifetime_start:
    5859             :   case Intrinsic::lifetime_end: {
    5860             :     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
    5861             :     // Stack coloring is not enabled in O0, discard region information.
    5862       41470 :     if (TM.getOptLevel() == CodeGenOpt::None)
    5863             :       return nullptr;
    5864             : 
    5865             :     SmallVector<Value *, 4> Allocas;
    5866       82938 :     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
    5867             : 
    5868       41473 :     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
    5869       82942 :            E = Allocas.end(); Object != E; ++Object) {
    5870       41475 :       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
    5871             : 
    5872             :       // Could not find an Alloca.
    5873           2 :       if (!LifetimeObject)
    5874           2 :         continue;
    5875             : 
    5876             :       // First check that the Alloca is static, otherwise it won't have a
    5877             :       // valid frame index.
    5878       41473 :       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
    5879       82946 :       if (SI == FuncInfo.StaticAllocaMap.end())
    5880           2 :         return nullptr;
    5881             : 
    5882       41471 :       int FI = SI->second;
    5883             : 
    5884       41471 :       SDValue Ops[2];
    5885       41471 :       Ops[0] = getRoot();
    5886       41471 :       Ops[1] =
    5887      165884 :           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
    5888       41471 :       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
    5889             : 
    5890       82942 :       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
    5891       41471 :       DAG.setRoot(Res);
    5892             :     }
    5893             :     return nullptr;
    5894             :   }
    5895         320 :   case Intrinsic::invariant_start:
    5896             :     // Discard region information.
    5897         960 :     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
    5898         320 :     return nullptr;
    5899             :   case Intrinsic::invariant_end:
    5900             :     // Discard region information.
    5901             :     return nullptr;
    5902           3 :   case Intrinsic::clear_cache:
    5903           3 :     return TLI.getClearCacheBuiltinName();
    5904             :   case Intrinsic::donothing:
    5905             :     // ignore
    5906             :     return nullptr;
    5907         112 :   case Intrinsic::experimental_stackmap:
    5908         112 :     visitStackmap(I);
    5909         112 :     return nullptr;
    5910             :   case Intrinsic::experimental_patchpoint_void:
    5911             :   case Intrinsic::experimental_patchpoint_i64:
    5912         115 :     visitPatchpoint(&I);
    5913         115 :     return nullptr;
    5914          58 :   case Intrinsic::experimental_gc_statepoint:
    5915         116 :     LowerStatepoint(ImmutableStatepoint(&I));
    5916          58 :     return nullptr;
    5917             :   case Intrinsic::experimental_gc_result:
    5918          24 :     visitGCResult(cast<GCResultInst>(I));
    5919          24 :     return nullptr;
    5920             :   case Intrinsic::experimental_gc_relocate:
    5921          66 :     visitGCRelocate(cast<GCRelocateInst>(I));
    5922          66 :     return nullptr;
    5923           0 :   case Intrinsic::instrprof_increment:
    5924           0 :     llvm_unreachable("instrprof failed to lower an increment");
    5925           0 :   case Intrinsic::instrprof_value_profile:
    5926           0 :     llvm_unreachable("instrprof failed to lower a value profiling call");
    5927          10 :   case Intrinsic::localescape: {
    5928          10 :     MachineFunction &MF = DAG.getMachineFunction();
    5929          10 :     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
    5930             : 
    5931             :     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
    5932             :     // is the same on all targets.
    5933          42 :     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
    5934             :       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
    5935          16 :       if (isa<ConstantPointerNull>(Arg))
    5936             :         continue; // Skip null pointers. They represent a hole in index space.
    5937             :       AllocaInst *Slot = cast<AllocaInst>(Arg);
    5938             :       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
    5939             :              "can only escape static allocas");
    5940          32 :       int FI = FuncInfo.StaticAllocaMap[Slot];
    5941             :       MCSymbol *FrameAllocSym =
    5942          32 :           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
    5943          16 :               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
    5944          16 :       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
    5945          16 :               TII->get(TargetOpcode::LOCAL_ESCAPE))
    5946             :           .addSym(FrameAllocSym)
    5947             :           .addFrameIndex(FI);
    5948             :     }
    5949             : 
    5950             :     return nullptr;
    5951             :   }
    5952             : 
    5953          12 :   case Intrinsic::localrecover: {
    5954             :     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
    5955          12 :     MachineFunction &MF = DAG.getMachineFunction();
    5956             :     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
    5957             : 
    5958             :     // Get the symbol that defines the frame offset.
    5959             :     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
    5960             :     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
    5961             :     unsigned IdxVal =
    5962          12 :         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
    5963             :     MCSymbol *FrameAllocSym =
    5964          24 :         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
    5965          12 :             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
    5966             : 
    5967             :     // Create a MCSymbol for the label to avoid any target lowering
    5968             :     // that would make this PC relative.
    5969          24 :     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
    5970             :     SDValue OffsetVal =
    5971          24 :         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
    5972             : 
    5973             :     // Add the offset to the FP.
    5974             :     Value *FP = I.getArgOperand(1);
    5975          12 :     SDValue FPVal = getValue(FP);
    5976          24 :     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
    5977          12 :     setValue(&I, Add);
    5978             : 
    5979             :     return nullptr;
    5980             :   }
    5981             : 
    5982             :   case Intrinsic::eh_exceptionpointer:
    5983             :   case Intrinsic::eh_exceptioncode: {
    5984             :     // Get the exception pointer vreg, copy from it, and resize it to fit.
    5985             :     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
    5986           6 :     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
    5987           6 :     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
    5988           6 :     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
    5989             :     SDValue N =
    5990          30 :         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
    5991           6 :     if (Intrinsic == Intrinsic::eh_exceptioncode)
    5992          12 :       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
    5993           6 :     setValue(&I, N);
    5994             :     return nullptr;
    5995             :   }
    5996           2 :   case Intrinsic::xray_customevent: {
    5997             :     // Here we want to make sure that the intrinsic behaves as if it has a
    5998             :     // specific calling convention, and only for x86_64.
    5999             :     // FIXME: Support other platforms later.
    6000           2 :     const auto &Triple = DAG.getTarget().getTargetTriple();
    6001           4 :     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
    6002             :       return nullptr;
    6003             : 
    6004           2 :     SDLoc DL = getCurSDLoc();
    6005             :     SmallVector<SDValue, 8> Ops;
    6006             : 
    6007             :     // We want to say that we always want the arguments in registers.
    6008           2 :     SDValue LogEntryVal = getValue(I.getArgOperand(0));
    6009           2 :     SDValue StrSizeVal = getValue(I.getArgOperand(1));
    6010           4 :     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    6011           2 :     SDValue Chain = getRoot();
    6012           2 :     Ops.push_back(LogEntryVal);
    6013           2 :     Ops.push_back(StrSizeVal);
    6014           2 :     Ops.push_back(Chain);
    6015             : 
    6016             :     // We need to enforce the calling convention for the callsite, so that
    6017             :     // argument ordering is enforced correctly, and that register allocation can
    6018             :     // see that some registers may be assumed clobbered and have to preserve
    6019             :     // them across calls to the intrinsic.
    6020           4 :     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
    6021           2 :                                            DL, NodeTys, Ops);
    6022             :     SDValue patchableNode = SDValue(MN, 0);
    6023           2 :     DAG.setRoot(patchableNode);
    6024           2 :     setValue(&I, patchableNode);
    6025             :     return nullptr;
    6026             :   }
    6027           0 :   case Intrinsic::experimental_deoptimize:
    6028           0 :     LowerDeoptimizeCall(&I);
    6029           0 :     return nullptr;
    6030             : 
    6031          31 :   case Intrinsic::experimental_vector_reduce_fadd:
    6032             :   case Intrinsic::experimental_vector_reduce_fmul:
    6033             :   case Intrinsic::experimental_vector_reduce_add:
    6034             :   case Intrinsic::experimental_vector_reduce_mul:
    6035             :   case Intrinsic::experimental_vector_reduce_and:
    6036             :   case Intrinsic::experimental_vector_reduce_or:
    6037             :   case Intrinsic::experimental_vector_reduce_xor:
    6038             :   case Intrinsic::experimental_vector_reduce_smax:
    6039             :   case Intrinsic::experimental_vector_reduce_smin:
    6040             :   case Intrinsic::experimental_vector_reduce_umax:
    6041             :   case Intrinsic::experimental_vector_reduce_umin:
    6042             :   case Intrinsic::experimental_vector_reduce_fmax:
    6043             :   case Intrinsic::experimental_vector_reduce_fmin:
    6044          31 :     visitVectorReduce(I, Intrinsic);
    6045          31 :     return nullptr;
    6046             :   }
    6047             : }
    6048             : 
    6049          40 : void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
    6050             :     const ConstrainedFPIntrinsic &FPI) {
    6051          40 :   SDLoc sdl = getCurSDLoc();
    6052             :   unsigned Opcode;
    6053          40 :   switch (FPI.getIntrinsicID()) {
    6054           0 :   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
    6055             :   case Intrinsic::experimental_constrained_fadd:
    6056             :     Opcode = ISD::STRICT_FADD;
    6057             :     break;
    6058           6 :   case Intrinsic::experimental_constrained_fsub:
    6059             :     Opcode = ISD::STRICT_FSUB;
    6060           6 :     break;
    6061           2 :   case Intrinsic::experimental_constrained_fmul:
    6062             :     Opcode = ISD::STRICT_FMUL;
    6063           2 :     break;
    6064           2 :   case Intrinsic::experimental_constrained_fdiv:
    6065             :     Opcode = ISD::STRICT_FDIV;
    6066           2 :     break;
    6067           0 :   case Intrinsic::experimental_constrained_frem:
    6068             :     Opcode = ISD::STRICT_FREM;
    6069           0 :     break;
    6070           4 :   case Intrinsic::experimental_constrained_fma:
    6071             :     Opcode = ISD::STRICT_FMA;
    6072           4 :     break;
    6073           2 :   case Intrinsic::experimental_constrained_sqrt:
    6074             :     Opcode = ISD::STRICT_FSQRT;
    6075           2 :     break;
    6076           2 :   case Intrinsic::experimental_constrained_pow:
    6077             :     Opcode = ISD::STRICT_FPOW;
    6078           2 :     break;
    6079           2 :   case Intrinsic::experimental_constrained_powi:
    6080             :     Opcode = ISD::STRICT_FPOWI;
    6081           2 :     break;
    6082           2 :   case Intrinsic::experimental_constrained_sin:
    6083             :     Opcode = ISD::STRICT_FSIN;
    6084           2 :     break;
    6085           2 :   case Intrinsic::experimental_constrained_cos:
    6086             :     Opcode = ISD::STRICT_FCOS;
    6087           2 :     break;
    6088           2 :   case Intrinsic::experimental_constrained_exp:
    6089             :     Opcode = ISD::STRICT_FEXP;
    6090           2 :     break;
    6091           2 :   case Intrinsic::experimental_constrained_exp2:
    6092             :     Opcode = ISD::STRICT_FEXP2;
    6093           2 :     break;
    6094           2 :   case Intrinsic::experimental_constrained_log:
    6095             :     Opcode = ISD::STRICT_FLOG;
    6096           2 :     break;
    6097           2 :   case Intrinsic::experimental_constrained_log10:
    6098             :     Opcode = ISD::STRICT_FLOG10;
    6099           2 :     break;
    6100           2 :   case Intrinsic::experimental_constrained_log2:
    6101             :     Opcode = ISD::STRICT_FLOG2;
    6102           2 :     break;
    6103           2 :   case Intrinsic::experimental_constrained_rint:
    6104             :     Opcode = ISD::STRICT_FRINT;
    6105           2 :     break;
    6106           2 :   case Intrinsic::experimental_constrained_nearbyint:
    6107             :     Opcode = ISD::STRICT_FNEARBYINT;
    6108           2 :     break;
    6109             :   }
    6110          40 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    6111          40 :   SDValue Chain = getRoot();
    6112             :   SmallVector<EVT, 4> ValueVTs;
    6113          80 :   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
    6114          40 :   ValueVTs.push_back(MVT::Other); // Out chain
    6115             : 
    6116          80 :   SDVTList VTs = DAG.getVTList(ValueVTs);
    6117             :   SDValue Result;
    6118          40 :   if (FPI.isUnaryOp())
    6119          40 :     Result = DAG.getNode(Opcode, sdl, VTs,
    6120          60 :                          { Chain, getValue(FPI.getArgOperand(0)) });
    6121          20 :   else if (FPI.isTernaryOp())
    6122           8 :     Result = DAG.getNode(Opcode, sdl, VTs,
    6123           4 :                          { Chain, getValue(FPI.getArgOperand(0)),
    6124             :                                   getValue(FPI.getArgOperand(1)),
    6125          20 :                                   getValue(FPI.getArgOperand(2)) });
    6126             :   else
    6127          32 :     Result = DAG.getNode(Opcode, sdl, VTs,
    6128          16 :                          { Chain, getValue(FPI.getArgOperand(0)),
    6129          64 :                            getValue(FPI.getArgOperand(1))  });
    6130             : 
    6131             :   assert(Result.getNode()->getNumValues() == 2);
    6132          40 :   SDValue OutChain = Result.getValue(1);
    6133          40 :   DAG.setRoot(OutChain);
    6134             :   SDValue FPResult = Result.getValue(0);
    6135          40 :   setValue(&FPI, FPResult);
    6136          40 : }
    6137             : 
    6138             : std::pair<SDValue, SDValue>
    6139      209928 : SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
    6140             :                                     const BasicBlock *EHPadBB) {
    6141      209928 :   MachineFunction &MF = DAG.getMachineFunction();
    6142      209928 :   MachineModuleInfo &MMI = MF.getMMI();
    6143             :   MCSymbol *BeginLabel = nullptr;
    6144             : 
    6145      209928 :   if (EHPadBB) {
    6146             :     // Insert a label before the invoke call to mark the try range.  This can be
    6147             :     // used to detect deletion of the invoke via the MachineModuleInfo.
    6148       41153 :     BeginLabel = MMI.getContext().createTempSymbol();
    6149             : 
    6150             :     // For SjLj, keep track of which landing pads go with which invokes
    6151             :     // so as to maintain the ordering of pads in the LSDA.
    6152       41153 :     unsigned CallSiteIndex = MMI.getCurrentCallSite();
    6153       41153 :     if (CallSiteIndex) {
    6154             :       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
    6155         522 :       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
    6156             : 
    6157             :       // Now that the call site is handled, stop tracking it.
    6158             :       MMI.setCurrentCallSite(0);
    6159             :     }
    6160             : 
    6161             :     // Both PendingLoads and PendingExports must be flushed here;
    6162             :     // this call might not return.
    6163       41153 :     (void)getRoot();
    6164      123459 :     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
    6165             : 
    6166       41153 :     CLI.setChain(getRoot());
    6167             :   }
    6168      209928 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    6169      209928 :   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
    6170             : 
    6171             :   assert((CLI.IsTailCall || Result.second.getNode()) &&
    6172             :          "Non-null chain expected with non-tail call!");
    6173             :   assert((Result.second.getNode() || !Result.first.getNode()) &&
    6174             :          "Null value expected with tail call!");
    6175             : 
    6176      209922 :   if (!Result.second.getNode()) {
    6177             :     // As a special case, a null chain means that a tail call has been emitted
    6178             :     // and the DAG root is already updated.
    6179        2578 :     HasTailCall = true;
    6180             : 
    6181             :     // Since there's no actual continuation from this block, nothing can be
    6182             :     // relying on us setting vregs for them.
    6183             :     PendingExports.clear();
    6184             :   } else {
    6185      207344 :     DAG.setRoot(Result.second);
    6186             :   }
    6187             : 
    6188      209922 :   if (EHPadBB) {
    6189             :     // Insert a label at the end of the invoke call to mark the try range.  This
    6190             :     // can be used to detect deletion of the invoke via the MachineModuleInfo.
    6191       41153 :     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
    6192      123459 :     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
    6193             : 
    6194             :     // Inform MachineModuleInfo of range.
    6195       41153 :     if (MF.hasEHFunclets()) {
    6196             :       assert(CLI.CS);
    6197         144 :       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
    6198         144 :       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
    6199             :                                 BeginLabel, EndLabel);
    6200             :     } else {
    6201       82018 :       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
    6202             :     }
    6203             :   }
    6204             : 
    6205      209922 :   return Result;
    6206             : }
    6207             : 
    6208      209743 : void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
    6209             :                                       bool isTailCall,
    6210             :                                       const BasicBlock *EHPadBB) {
    6211      209743 :   auto &DL = DAG.getDataLayout();
    6212             :   FunctionType *FTy = CS.getFunctionType();
    6213             :   Type *RetTy = CS.getType();
    6214             : 
    6215             :   TargetLowering::ArgListTy Args;
    6216      209743 :   Args.reserve(CS.arg_size());
    6217             : 
    6218             :   const Value *SwiftErrorVal = nullptr;
    6219      209743 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    6220             : 
    6221             :   // We can't tail call inside a function with a swifterror argument. Lowering
    6222             :   // does not support this yet. It would have to move into the swifterror
    6223             :   // register before the call.
    6224      209743 :   auto *Caller = CS.getInstruction()->getParent()->getParent();
    6225      330745 :   if (TLI.supportSwiftError() &&
    6226      121113 :       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
    6227             :     isTailCall = false;
    6228             : 
    6229      668359 :   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
    6230      668359 :        i != e; ++i) {
    6231             :     TargetLowering::ArgListEntry Entry;
    6232      458616 :     const Value *V = *i;
    6233             : 
    6234             :     // Skip empty types
    6235      458616 :     if (V->getType()->isEmptyTy())
    6236           6 :       continue;
    6237             : 
    6238      458610 :     SDValue ArgNode = getValue(V);
    6239      458610 :     Entry.Node = ArgNode; Entry.Ty = V->getType();
    6240             : 
    6241      917220 :     Entry.setAttributes(&CS, i - CS.arg_begin());
    6242             : 
    6243             :     // Use swifterror virtual register as input to the call.
    6244      458610 :     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
    6245             :       SwiftErrorVal = V;
    6246             :       // We find the virtual register for the actual swifterror argument.
    6247             :       // Instead of using the Value, we use the virtual register instead.
    6248         330 :       Entry.Node = DAG.getRegister(FuncInfo
    6249         110 :                                        .getOrCreateSwiftErrorVRegUseAt(
    6250         110 :                                            CS.getInstruction(), FuncInfo.MBB, V)
    6251             :                                        .first,
    6252         220 :                                    EVT(TLI.getPointerTy(DL)));
    6253             :     }
    6254             : 
    6255      458610 :     Args.push_back(Entry);
    6256             : 
    6257             :     // If we have an explicit sret argument that is an Instruction, (i.e., it
    6258             :     // might point to function-local memory), we can't meaningfully tail-call.
    6259      465111 :     if (Entry.IsSRet && isa<Instruction>(V))
    6260             :       isTailCall = false;
    6261             :   }
    6262             : 
    6263             :   // Check if target-independent constraints permit a tail call here.
    6264             :   // Target-dependent constraints are checked within TLI->LowerCallTo.
    6265      209743 :   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
    6266             :     isTailCall = false;
    6267             : 
    6268             :   // Disable tail calls if there is an swifterror argument. Targets have not
    6269             :   // been updated to support tail calls.
    6270      209743 :   if (TLI.supportSwiftError() && SwiftErrorVal)
    6271             :     isTailCall = false;
    6272             : 
    6273      419480 :   TargetLowering::CallLoweringInfo CLI(DAG);
    6274      419486 :   CLI.setDebugLoc(getCurSDLoc())
    6275      209743 :       .setChain(getRoot())
    6276      209743 :       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
    6277             :       .setTailCall(isTailCall)
    6278      209743 :       .setConvergent(CS.isConvergent());
    6279      209743 :   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
    6280             : 
    6281      209737 :   if (Result.first.getNode()) {
    6282             :     const Instruction *Inst = CS.getInstruction();
    6283       35610 :     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
    6284             :     setValue(Inst, Result.first);
    6285             :   }
    6286             : 
    6287             :   // The last element of CLI.InVals has the SDValue for swifterror return.
    6288             :   // Here we copy it to a virtual register and update SwiftErrorMap for
    6289             :   // book-keeping.
    6290      209737 :   if (SwiftErrorVal && TLI.supportSwiftError()) {
    6291             :     // Get the last element of InVals.
    6292         110 :     SDValue Src = CLI.InVals.back();
    6293             :     unsigned VReg; bool CreatedVReg;
    6294             :     std::tie(VReg, CreatedVReg) =
    6295         330 :         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
    6296         110 :     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
    6297             :     // We update the virtual register for the actual swifterror argument.
    6298         110 :     if (CreatedVReg)
    6299          67 :       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
    6300         110 :     DAG.setRoot(CopyNode);
    6301             :   }
    6302      209737 : }
    6303             : 
    6304          56 : static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
    6305             :                              SelectionDAGBuilder &Builder) {
    6306             :   // Check to see if this load can be trivially constant folded, e.g. if the
    6307             :   // input is from a string literal.
    6308             :   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
    6309             :     // Cast pointer to the type we really want to load.
    6310             :     Type *LoadTy =
    6311          14 :         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
    6312          14 :     if (LoadVT.isVector())
    6313           4 :       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
    6314             : 
    6315          14 :     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
    6316             :                                          PointerType::getUnqual(LoadTy));
    6317             : 
    6318          14 :     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
    6319          14 :             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
    6320          14 :       return Builder.getValue(LoadCst);
    6321             :   }
    6322             : 
    6323             :   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
    6324             :   // still constant memory, the input chain can be the entry node.
    6325          42 :   SDValue Root;
    6326             :   bool ConstantMemory = false;
    6327             : 
    6328             :   // Do not serialize (non-volatile) loads of constant memory with anything.
    6329          84 :   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
    6330           0 :     Root = Builder.DAG.getEntryNode();
    6331             :     ConstantMemory = true;
    6332             :   } else {
    6333             :     // Do not serialize non-volatile loads against each other.
    6334          42 :     Root = Builder.DAG.getRoot();
    6335             :   }
    6336             : 
    6337          42 :   SDValue Ptr = Builder.getValue(PtrVal);
    6338         126 :   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
    6339             :                                         Ptr, MachinePointerInfo(PtrVal),
    6340          84 :                                         /* Alignment = */ 1);
    6341             : 
    6342          42 :   if (!ConstantMemory)
    6343          42 :     Builder.PendingLoads.push_back(LoadVal.getValue(1));
    6344          42 :   return LoadVal;
    6345             : }
    6346             : 
    6347             : /// Record the value for an instruction that produces an integer result,
    6348             : /// converting the type where necessary.
    6349          46 : void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
    6350             :                                                   SDValue Value,
    6351             :                                                   bool IsSigned) {
    6352          46 :   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    6353          92 :                                                     I.getType(), true);
    6354          46 :   if (IsSigned)
    6355          48 :     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
    6356             :   else
    6357          90 :     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
    6358          46 :   setValue(&I, Value);
    6359          46 : }
    6360             : 
    6361             : /// See if we can lower a memcmp call into an optimized form. If so, return
    6362             : /// true and lower it. Otherwise return false, and it will be lowered like a
    6363             : /// normal call.
    6364             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6365             : /// correct prototype.
    6366         264 : bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
    6367         528 :   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
    6368             :   const Value *Size = I.getArgOperand(2);
    6369             :   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
    6370         224 :   if (CSize && CSize->getZExtValue() == 0) {
    6371          13 :     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
    6372          26 :                                                           I.getType(), true);
    6373          39 :     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
    6374             :     return true;
    6375             :   }
    6376             : 
    6377         251 :   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
    6378             :   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
    6379         753 :       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
    6380        1004 :       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
    6381         251 :   if (Res.first.getNode()) {
    6382          12 :     processIntegerCallValue(I, Res.first, true);
    6383          12 :     PendingLoads.push_back(Res.second);
    6384          12 :     return true;
    6385             :   }
    6386             : 
    6387             :   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
    6388             :   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
    6389         239 :   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
    6390             :     return false;
    6391             : 
    6392             :   // If the target has a fast compare for the given size, it will return a
    6393             :   // preferred load type for that size. Require that the load VT is legal and
    6394             :   // that the target supports unaligned loads of that type. Otherwise, return
    6395             :   // INVALID.
    6396          36 :   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
    6397          36 :     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    6398          36 :     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
    6399          36 :     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
    6400             :       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
    6401             :       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
    6402             :       // TODO: Check alignment of src and dest ptrs.
    6403          12 :       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
    6404          12 :       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
    6405          12 :       if (!TLI.isTypeLegal(LVT) ||
    6406          48 :           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
    6407          36 :           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
    6408             :         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
    6409             :     }
    6410             : 
    6411          36 :     return LVT;
    6412         111 :   };
    6413             : 
    6414             :   // This turns into unaligned loads. We only do this if the target natively
    6415             :   // supports the MVT we'll be loading or if it is small enough (<= 4) that
    6416             :   // we'll only produce a small number of byte loads.
    6417         111 :   MVT LoadVT;
    6418         111 :   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
    6419         111 :   switch (NumBitsToCompare) {
    6420             :   default:
    6421             :     return false;
    6422             :   case 16:
    6423           8 :     LoadVT = MVT::i16;
    6424           8 :     break;
    6425             :   case 32:
    6426           8 :     LoadVT = MVT::i32;
    6427           8 :     break;
    6428          36 :   case 64:
    6429             :   case 128:
    6430             :   case 256:
    6431          36 :     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
    6432          36 :     break;
    6433             :   }
    6434             : 
    6435          52 :   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
    6436             :     return false;
    6437             : 
    6438          28 :   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
    6439          28 :   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
    6440             : 
    6441             :   // Bitcast to a wide integer type if the loads are vectors.
    6442          28 :   if (LoadVT.isVector()) {
    6443           8 :     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
    6444           8 :     LoadL = DAG.getBitcast(CmpVT, LoadL);
    6445           8 :     LoadR = DAG.getBitcast(CmpVT, LoadR);
    6446             :   }
    6447             : 
    6448         112 :   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
    6449          28 :   processIntegerCallValue(I, Cmp, false);
    6450          28 :   return true;
    6451             : }
    6452             : 
    6453             : /// See if we can lower a memchr call into an optimized form. If so, return
    6454             : /// true and lower it. Otherwise return false, and it will be lowered like a
    6455             : /// normal call.
    6456             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6457             : /// correct prototype.
    6458           7 : bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
    6459             :   const Value *Src = I.getArgOperand(0);
    6460             :   const Value *Char = I.getArgOperand(1);
    6461             :   const Value *Length = I.getArgOperand(2);
    6462             : 
    6463           7 :   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
    6464             :   std::pair<SDValue, SDValue> Res =
    6465          21 :     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
    6466             :                                 getValue(Src), getValue(Char), getValue(Length),
    6467          28 :                                 MachinePointerInfo(Src));
    6468           7 :   if (Res.first.getNode()) {
    6469           5 :     setValue(&I, Res.first);
    6470           5 :     PendingLoads.push_back(Res.second);
    6471           5 :     return true;
    6472             :   }
    6473             : 
    6474             :   return false;
    6475             : }
    6476             : 
    6477             : /// See if we can lower a mempcpy call into an optimized form. If so, return
    6478             : /// true and lower it. Otherwise return false, and it will be lowered like a
    6479             : /// normal call.
    6480             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6481             : /// correct prototype.
    6482           2 : bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
    6483           2 :   SDValue Dst = getValue(I.getArgOperand(0));
    6484           2 :   SDValue Src = getValue(I.getArgOperand(1));
    6485           2 :   SDValue Size = getValue(I.getArgOperand(2));
    6486             : 
    6487           2 :   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
    6488           2 :   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
    6489           2 :   unsigned Align = std::min(DstAlign, SrcAlign);
    6490           2 :   if (Align == 0) // Alignment of one or both could not be inferred.
    6491             :     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
    6492             : 
    6493             :   bool isVol = false;
    6494           2 :   SDLoc sdl = getCurSDLoc();
    6495             : 
    6496             :   // In the mempcpy context we need to pass in a false value for isTailCall
    6497             :   // because the return pointer needs to be adjusted by the size of
    6498             :   // the copied memory.
    6499           2 :   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
    6500             :                              false, /*isTailCall=*/false,
    6501             :                              MachinePointerInfo(I.getArgOperand(0)),
    6502           2 :                              MachinePointerInfo(I.getArgOperand(1)));
    6503             :   assert(MC.getNode() != nullptr &&
    6504             :          "** memcpy should not be lowered as TailCall in mempcpy context **");
    6505           2 :   DAG.setRoot(MC);
    6506             : 
    6507             :   // Check if Size needs to be truncated or extended.
    6508           4 :   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
    6509             : 
    6510             :   // Adjust return pointer to point just past the last dst byte.
    6511           2 :   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
    6512           2 :                                     Dst, Size);
    6513           2 :   setValue(&I, DstPlusSize);
    6514           2 :   return true;
    6515             : }
    6516             : 
    6517             : /// See if we can lower a strcpy call into an optimized form.  If so, return
    6518             : /// true and lower it, otherwise return false and it will be lowered like a
    6519             : /// normal call.
    6520             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6521             : /// correct prototype.
    6522         119 : bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
    6523             :   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
    6524             : 
    6525         119 :   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
    6526             :   std::pair<SDValue, SDValue> Res =
    6527         238 :     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
    6528             :                                 getValue(Arg0), getValue(Arg1),
    6529             :                                 MachinePointerInfo(Arg0),
    6530         476 :                                 MachinePointerInfo(Arg1), isStpcpy);
    6531         119 :   if (Res.first.getNode()) {
    6532           3 :     setValue(&I, Res.first);
    6533           3 :     DAG.setRoot(Res.second);
    6534           3 :     return true;
    6535             :   }
    6536             : 
    6537             :   return false;
    6538             : }
    6539             : 
    6540             : /// See if we can lower a strcmp call into an optimized form.  If so, return
    6541             : /// true and lower it, otherwise return false and it will be lowered like a
    6542             : /// normal call.
    6543             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6544             : /// correct prototype.
    6545          50 : bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
    6546             :   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
    6547             : 
    6548          50 :   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
    6549             :   std::pair<SDValue, SDValue> Res =
    6550         150 :     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
    6551             :                                 getValue(Arg0), getValue(Arg1),
    6552             :                                 MachinePointerInfo(Arg0),
    6553         200 :                                 MachinePointerInfo(Arg1));
    6554          50 :   if (Res.first.getNode()) {
    6555           4 :     processIntegerCallValue(I, Res.first, true);
    6556           4 :     PendingLoads.push_back(Res.second);
    6557           4 :     return true;
    6558             :   }
    6559             : 
    6560             :   return false;
    6561             : }
    6562             : 
    6563             : /// See if we can lower a strlen call into an optimized form.  If so, return
    6564             : /// true and lower it, otherwise return false and it will be lowered like a
    6565             : /// normal call.
    6566             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6567             : /// correct prototype.
    6568         234 : bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
    6569             :   const Value *Arg0 = I.getArgOperand(0);
    6570             : 
    6571         234 :   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
    6572             :   std::pair<SDValue, SDValue> Res =
    6573         702 :     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
    6574         936 :                                 getValue(Arg0), MachinePointerInfo(Arg0));
    6575         234 :   if (Res.first.getNode()) {
    6576           1 :     processIntegerCallValue(I, Res.first, false);
    6577           1 :     PendingLoads.push_back(Res.second);
    6578           1 :     return true;
    6579             :   }
    6580             : 
    6581             :   return false;
    6582             : }
    6583             : 
    6584             : /// See if we can lower a strnlen call into an optimized form.  If so, return
    6585             : /// true and lower it, otherwise return false and it will be lowered like a
    6586             : /// normal call.
    6587             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6588             : /// correct prototype.
    6589           2 : bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
    6590             :   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
    6591             : 
    6592           2 :   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
    6593             :   std::pair<SDValue, SDValue> Res =
    6594           6 :     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
    6595             :                                  getValue(Arg0), getValue(Arg1),
    6596           8 :                                  MachinePointerInfo(Arg0));
    6597           2 :   if (Res.first.getNode()) {
    6598           1 :     processIntegerCallValue(I, Res.first, false);
    6599           1 :     PendingLoads.push_back(Res.second);
    6600           1 :     return true;
    6601             :   }
    6602             : 
    6603             :   return false;
    6604             : }
    6605             : 
    6606             : /// See if we can lower a unary floating-point operation into an SDNode with
    6607             : /// the specified Opcode.  If so, return true and lower it, otherwise return
    6608             : /// false and it will be lowered like a normal call.
    6609             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6610             : /// correct prototype.
    6611         709 : bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
    6612             :                                               unsigned Opcode) {
    6613             :   // We already checked this call's prototype; verify it doesn't modify errno.
    6614         709 :   if (!I.onlyReadsMemory())
    6615             :     return false;
    6616             : 
    6617         526 :   SDValue Tmp = getValue(I.getArgOperand(0));
    6618        2630 :   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
    6619         526 :   return true;
    6620             : }
    6621             : 
    6622             : /// See if we can lower a binary floating-point operation into an SDNode with
    6623             : /// the specified Opcode. If so, return true and lower it. Otherwise return
    6624             : /// false, and it will be lowered like a normal call.
    6625             : /// The caller already checked that \p I calls the appropriate LibFunc with a
    6626             : /// correct prototype.
    6627          38 : bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
    6628             :                                                unsigned Opcode) {
    6629             :   // We already checked this call's prototype; verify it doesn't modify errno.
    6630          38 :   if (!I.onlyReadsMemory())
    6631             :     return false;
    6632             : 
    6633          38 :   SDValue Tmp0 = getValue(I.getArgOperand(0));
    6634          38 :   SDValue Tmp1 = getValue(I.getArgOperand(1));
    6635          76 :   EVT VT = Tmp0.getValueType();
    6636         152 :   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
    6637          38 :   return true;
    6638             : }
    6639             : 
    6640      351509 : void SelectionDAGBuilder::visitCall(const CallInst &I) {
    6641             :   // Handle inline assembly differently.
    6642      351509 :   if (isa<InlineAsm>(I.getCalledValue())) {
    6643       12044 :     visitInlineAsm(&I);
    6644      194951 :     return;
    6645             :   }
    6646             : 
    6647      339465 :   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
    6648      339465 :   computeUsesVAFloatArgument(I, MMI);
    6649             : 
    6650             :   const char *RenameFn = nullptr;
    6651             :   if (Function *F = I.getCalledFunction()) {
    6652      337311 :     if (F->isDeclaration()) {
    6653      261911 :       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
    6654       14263 :         if (unsigned IID = II->getIntrinsicID(F)) {
    6655        1003 :           RenameFn = visitIntrinsicCall(I, IID);
    6656        1003 :           if (!RenameFn)
    6657      170863 :             return;
    6658             :         }
    6659             :       }
    6660      260908 :       if (Intrinsic::ID IID = F->getIntrinsicID()) {
    6661      169128 :         RenameFn = visitIntrinsicCall(I, IID);
    6662      169128 :         if (!RenameFn)
    6663             :           return;
    6664             :       }
    6665             :     }
    6666             : 
    6667             :     // Check for well-known libc/libm calls.  If the function is internal, it
    6668             :     // can't be a library call.  Don't do the check if marked as nobuiltin for
    6669             :     // some reason or the call site requires strict floating point semantics.
    6670             :     LibFunc Func;
    6671      433711 :     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
    6672      390704 :         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
    6673        7806 :         LibInfo->hasOptimizedCodeGen(Func)) {
    6674        1531 :       switch (Func) {
    6675             :       default: break;
    6676         106 :       case LibFunc_copysign:
    6677             :       case LibFunc_copysignf:
    6678             :       case LibFunc_copysignl:
    6679             :         // We already checked this call's prototype; verify it doesn't modify
    6680             :         // errno.
    6681         106 :         if (I.onlyReadsMemory()) {
    6682         101 :           SDValue LHS = getValue(I.getArgOperand(0));
    6683         101 :           SDValue RHS = getValue(I.getArgOperand(1));
    6684         505 :           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
    6685             :                                    LHS.getValueType(), LHS, RHS));
    6686             :           return;
    6687           5 :         }
    6688             :         break;
    6689          77 :       case LibFunc_fabs:
    6690             :       case LibFunc_fabsf:
    6691             :       case LibFunc_fabsl:
    6692          77 :         if (visitUnaryFloatCall(I, ISD::FABS))
    6693             :           return;
    6694             :         break;
    6695          18 :       case LibFunc_fmin:
    6696             :       case LibFunc_fminf:
    6697             :       case LibFunc_fminl:
    6698          18 :         if (visitBinaryFloatCall(I, ISD::FMINNUM))
    6699             :           return;
    6700             :         break;
    6701          20 :       case LibFunc_fmax:
    6702             :       case LibFunc_fmaxf:
    6703             :       case LibFunc_fmaxl:
    6704          20 :         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
    6705             :           return;
    6706             :         break;
    6707         146 :       case LibFunc_sin:
    6708             :       case LibFunc_sinf:
    6709             :       case LibFunc_sinl:
    6710         146 :         if (visitUnaryFloatCall(I, ISD::FSIN))
    6711             :           return;
    6712             :         break;
    6713         112 :       case LibFunc_cos:
    6714             :       case LibFunc_cosf:
    6715             :       case LibFunc_cosl:
    6716         112 :         if (visitUnaryFloatCall(I, ISD::FCOS))
    6717             :           return;
    6718             :         break;
    6719         101 :       case LibFunc_sqrt:
    6720             :       case LibFunc_sqrtf:
    6721             :       case LibFunc_sqrtl:
    6722             :       case LibFunc_sqrt_finite:
    6723             :       case LibFunc_sqrtf_finite:
    6724             :       case LibFunc_sqrtl_finite:
    6725         101 :         if (visitUnaryFloatCall(I, ISD::FSQRT))
    6726             :           return;
    6727             :         break;
    6728          68 :       case LibFunc_floor:
    6729             :       case LibFunc_floorf:
    6730             :       case LibFunc_floorl:
    6731          68 :         if (visitUnaryFloatCall(I, ISD::FFLOOR))
    6732             :           return;
    6733             :         break;
    6734          25 :       case LibFunc_nearbyint:
    6735             :       case LibFunc_nearbyintf:
    6736             :       case LibFunc_nearbyintl:
    6737          25 :         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
    6738             :           return;
    6739             :         break;
    6740          56 :       case LibFunc_ceil:
    6741             :       case LibFunc_ceilf:
    6742             :       case LibFunc_ceill:
    6743          56 :         if (visitUnaryFloatCall(I, ISD::FCEIL))
    6744             :           return;
    6745             :         break;
    6746          25 :       case LibFunc_rint:
    6747             :       case LibFunc_rintf:
    6748             :       case LibFunc_rintl:
    6749          25 :         if (visitUnaryFloatCall(I, ISD::FRINT))
    6750             :           return;
    6751             :         break;
    6752          39 :       case LibFunc_round:
    6753             :       case LibFunc_roundf:
    6754             :       case LibFunc_roundl:
    6755          39 :         if (visitUnaryFloatCall(I, ISD::FROUND))
    6756             :           return;
    6757             :         break;
    6758          40 :       case LibFunc_trunc:
    6759             :       case LibFunc_truncf:
    6760             :       case LibFunc_truncl:
    6761          40 :         if (visitUnaryFloatCall(I, ISD::FTRUNC))
    6762             :           return;
    6763             :         break;
    6764          10 :       case LibFunc_log2:
    6765             :       case LibFunc_log2f:
    6766             :       case LibFunc_log2l:
    6767          10 :         if (visitUnaryFloatCall(I, ISD::FLOG2))
    6768             :           return;
    6769             :         break;
    6770          10 :       case LibFunc_exp2:
    6771             :       case LibFunc_exp2f:
    6772             :       case LibFunc_exp2l:
    6773          10 :         if (visitUnaryFloatCall(I, ISD::FEXP2))
    6774             :           return;
    6775             :         break;
    6776         264 :       case LibFunc_memcmp:
    6777         264 :         if (visitMemCmpCall(I))
    6778             :           return;
    6779             :         break;
    6780           2 :       case LibFunc_mempcpy:
    6781           2 :         if (visitMemPCpyCall(I))
    6782             :           return;
    6783             :         break;
    6784           7 :       case LibFunc_memchr:
    6785           7 :         if (visitMemChrCall(I))
    6786             :           return;
    6787             :         break;
    6788         118 :       case LibFunc_strcpy:
    6789         118 :         if (visitStrCpyCall(I, false))
    6790             :           return;
    6791             :         break;
    6792           1 :       case LibFunc_stpcpy:
    6793           1 :         if (visitStrCpyCall(I, true))
    6794             :           return;
    6795             :         break;
    6796          50 :       case LibFunc_strcmp:
    6797          50 :         if (visitStrCmpCall(I))
    6798             :           return;
    6799             :         break;
    6800         234 :       case LibFunc_strlen:
    6801         234 :         if (visitStrLenCall(I))
    6802             :           return;
    6803             :         break;
    6804           2 :       case LibFunc_strnlen:
    6805           2 :         if (visitStrNLenCall(I))
    6806             :           return;
    6807             :         break;
    6808             :       }
    6809             :     }
    6810             :   }
    6811             : 
    6812      168602 :   SDValue Callee;
    6813      168602 :   if (!RenameFn)
    6814      168600 :     Callee = getValue(I.getCalledValue());
    6815             :   else
    6816           4 :     Callee = DAG.getExternalSymbol(
    6817             :         RenameFn,
    6818           4 :         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
    6819             : 
    6820             :   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
    6821             :   // have to do anything here to lower funclet bundles.
    6822             :   assert(!I.hasOperandBundlesOtherThan(
    6823             :              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
    6824             :          "Cannot lower calls with arbitrary operand bundles!");
    6825             : 
    6826      168602 :   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
    6827           3 :     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
    6828             :   else
    6829             :     // Check if we can potentially perform a tail call. More detailed checking
    6830             :     // is be done within LowerCallTo, after more information about the call is
    6831             :     // known.
    6832      337198 :     LowerCallTo(&I, Callee, I.isTailCall());
    6833             : }
    6834             : 
    6835             : namespace {
    6836             : 
    6837             : /// AsmOperandInfo - This contains information for each constraint that we are
    6838             : /// lowering.
    6839      252672 : class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
    6840             : public:
    6841             :   /// CallOperand - If this is the result output operand or a clobber
    6842             :   /// this is null, otherwise it is the incoming operand to the CallInst.
    6843             :   /// This gets modified as the asm is processed.
    6844             :   SDValue CallOperand;
    6845             : 
    6846             :   /// AssignedRegs - If this is a register or register class operand, this
    6847             :   /// contains the set of register corresponding to the operand.
    6848             :   RegsForValue AssignedRegs;
    6849             : 
    6850       65568 :   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
    6851       65568 :     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
    6852       65568 :   }
    6853             : 
    6854             :   /// Whether or not this operand accesses memory
    6855       61454 :   bool hasMemory(const TargetLowering &TLI) const {
    6856             :     // Indirect operand accesses access memory.
    6857       61454 :     if (isIndirect)
    6858             :       return true;
    6859             : 
    6860       59018 :     for (const auto &Code : Codes)
    6861      208612 :       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
    6862             :         return true;
    6863             : 
    6864             :     return false;
    6865             :   }
    6866             : 
    6867             :   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
    6868             :   /// corresponds to.  If there is no Value* for this operand, it returns
    6869             :   /// MVT::Other.
    6870       10645 :   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
    6871             :                            const DataLayout &DL) const {
    6872       10645 :     if (!CallOperandVal) return MVT::Other;
    6873             : 
    6874       10645 :     if (isa<BasicBlock>(CallOperandVal))
    6875           2 :       return TLI.getPointerTy(DL);
    6876             : 
    6877       10643 :     llvm::Type *OpTy = CallOperandVal->getType();
    6878             : 
    6879             :     // FIXME: code duplicated from TargetLowering::ParseConstraints().
    6880             :     // If this is an indirect operand, the operand is a pointer to the
    6881             :     // accessed type.
    6882       10643 :     if (isIndirect) {
    6883             :       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
    6884             :       if (!PtrTy)
    6885           0 :         report_fatal_error("Indirect operand for inline asm not a pointer!");
    6886        3036 :       OpTy = PtrTy->getElementType();
    6887             :     }
    6888             : 
    6889             :     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
    6890             :     if (StructType *STy = dyn_cast<StructType>(OpTy))
    6891          12 :       if (STy->getNumElements() == 1)
    6892           8 :         OpTy = STy->getElementType(0);
    6893             : 
    6894             :     // If OpTy is not a single value, it may be a struct/union that we
    6895             :     // can tile with integers.
    6896       10643 :     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
    6897          15 :       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
    6898          15 :       switch (BitSize) {
    6899             :       default: break;
    6900           7 :       case 1:
    6901             :       case 8:
    6902             :       case 16:
    6903             :       case 32:
    6904             :       case 64:
    6905             :       case 128:
    6906           7 :         OpTy = IntegerType::get(Context, BitSize);
    6907             :         break;
    6908             :       }
    6909             :     }
    6910             : 
    6911       10643 :     return TLI.getValueType(DL, OpTy, true);
    6912             :   }
    6913             : };
    6914             : 
    6915             : using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
    6916             : 
    6917             : } // end anonymous namespace
    6918             : 
    6919             : /// Make sure that the output operand \p OpInfo and its corresponding input
    6920             : /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
    6921             : /// out).
    6922         265 : static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
    6923             :                                SDISelAsmOperandInfo &MatchingOpInfo,
    6924             :                                SelectionDAG &DAG) {
    6925         265 :   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
    6926         252 :     return;
    6927             : 
    6928          26 :   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
    6929          13 :   const auto &TLI = DAG.getTargetLoweringInfo();
    6930             : 
    6931             :   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
    6932             :       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
    6933          26 :                                        OpInfo.ConstraintVT);
    6934             :   std::pair<unsigned, const TargetRegisterClass *> InputRC =
    6935             :       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
    6936          26 :                                        MatchingOpInfo.ConstraintVT);
    6937             :   if ((OpInfo.ConstraintVT.isInteger() !=
    6938          26 :        MatchingOpInfo.ConstraintVT.isInteger()) ||
    6939          13 :       (MatchRC.second != InputRC.second)) {
    6940             :     // FIXME: error out in a more elegant fashion
    6941           0 :     report_fatal_error("Unsupported asm: input constraint"
    6942             :                        " with a matching output constraint of"
    6943             :                        " incompatible type!");
    6944             :   }
    6945          13 :   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
    6946             : }
    6947             : 
    6948             : /// Get a direct memory input to behave well as an indirect operand.
    6949             : /// This may introduce stores, hence the need for a \p Chain.
    6950             : /// \return The (possibly updated) chain.
    6951         137 : static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
    6952             :                                         SDISelAsmOperandInfo &OpInfo,
    6953             :                                         SelectionDAG &DAG) {
    6954             :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    6955             : 
    6956             :   // If we don't have an indirect input, put it in the constpool if we can,
    6957             :   // otherwise spill it to a stack slot.
    6958             :   // TODO: This isn't quite right. We need to handle these according to
    6959             :   // the addressing mode that the constraint wants. Also, this may take
    6960             :   // an additional register for the computation and we don't want that
    6961             :   // either.
    6962             : 
    6963             :   // If the operand is a float, integer, or vector constant, spill to a
    6964             :   // constant pool entry to get its address.
    6965         137 :   const Value *OpVal = OpInfo.CallOperandVal;
    6966         133 :   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
    6967         264 :       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
    6968          10 :     OpInfo.CallOperand = DAG.getConstantPool(
    6969          20 :         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
    6970          10 :     return Chain;
    6971             :   }
    6972             : 
    6973             :   // Otherwise, create a stack slot and emit a store to it before the asm.
    6974         127 :   Type *Ty = OpVal->getType();
    6975         127 :   auto &DL = DAG.getDataLayout();
    6976         127 :   uint64_t TySize = DL.getTypeAllocSize(Ty);
    6977         127 :   unsigned Align = DL.getPrefTypeAlignment(Ty);
    6978         127 :   MachineFunction &MF = DAG.getMachineFunction();
    6979         127 :   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
    6980         254 :   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
    6981         127 :   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
    6982         254 :                        MachinePointerInfo::getFixedStack(MF, SSFI));
    6983         127 :   OpInfo.CallOperand = StackSlot;
    6984             : 
    6985         127 :   return Chain;
    6986             : }
    6987             : 
    6988             : /// GetRegistersForValue - Assign registers (virtual or physical) for the
    6989             : /// specified operand.  We prefer to assign virtual registers, to allow the
    6990             : /// register allocator to handle the assignment process.  However, if the asm
    6991             : /// uses features that we can't model on machineinstrs, we have SDISel do the
    6992             : /// allocation.  This produces generally horrible, but correct, code.
    6993             : ///
    6994             : ///   OpInfo describes the operand.
    6995       60195 : static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
    6996             :                                  const SDLoc &DL,
    6997             :                                  SDISelAsmOperandInfo &OpInfo) {
    6998       60195 :   LLVMContext &Context = *DAG.getContext();
    6999             : 
    7000       60195 :   MachineFunction &MF = DAG.getMachineFunction();
    7001             :   SmallVector<unsigned, 4> Regs;
    7002       60195 :   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
    7003             : 
    7004             :   // If this is a constraint for a single physreg, or a constraint for a
    7005             :   // register class, find it.
    7006             :   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
    7007             :       TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode,
    7008      120390 :                                        OpInfo.ConstraintVT);
    7009             : 
    7010             :   unsigned NumRegs = 1;
    7011       60195 :   if (OpInfo.ConstraintVT != MVT::Other) {
    7012             :     // If this is a FP input in an integer register (or visa versa) insert a bit
    7013             :     // cast of the input value.  More generally, handle any case where the input
    7014             :     // value disagrees with the register class we plan to stick this in.
    7015       15282 :     if (OpInfo.Type == InlineAsm::isInput && PhysReg.second &&
    7016             :         !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
    7017             :       // Try to convert to the first EVT that the reg class contains.  If the
    7018             :       // types are identical size, use a bitcast to convert (e.g. two differing
    7019             :       // vector types).
    7020         192 :       MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
    7021         192 :       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
    7022          69 :         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
    7023          69 :                                          RegVT, OpInfo.CallOperand);
    7024          69 :         OpInfo.ConstraintVT = RegVT;
    7025         237 :       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
    7026             :         // If the input is a FP value and we want it in FP registers, do a
    7027             :         // bitcast to the corresponding integer type.  This turns an f64 value
    7028             :         // into i64, which can be passed with two i32 values on a 32-bit
    7029             :         // machine.
    7030           1 :         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
    7031           1 :         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
    7032           1 :                                          RegVT, OpInfo.CallOperand);
    7033           1 :         OpInfo.ConstraintVT = RegVT;
    7034             :       }
    7035             :     }
    7036             : 
    7037       19156 :     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
    7038             :   }
    7039             : 
    7040             :   MVT RegVT;
    7041             :   EVT ValueVT = OpInfo.ConstraintVT;
    7042             : 
    7043             :   // If this is a constraint for a specific physical register, like {r17},
    7044             :   // assign it now.
    7045       60195 :   if (unsigned AssignedReg = PhysReg.first) {
    7046             :     const TargetRegisterClass *RC = PhysReg.second;
    7047       49250 :     if (OpInfo.ConstraintVT == MVT::Other)
    7048       47986 :       ValueVT = *TRI.legalclasstypes_begin(*RC);
    7049             : 
    7050             :     // Get the actual register value type.  This is important, because the user
    7051             :     // may have asked for (e.g.) the AX register in i32 type.  We need to
    7052             :     // remember that AX is actually i16 to get the right extension.
    7053       49250 :     RegVT = *TRI.legalclasstypes_begin(*RC);
    7054             : 
    7055             :     // This is a explicit reference to a physical register.
    7056       49250 :     Regs.push_back(AssignedReg);
    7057             : 
    7058             :     // If this is an expanded reference, add the rest of the regs to Regs.
    7059       49250 :     if (NumRegs != 1) {
    7060           8 :       TargetRegisterClass::iterator I = RC->begin();
    7061          30 :       for (; *I != AssignedReg; ++I)
    7062             :         assert(I != RC->end() && "Didn't find reg!");
    7063             : 
    7064             :       // Already added the first reg.
    7065           8 :       --NumRegs; ++I;
    7066          24 :       for (; NumRegs; --NumRegs, ++I) {
    7067             :         assert(I != RC->end() && "Ran out of registers to allocate!");
    7068           8 :         Regs.push_back(*I);
    7069             :       }
    7070             :     }
    7071             : 
    7072       49250 :     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
    7073       49250 :     return;
    7074             :   }
    7075             : 
    7076             :   // Otherwise, if this was a reference to an LLVM register class, create vregs
    7077             :   // for this reference.
    7078       10945 :   if (const TargetRegisterClass *RC = PhysReg.second) {
    7079        8258 :     RegVT = *TRI.legalclasstypes_begin(*RC);
    7080        8258 :     if (OpInfo.ConstraintVT == MVT::Other)
    7081           1 :       ValueVT = RegVT;
    7082             : 
    7083             :     // Create the appropriate number of virtual registers.
    7084        8258 :     MachineRegisterInfo &RegInfo = MF.getRegInfo();
    7085       25028 :     for (; NumRegs; --NumRegs)
    7086        8385 :       Regs.push_back(RegInfo.createVirtualRegister(RC));
    7087             : 
    7088        8258 :     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
    7089        8258 :     return;
    7090             :   }
    7091             : 
    7092             :   // Otherwise, we couldn't allocate enough registers for this.
    7093             : }
    7094             : 
    7095             : static unsigned
    7096             : findMatchingInlineAsmOperand(unsigned OperandNo,
    7097             :                              const std::vector<SDValue> &AsmNodeOperands) {
    7098             :   // Scan until we find the definition we already emitted of this operand.
    7099             :   unsigned CurOp = InlineAsm::Op_FirstOperand;
    7100        5252 :   for (; OperandNo; --OperandNo) {
    7101             :     // Advance to the next operand.
    7102             :     unsigned OpFlag =
    7103        7485 :         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
    7104             :     assert((InlineAsm::isRegDefKind(OpFlag) ||
    7105             :             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
    7106             :             InlineAsm::isMemKind(OpFlag)) &&
    7107             :            "Skipped past definitions?");
    7108        2495 :     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
    7109             :   }
    7110             :   return CurOp;
    7111             : }
    7112             : 
    7113             : /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
    7114             : /// \return true if it has succeeded, false otherwise
    7115         261 : static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
    7116             :                               MVT RegVT, SelectionDAG &DAG) {
    7117         261 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    7118         261 :   MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
    7119         811 :   for (unsigned i = 0, e = NumRegs; i != e; ++i) {
    7120         275 :     if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
    7121         275 :       Regs.push_back(RegInfo.createVirtualRegister(RC));
    7122             :     else
    7123             :       return false;
    7124             :   }
    7125             :   return true;
    7126             : }
    7127             : 
    7128             : namespace {
    7129             : 
    7130             : class ExtraFlags {
    7131             :   unsigned Flags = 0;
    7132             : 
    7133             : public:
    7134       12045 :   explicit ExtraFlags(ImmutableCallSite CS) {
    7135             :     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
    7136       12045 :     if (IA->hasSideEffects())
    7137        9620 :       Flags |= InlineAsm::Extra_HasSideEffects;
    7138       12045 :     if (IA->isAlignStack())
    7139          21 :       Flags |= InlineAsm::Extra_IsAlignStack;
    7140       12045 :     if (CS.isConvergent())
    7141           1 :       Flags |= InlineAsm::Extra_IsConvergent;
    7142       12045 :     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
    7143       12045 :   }
    7144             : 
    7145             :   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
    7146             :     // Ideally, we would only check against memory constraints.  However, the
    7147             :     // meaning of an Other constraint can be target-specific and we can't easily
    7148             :     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
    7149             :     // for Other constraints as well.
    7150       65568 :     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
    7151             :         OpInfo.ConstraintType == TargetLowering::C_Other) {
    7152        5074 :       if (OpInfo.Type == InlineAsm::isInput)
    7153        4393 :         Flags |= InlineAsm::Extra_MayLoad;
    7154         681 :       else if (OpInfo.Type == InlineAsm::isOutput)
    7155         184 :         Flags |= InlineAsm::Extra_MayStore;
    7156         497 :       else if (OpInfo.Type == InlineAsm::isClobber)
    7157         497 :         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
    7158             :     }
    7159             :   }
    7160             : 
    7161       12045 :   unsigned get() const { return Flags; }
    7162             : };
    7163             : 
    7164             : } // end anonymous namespace
    7165             : 
    7166             : /// visitInlineAsm - Handle a call to an InlineAsm object.
    7167       12045 : void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
    7168             :   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
    7169             : 
    7170             :   /// ConstraintOperands - Information about all of the constraints.
    7171       11204 :   SDISelAsmOperandInfoVector ConstraintOperands;
    7172             : 
    7173       12045 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    7174             :   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
    7175       47339 :       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
    7176             : 
    7177             :   bool hasMemory = false;
    7178             : 
    7179             :   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
    7180       12045 :   ExtraFlags ExtraInfo(CS);
    7181             : 
    7182             :   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
    7183             :   unsigned ResNo = 0;   // ResNo - The result number of the next output.
    7184       89658 :   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
    7185      196704 :     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
    7186       65568 :     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
    7187             : 
    7188             :     MVT OpVT = MVT::Other;
    7189             : 
    7190             :     // Compute the value type for each operand.
    7191       65568 :     if (OpInfo.Type == InlineAsm::isInput ||
    7192        4031 :         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
    7193       21290 :       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
    7194             : 
    7195             :       // Process the call argument. BasicBlocks are labels, currently appearing
    7196             :       // only in asm's.
    7197       10645 :       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
    7198           4 :         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
    7199             :       } else {
    7200       10643 :         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
    7201             :       }
    7202             : 
    7203             :       OpVT =
    7204             :           OpInfo
    7205       21290 :               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
    7206             :               .getSimpleVT();
    7207             :     }
    7208             : 
    7209       65568 :     if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
    7210             :       // The return value of the call is this value.  As such, there is no
    7211             :       // corresponding argument.
    7212             :       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
    7213             :       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
    7214         569 :         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
    7215        1138 :                                       STy->getElementType(ResNo));
    7216             :       } else {
    7217             :         assert(ResNo == 0 && "Asm only has one result!");
    7218        3242 :         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
    7219             :       }
    7220        3811 :       ++ResNo;
    7221             :     }
    7222             : 
    7223       65568 :     OpInfo.ConstraintVT = OpVT;
    7224             : 
    7225       65568 :     if (!hasMemory)
    7226       61454 :       hasMemory = OpInfo.hasMemory(TLI);
    7227             : 
    7228             :     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
    7229             :     // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
    7230      196704 :     auto TargetConstraint = TargetConstraints[i];
    7231             : 
    7232             :     // Compute the constraint code and ConstraintType to use.
    7233       65568 :     TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
    7234             : 
    7235       65568 :     ExtraInfo.update(TargetConstraint);
    7236             :   }
    7237             : 
    7238       12045 :   SDValue Chain, Flag;
    7239             : 
    7240             :   // We won't need to flush pending loads if this asm doesn't touch
    7241             :   // memory and is nonvolatile.
    7242       12045 :   if (hasMemory || IA->hasSideEffects())
    7243       10995 :     Chain = getRoot();
    7244             :   else
    7245        1050 :     Chain = DAG.getRoot();
    7246             : 
    7247             :   // Second pass over the constraints: compute which constraint option to use
    7248             :   // and assign registers to constraints that want a specific physreg.
    7249       77613 :   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
    7250       65568 :     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
    7251             : 
    7252             :     // If this is an output operand with a matching input operand, look up the
    7253             :     // matching input. If their types mismatch, e.g. one is an integer, the
    7254             :     // other is floating point, or their sizes are different, flag it as an
    7255             :     // error.
    7256       65568 :     if (OpInfo.hasMatchingInput()) {
    7257         265 :       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
    7258         265 :       patchMatchingInput(OpInfo, Input, DAG);
    7259             :     }
    7260             : 
    7261             :     // Compute the constraint code and ConstraintType to use.
    7262       65568 :     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
    7263             : 
    7264       69196 :     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
    7265        3628 :         OpInfo.Type == InlineAsm::isClobber)
    7266         497 :       continue;
    7267             : 
    7268             :     // If this is a memory input, and if the operand is not indirect, do what we
    7269             :     // need to provide an address for the memory input.
    7270       68202 :     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
    7271        3131 :         !OpInfo.isIndirect) {
    7272             :       assert((OpInfo.isMultipleAlternative ||
    7273             :               (OpInfo.Type == InlineAsm::isInput)) &&
    7274             :              "Can only indirectify direct input operands!");
    7275             : 
    7276             :       // Memory operands really want the address of the value.
    7277         411 :       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
    7278             : 
    7279             :       // There is no longer a Value* corresponding to this operand.
    7280         137 :       OpInfo.CallOperandVal = nullptr;
    7281             : 
    7282             :       // It is now an indirect operand.
    7283         137 :       OpInfo.isIndirect = true;
    7284             :     }
    7285             : 
    7286             :     // If this constraint is for a specific register, allocate it before
    7287             :     // anything else.
    7288       65071 :     if (OpInfo.ConstraintType == TargetLowering::C_Register)
    7289      155610 :       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
    7290             :   }
    7291             : 
    7292             :   // Third pass - Loop over all of the operands, assigning virtual or physregs
    7293             :   // to register class operands.
    7294       77613 :   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
    7295       65568 :     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
    7296             : 
    7297             :     // C_Register operands have already been allocated, Other/Memory don't need
    7298             :     // to be.
    7299       65568 :     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
    7300       24975 :       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
    7301             :   }
    7302             : 
    7303             :   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
    7304             :   std::vector<SDValue> AsmNodeOperands;
    7305       24090 :   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
    7306       36135 :   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
    7307       24090 :       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
    7308             : 
    7309             :   // If we have a !srcloc metadata node associated with it, we want to attach
    7310             :   // this to the ultimately generated inline asm machineinstr.  To do this, we
    7311             :   // pass in the third operand as this (potentially null) inline asm MDNode.
    7312             :   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
    7313       24090 :   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
    7314             : 
    7315             :   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
    7316             :   // bits as operand 3.
    7317       36135 :   AsmNodeOperands.push_back(DAG.getTargetConstant(
    7318       48180 :       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
    7319             : 
    7320             :   // Loop over all of the inputs, copying the operand values into the
    7321             :   // appropriate registers and processing the output regs.
    7322       11204 :   RegsForValue RetValRegs;
    7323             : 
    7324             :   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
    7325       11204 :   std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
    7326             : 
    7327       77529 :   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
    7328       65559 :     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
    7329             : 
    7330       65559 :     switch (OpInfo.Type) {
    7331        4030 :     case InlineAsm::isOutput:
    7332        4030 :       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
    7333             :           OpInfo.ConstraintType != TargetLowering::C_Register) {
    7334             :         // Memory output, or 'other' output (e.g. 'X' constraint).
    7335             :         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
    7336             : 
    7337             :         unsigned ConstraintID =
    7338         368 :             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
    7339             :         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
    7340             :                "Failed to convert memory constraint code to constraint id.");
    7341             : 
    7342             :         // Add information to the INLINEASM node to know about this output.
    7343             :         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
    7344             :         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
    7345         736 :         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
    7346         184 :                                                         MVT::i32));
    7347         184 :         AsmNodeOperands.push_back(OpInfo.CallOperand);
    7348         184 :         break;
    7349        3846 :       }
    7350             : 
    7351             :       // Otherwise, this is a register or register class output.
    7352             : 
    7353             :       // Copy the output from the appropriate register.  Find a register that
    7354             :       // we can use.
    7355        3846 :       if (OpInfo.AssignedRegs.Regs.empty()) {
    7356          29 :         emitInlineAsmError(
    7357          29 :             CS, "couldn't allocate output register for constraint '" +
    7358          87 :                     Twine(OpInfo.ConstraintCode) + "'");
    7359         870 :         return;
    7360             :       }
    7361             : 
    7362             :       // If this is an indirect operand, store through the pointer after the
    7363             :       // asm.
    7364        3817 :       if (OpInfo.isIndirect) {
    7365          70 :         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
    7366             :                                                       OpInfo.CallOperandVal));
    7367             :       } else {
    7368             :         // This is the result value of the call.
    7369             :         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
    7370             :         // Concatenate this output onto the outputs list.
    7371        3782 :         RetValRegs.append(OpInfo.AssignedRegs);
    7372             :       }
    7373             : 
    7374             :       // Add information to the INLINEASM node to know that this register is
    7375             :       // set.
    7376             :       OpInfo.AssignedRegs
    7377        7634 :           .AddInlineAsmOperands(OpInfo.isEarlyClobber
    7378             :                                     ? InlineAsm::Kind_RegDefEarlyClobber
    7379             :                                     : InlineAsm::Kind_RegDef,
    7380        7634 :                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
    7381        3817 :       break;
    7382             : 
    7383       10418 :     case InlineAsm::isInput: {
    7384       10418 :       SDValue InOperandVal = OpInfo.CallOperand;
    7385             : 
    7386       10418 :       if (OpInfo.isMatchingInputConstraint()) {
    7387             :         // If this is required to match an output register we have already set,
    7388             :         // just use its register.
    7389         262 :         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
    7390             :                                                   AsmNodeOperands);
    7391             :         unsigned OpFlag =
    7392         786 :           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
    7393         262 :         if (InlineAsm::isRegDefKind(OpFlag) ||
    7394             :             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
    7395             :           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
    7396         262 :           if (OpInfo.isIndirect) {
    7397             :             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
    7398           1 :             emitInlineAsmError(CS, "inline asm not supported yet:"
    7399             :                                    " don't know how to handle tied "
    7400             :                                    "indirect register inputs");
    7401           2 :             return;
    7402             :           }
    7403             : 
    7404         522 :           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
    7405             :           SmallVector<unsigned, 4> Regs;
    7406             : 
    7407         522 :           if (!createVirtualRegs(Regs,
    7408             :                                  InlineAsm::getNumOperandRegisters(OpFlag),
    7409             :                                  RegVT, DAG)) {
    7410           0 :             emitInlineAsmError(CS, "inline asm error: This value type register "
    7411             :                                    "class is not natively supported!");
    7412             :             return;
    7413             :           }
    7414             : 
    7415         783 :           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
    7416             : 
    7417         261 :           SDLoc dl = getCurSDLoc();
    7418             :           // Use the produced MatchedRegs object to
    7419         261 :           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
    7420             :                                     CS.getInstruction());
    7421         261 :           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
    7422             :                                            true, OpInfo.getMatchedOperand(), dl,
    7423             :                                            DAG, AsmNodeOperands);
    7424             :           break;
    7425             :         }
    7426             : 
    7427             :         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
    7428             :         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
    7429             :                "Unexpected number of operands");
    7430             :         // Add information to the INLINEASM node to know about this input.
    7431             :         // See InlineAsm.h isUseOperandTiedToDef.
    7432             :         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
    7433           0 :         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
    7434             :                                                     OpInfo.getMatchedOperand());
    7435           0 :         AsmNodeOperands.push_back(DAG.getTargetConstant(
    7436           0 :             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
    7437           0 :         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
    7438           0 :         break;
    7439             :       }
    7440             : 
    7441             :       // Treat indirect 'X' constraint as memory.
    7442       11634 :       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
    7443        1478 :           OpInfo.isIndirect)
    7444           1 :         OpInfo.ConstraintType = TargetLowering::C_Memory;
    7445             : 
    7446       10156 :       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
    7447             :         std::vector<SDValue> Ops;
    7448        1477 :         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
    7449        1477 :                                           Ops, DAG);
    7450        1477 :         if (Ops.empty()) {
    7451          38 :           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
    7452          38 :                                      Twine(OpInfo.ConstraintCode) + "'");
    7453             :           return;
    7454             :         }
    7455             : 
    7456             :         // Add information to the INLINEASM node to know about this input.
    7457             :         unsigned ResOpType =
    7458        1458 :           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
    7459        4374 :         AsmNodeOperands.push_back(DAG.getTargetConstant(
    7460        5832 :             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
    7461        1458 :         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
    7462             :         break;
    7463             :       }
    7464             : 
    7465        8679 :       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
    7466             :         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
    7467             :         assert(InOperandVal.getValueType() ==
    7468             :                    TLI.getPointerTy(DAG.getDataLayout()) &&
    7469             :                "Memory operands expect pointer values");
    7470             : 
    7471             :         unsigned ConstraintID =
    7472        5902 :             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
    7473             :         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
    7474             :                "Failed to convert memory constraint code to constraint id.");
    7475             : 
    7476             :         // Add information to the INLINEASM node to know about this input.
    7477             :         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
    7478             :         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
    7479        8853 :         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
    7480        5902 :                                                         getCurSDLoc(),
    7481        2951 :                                                         MVT::i32));
    7482        2951 :         AsmNodeOperands.push_back(InOperandVal);
    7483        2951 :         break;
    7484             :       }
    7485             : 
    7486             :       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
    7487             :               OpInfo.ConstraintType == TargetLowering::C_Register) &&
    7488             :              "Unknown constraint type!");
    7489             : 
    7490             :       // TODO: Support this.
    7491        5728 :       if (OpInfo.isIndirect) {
    7492           1 :         emitInlineAsmError(
    7493             :             CS, "Don't know how to handle indirect register inputs yet "
    7494           1 :                 "for constraint '" +
    7495           3 :                     Twine(OpInfo.ConstraintCode) + "'");
    7496           1 :         return;
    7497             :       }
    7498             : 
    7499             :       // Copy the input into the appropriate registers.
    7500        5727 :       if (OpInfo.AssignedRegs.Regs.empty()) {
    7501          50 :         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
    7502          75 :                                    Twine(OpInfo.ConstraintCode) + "'");
    7503          25 :         return;
    7504             :       }
    7505             : 
    7506        5702 :       SDLoc dl = getCurSDLoc();
    7507             : 
    7508        5702 :       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
    7509             :                                         Chain, &Flag, CS.getInstruction());
    7510             : 
    7511        5702 :       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
    7512             :                                                dl, DAG, AsmNodeOperands);
    7513             :       break;
    7514             :     }
    7515       51111 :     case InlineAsm::isClobber:
    7516             :       // Add the clobbered value to the operand list, so that the register
    7517             :       // allocator is aware that the physreg got clobbered.
    7518       51111 :       if (!OpInfo.AssignedRegs.Regs.empty())
    7519       95970 :         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
    7520       95970 :                                                  false, 0, getCurSDLoc(), DAG,
    7521             :                                                  AsmNodeOperands);
    7522             :       break;
    7523             :     }
    7524             :   }
    7525             : 
    7526             :   // Finish up input operands.  Set the input chain and add the flag last.
    7527       11970 :   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
    7528       11970 :   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
    7529             : 
    7530       47880 :   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
    7531       23940 :                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
    7532       11970 :   Flag = Chain.getValue(1);
    7533             : 
    7534             :   // If this asm returns a register value, copy the result from that register
    7535             :   // and set it as the value of the call.
    7536       11970 :   if (!RetValRegs.Regs.empty()) {
    7537        6758 :     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
    7538        3379 :                                              Chain, &Flag, CS.getInstruction());
    7539             : 
    7540             :     // FIXME: Why don't we do this for inline asms with MRVs?
    7541        3379 :     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
    7542        6400 :       EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
    7543             : 
    7544             :       // If any of the results of the inline asm is a vector, it may have the
    7545             :       // wrong width/num elts.  This can happen for register classes that can
    7546             :       // contain multiple different value types.  The preg or vreg allocated may
    7547             :       // not have the same VT as was expected.  Convert it to the right type
    7548             :       // with bit_convert.
    7549        3200 :       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
    7550           0 :         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
    7551           0 :                           ResultType, Val);
    7552             : 
    7553           0 :       } else if (ResultType != Val.getValueType() &&
    7554           0 :                  ResultType.isInteger() && Val.getValueType().isInteger()) {
    7555             :         // If a result value was tied to an input value, the computed result may
    7556             :         // have a wider width than the expected result.  Extract the relevant
    7557             :         // portion.
    7558           0 :         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
    7559             :       }
    7560             : 
    7561             :       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
    7562             :     }
    7563             : 
    7564             :     setValue(CS.getInstruction(), Val);
    7565             :     // Don't need to use this as a chain in this case.
    7566        4145 :     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
    7567         766 :       return;
    7568             :   }
    7569             : 
    7570             :   std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
    7571             : 
    7572             :   // Process indirect outputs, first output all of the flagged copies out of
    7573             :   // physregs.
    7574       22440 :   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
    7575          64 :     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
    7576          32 :     const Value *Ptr = IndirectStoresToEmit[i].second;
    7577          64 :     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
    7578          32 :                                              Chain, &Flag, IA);
    7579          32 :     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
    7580             :   }
    7581             : 
    7582             :   // Emit the non-flagged stores from the physregs.
    7583             :   SmallVector<SDValue, 8> OutChains;
    7584       22440 :   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
    7585         128 :     SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
    7586             :                                getValue(StoresToEmit[i].second),
    7587         160 :                                MachinePointerInfo(StoresToEmit[i].second));
    7588          32 :     OutChains.push_back(Val);
    7589             :   }
    7590             : 
    7591       11204 :   if (!OutChains.empty())
    7592         116 :     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
    7593             : 
    7594       11204 :   DAG.setRoot(Chain);
    7595             : }
    7596             : 
    7597          75 : void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
    7598             :                                              const Twine &Message) {
    7599          75 :   LLVMContext &Ctx = *DAG.getContext();
    7600          75 :   Ctx.emitError(CS.getInstruction(), Message);
    7601             : 
    7602             :   // Make sure we leave the DAG in a valid state
    7603          75 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    7604         225 :   auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType());
    7605          75 :   setValue(CS.getInstruction(), DAG.getUNDEF(VT));
    7606          75 : }
    7607             : 
    7608         225 : void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
    7609         900 :   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
    7610             :                           MVT::Other, getRoot(),
    7611             :                           getValue(I.getArgOperand(0)),
    7612         900 :                           DAG.getSrcValue(I.getArgOperand(0))));
    7613         225 : }
    7614             : 
    7615         177 : void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
    7616         177 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    7617         177 :   const DataLayout &DL = DAG.getDataLayout();
    7618         354 :   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
    7619         354 :                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
    7620         177 :                            DAG.getSrcValue(I.getOperand(0)),
    7621        1062 :                            DL.getABITypeAlignment(I.getType()));
    7622         177 :   setValue(&I, V);
    7623         177 :   DAG.setRoot(V.getValue(1));
    7624         177 : }
    7625             : 
    7626         152 : void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
    7627         608 :   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
    7628             :                           MVT::Other, getRoot(),
    7629             :                           getValue(I.getArgOperand(0)),
    7630         608 :                           DAG.getSrcValue(I.getArgOperand(0))));
    7631         152 : }
    7632             : 
    7633           8 : void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
    7634          32 :   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
    7635             :                           MVT::Other, getRoot(),
    7636             :                           getValue(I.getArgOperand(0)),
    7637             :                           getValue(I.getArgOperand(1)),
    7638           8 :                           DAG.getSrcValue(I.getArgOperand(0)),
    7639          48 :                           DAG.getSrcValue(I.getArgOperand(1))));
    7640           8 : }
    7641             : 
    7642       51887 : SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
    7643             :                                                     const Instruction &I,
    7644             :                                                     SDValue Op) {
    7645             :   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
    7646       32023 :   if (!Range)
    7647       48548 :     return Op;
    7648             : 
    7649        6678 :   ConstantRange CR = getConstantRangeFromMetadata(*Range);
    7650        3339 :   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
    7651           0 :     return Op;
    7652             : 
    7653        3339 :   APInt Lo = CR.getUnsignedMin();
    7654        3339 :   if (!Lo.isMinValue())
    7655           1 :     return Op;
    7656             : 
    7657        3338 :   APInt Hi = CR.getUnsignedMax();
    7658             :   unsigned Bits = Hi.getActiveBits();
    7659             : 
    7660        3338 :   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
    7661             : 
    7662        3338 :   SDLoc SL = getCurSDLoc();
    7663             : 
    7664             :   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
    7665        6676 :                              DAG.getValueType(SmallVT));
    7666        3338 :   unsigned NumVals = Op.getNode()->getNumValues();
    7667        3338 :   if (NumVals == 1)
    7668        3334 :     return ZExt;
    7669             : 
    7670             :   SmallVector<SDValue, 4> Ops;
    7671             : 
    7672           4 :   Ops.push_back(ZExt);
    7673          20 :   for (unsigned I = 1; I != NumVals; ++I)
    7674           8 :     Ops.push_back(Op.getValue(I));
    7675             : 
    7676           4 :   return DAG.getMergeValues(Ops, SL);
    7677             : }
    7678             : 
    7679             : /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of
    7680             : /// the call being lowered.
    7681             : ///
    7682             : /// This is a helper for lowering intrinsics that follow a target calling
    7683             : /// convention or require stack pointer adjustment. Only a subset of the
    7684             : /// intrinsic's operands need to participate in the calling convention.
    7685         185 : void SelectionDAGBuilder::populateCallLoweringInfo(
    7686             :     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
    7687             :     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
    7688             :     bool IsPatchPoint) {
    7689             :   TargetLowering::ArgListTy Args;
    7690         185 :   Args.reserve(NumArgs);
    7691             : 
    7692             :   // Populate the argument list.
    7693             :   // Attributes for args start at offset 1, after the return attribute.
    7694         349 :   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
    7695         349 :        ArgI != ArgE; ++ArgI) {
    7696         164 :     const Value *V = CS->getOperand(ArgI);
    7697             : 
    7698             :     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
    7699             : 
    7700             :     TargetLowering::ArgListEntry Entry;
    7701         164 :     Entry.Node = getValue(V);
    7702         164 :     Entry.Ty = V->getType();
    7703         164 :     Entry.setAttributes(&CS, ArgIdx);
    7704         164 :     Args.push_back(Entry);
    7705             :   }
    7706             : 
    7707         370 :   CLI.setDebugLoc(getCurSDLoc())
    7708         185 :       .setChain(getRoot())
    7709             :       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
    7710         185 :       .setDiscardResult(CS->use_empty())
    7711             :       .setIsPatchPoint(IsPatchPoint);
    7712         185 : }
    7713             : 
    7714             : /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
    7715             : /// or patchpoint target node's operand list.
    7716             : ///
    7717             : /// Constants are converted to TargetConstants purely as an optimization to
    7718             : /// avoid constant materialization and register allocation.
    7719             : ///
    7720             : /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
    7721             : /// generate addess computation nodes, and so ExpandISelPseudo can convert the
    7722             : /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
    7723             : /// address materialization and register allocation, but may also be required
    7724             : /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
    7725             : /// alloca in the entry block, then the runtime may assume that the alloca's
    7726             : /// StackMap location can be read immediately after compilation and that the
    7727             : /// location is valid at any point during execution (this is similar to the
    7728             : /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
    7729             : /// only available in a register, then the runtime would need to trap when
    7730             : /// execution reaches the StackMap in order to read the alloca's location.
    7731         228 : static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
    7732             :                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
    7733             :                                 SelectionDAGBuilder &Builder) {
    7734         534 :   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
    7735         306 :     SDValue OpVal = Builder.getValue(CS.getArgument(i));
    7736             :     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
    7737          88 :       Ops.push_back(
    7738         132 :         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
    7739          44 :       Ops.push_back(
    7740         176 :         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
    7741             :     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
    7742          16 :       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
    7743          32 :       Ops.push_back(Builder.DAG.getTargetFrameIndex(
    7744          32 :           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
    7745             :     } else
    7746         246 :       Ops.push_back(OpVal);
    7747             :   }
    7748         228 : }
    7749             : 
    7750             : /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
    7751         112 : void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
    7752             :   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
    7753             :   //                                  [live variables...])
    7754             : 
    7755             :   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
    7756             : 
    7757         112 :   SDValue Chain, InFlag, Callee, NullPtr;
    7758             :   SmallVector<SDValue, 32> Ops;
    7759             : 
    7760         112 :   SDLoc DL = getCurSDLoc();
    7761         112 :   Callee = getValue(CI.getCalledValue());
    7762         112 :   NullPtr = DAG.getIntPtrConstant(0, DL, true);
    7763             : 
    7764             :   // The stackmap intrinsic only records the live variables (the arguemnts
    7765             :   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
    7766             :   // intrinsic, this won't be lowered to a function call. This means we don't
    7767             :   // have to worry about calling conventions and target specific lowering code.
    7768             :   // Instead we perform the call lowering right here.
    7769             :   //
    7770             :   // chain, flag = CALLSEQ_START(chain, 0, 0)
    7771             :   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
    7772             :   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
    7773             :   //
    7774         112 :   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
    7775         112 :   InFlag = Chain.getValue(1);
    7776             : 
    7777             :   // Add the <id> and <numBytes> constants.
    7778         112 :   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
    7779         224 :   Ops.push_back(DAG.getTargetConstant(
    7780         112 :                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
    7781         112 :   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
    7782         224 :   Ops.push_back(DAG.getTargetConstant(
    7783             :                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
    7784         112 :                   MVT::i32));
    7785             : 
    7786             :   // Push live variables for the stack map.
    7787         112 :   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
    7788             : 
    7789             :   // We are not pushing any register mask info here on the operands list,
    7790             :   // because the stackmap doesn't clobber anything.
    7791             : 
    7792             :   // Push the chain and the glue flag.
    7793         112 :   Ops.push_back(Chain);
    7794         112 :   Ops.push_back(InFlag);
    7795             : 
    7796             :   // Create the STACKMAP node.
    7797         224 :   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    7798         224 :   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
    7799         112 :   Chain = SDValue(SM, 0);
    7800         112 :   InFlag = Chain.getValue(1);
    7801             : 
    7802         112 :   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
    7803             : 
    7804             :   // Stackmaps don't generate values, so nothing goes into the NodeMap.
    7805             : 
    7806             :   // Set the root to the target-lowered call chain.
    7807         112 :   DAG.setRoot(Chain);
    7808             : 
    7809             :   // Inform the Frame Information that we have a stackmap in this function.
    7810         112 :   FuncInfo.MF->getFrameInfo().setHasStackMap();
    7811         112 : }
    7812             : 
    7813             : /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
    7814         116 : void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
    7815             :                                           const BasicBlock *EHPadBB) {
    7816             :   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
    7817             :   //                                                 i32 <numBytes>,
    7818             :   //                                                 i8* <target>,
    7819             :   //                                                 i32 <numArgs>,
    7820             :   //                                                 [Args...],
    7821             :   //                                                 [live variables...])
    7822             : 
    7823             :   CallingConv::ID CC = CS.getCallingConv();
    7824         116 :   bool IsAnyRegCC = CC == CallingConv::AnyReg;
    7825         232 :   bool HasDef = !CS->getType()->isVoidTy();
    7826         116 :   SDLoc dl = getCurSDLoc();
    7827         232 :   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
    7828             : 
    7829             :   // Handle immediate and symbolic callees.
    7830             :   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
    7831         226 :     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
    7832         113 :                                    /*isTarget=*/true);
    7833             :   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
    7834           6 :     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
    7835           3 :                                          SDLoc(SymbolicCallee),
    7836           6 :                                          SymbolicCallee->getValueType(0));
    7837             : 
    7838             :   // Get the real number of arguments participating in the call <numArgs>
    7839         116 :   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
    7840         232 :   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
    7841             : 
    7842             :   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
    7843             :   // Intrinsics include all meta-operands up to but not including CC.
    7844             :   unsigned NumMetaOpers = PatchPointOpers::CCPos;
    7845             :   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
    7846             :          "Not enough arguments provided to the patchpoint intrinsic");
    7847             : 
    7848             :   // For AnyRegCC the arguments are lowered later on manually.
    7849         116 :   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
    7850             :   Type *ReturnTy =
    7851         116 :     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
    7852             : 
    7853         232 :   TargetLowering::CallLoweringInfo CLI(DAG);
    7854         116 :   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
    7855             :                            true);
    7856         116 :   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
    7857             : 
    7858         116 :   SDNode *CallEnd = Result.second.getNode();
    7859         116 :   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
    7860          27 :     CallEnd = CallEnd->getOperand(0).getNode();
    7861             : 
    7862             :   /// Get a call instruction from the call sequence chain.
    7863             :   /// Tail calls are not allowed.
    7864             :   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
    7865             :          "Expected a callseq node.");
    7866         116 :   SDNode *Call = CallEnd->getOperand(0).getNode();
    7867             :   bool HasGlue = Call->getGluedNode();
    7868             : 
    7869             :   // Replace the target specific call node with the patchable intrinsic.
    7870             :   SmallVector<SDValue, 8> Ops;
    7871             : 
    7872             :   // Add the <id> and <numBytes> constants.
    7873         116 :   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
    7874         232 :   Ops.push_back(DAG.getTargetConstant(
    7875         116 :                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
    7876         116 :   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
    7877         232 :   Ops.push_back(DAG.getTargetConstant(
    7878             :                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
    7879         116 :                   MVT::i32));
    7880             : 
    7881             :   // Add the callee.
    7882         116 :   Ops.push_back(Callee);
    7883             : 
    7884             :   // Adjust <numArgs> to account for any arguments that have been passed on the
    7885             :   // stack instead.
    7886             :   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
    7887         232 :   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
    7888         116 :   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
    7889         232 :   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
    7890             : 
    7891             :   // Add the calling convention
    7892         232 :   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
    7893             : 
    7894             :   // Add the arguments we omitted previously. The register allocator should
    7895             :   // place these in any free register.
    7896         116 :   if (IsAnyRegCC)
    7897         288 :     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
    7898         232 :       Ops.push_back(getValue(CS.getArgument(i)));
    7899             : 
    7900             :   // Push the arguments from the call instruction up to the register mask.
    7901         232 :   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
    7902         116 :   Ops.append(Call->op_begin() + 2, e);
    7903             : 
    7904             :   // Push live variables for the stack map.
    7905         116 :   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
    7906             : 
    7907             :   // Push the register mask info.
    7908         116 :   if (HasGlue)
    7909          94 :     Ops.push_back(*(Call->op_end()-2));
    7910             :   else
    7911         138 :     Ops.push_back(*(Call->op_end()-1));
    7912             : 
    7913             :   // Push the chain (this is originally the first operand of the call, but
    7914             :   // becomes now the last or second to last operand).
    7915         232 :   Ops.push_back(*(Call->op_begin()));
    7916             : 
    7917             :   // Push the glue flag (last operand).
    7918         116 :   if (HasGlue)
    7919          94 :     Ops.push_back(*(Call->op_end()-1));
    7920             : 
    7921             :   SDVTList NodeTys;
    7922         116 :   if (IsAnyRegCC && HasDef) {
    7923             :     // Create the return types based on the intrinsic definition
    7924          39 :     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    7925             :     SmallVector<EVT, 3> ValueVTs;
    7926          78 :     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
    7927             :     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
    7928             : 
    7929             :     // There is always a chain and a glue type at the end
    7930          39 :     ValueVTs.push_back(MVT::Other);
    7931          39 :     ValueVTs.push_back(MVT::Glue);
    7932          78 :     NodeTys = DAG.getVTList(ValueVTs);
    7933             :   } else
    7934         154 :     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    7935             : 
    7936             :   // Replace the target specific call node with a PATCHPOINT node.
    7937         232 :   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
    7938         116 :                                          dl, NodeTys, Ops);
    7939             : 
    7940             :   // Update the NodeMap.
    7941         116 :   if (HasDef) {
    7942          66 :     if (IsAnyRegCC)
    7943             :       setValue(CS.getInstruction(), SDValue(MN, 0));
    7944             :     else
    7945             :       setValue(CS.getInstruction(), Result.first);
    7946             :   }
    7947             : 
    7948             :   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
    7949             :   // call sequence. Furthermore the location of the chain and glue can change
    7950             :   // when the AnyReg calling convention is used and the intrinsic returns a
    7951             :   // value.
    7952         116 :   if (IsAnyRegCC && HasDef) {
    7953             :     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
    7954             :     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
    7955          39 :     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
    7956             :   } else
    7957          77 :     DAG.ReplaceAllUsesWith(Call, MN);
    7958         116 :   DAG.DeleteNode(Call);
    7959             : 
    7960             :   // Inform the Frame Information that we have a patchpoint in this function.
    7961         116 :   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
    7962         116 : }
    7963             : 
    7964          31 : void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
    7965             :                                             unsigned Intrinsic) {
    7966          31 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    7967          31 :   SDValue Op1 = getValue(I.getArgOperand(0));
    7968          31 :   SDValue Op2;
    7969          31 :   if (I.getNumArgOperands() > 1)
    7970           0 :     Op2 = getValue(I.getArgOperand(1));
    7971          31 :   SDLoc dl = getCurSDLoc();
    7972          62 :   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
    7973             :   SDValue Res;
    7974             :   FastMathFlags FMF;
    7975          31 :   if (isa<FPMathOperator>(I))
    7976           2 :     FMF = I.getFastMathFlags();
    7977             :   SDNodeFlags SDFlags;
    7978             :   SDFlags.setNoNaNs(FMF.noNaNs());
    7979             : 
    7980          31 :   switch (Intrinsic) {
    7981             :   case Intrinsic::experimental_vector_reduce_fadd:
    7982           0 :     if (FMF.isFast())
    7983           0 :       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
    7984             :     else
    7985           0 :       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
    7986             :     break;
    7987             :   case Intrinsic::experimental_vector_reduce_fmul:
    7988           0 :     if (FMF.isFast())
    7989           0 :       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
    7990             :     else
    7991           0 :       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
    7992             :     break;
    7993           9 :   case Intrinsic::experimental_vector_reduce_add:
    7994          18 :     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
    7995           9 :     break;
    7996           0 :   case Intrinsic::experimental_vector_reduce_mul:
    7997           0 :     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
    7998           0 :     break;
    7999           0 :   case Intrinsic::experimental_vector_reduce_and:
    8000           0 :     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
    8001           0 :     break;
    8002           0 :   case Intrinsic::experimental_vector_reduce_or:
    8003           0 :     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
    8004           0 :     break;
    8005           0 :   case Intrinsic::experimental_vector_reduce_xor:
    8006           0 :     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
    8007           0 :     break;
    8008           5 :   case Intrinsic::experimental_vector_reduce_smax:
    8009          10 :     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
    8010           5 :     break;
    8011           5 :   case Intrinsic::experimental_vector_reduce_smin:
    8012          10 :     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
    8013           5 :     break;
    8014           5 :   case Intrinsic::experimental_vector_reduce_umax:
    8015          10 :     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
    8016           5 :     break;
    8017           5 :   case Intrinsic::experimental_vector_reduce_umin:
    8018          10 :     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
    8019           5 :     break;
    8020           1 :   case Intrinsic::experimental_vector_reduce_fmax:
    8021           1 :     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
    8022           1 :     break;
    8023           1 :   case Intrinsic::experimental_vector_reduce_fmin:
    8024           1 :     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
    8025           1 :     break;
    8026           0 :   default:
    8027           0 :     llvm_unreachable("Unhandled vector reduce intrinsic");
    8028             :   }
    8029          31 :   setValue(&I, Res);
    8030          31 : }
    8031             : 
    8032             : /// Returns an AttributeList representing the attributes applied to the return
    8033             : /// value of the given call.
    8034      217885 : static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
    8035             :   SmallVector<Attribute::AttrKind, 2> Attrs;
    8036      217885 :   if (CLI.RetSExt)
    8037        1002 :     Attrs.push_back(Attribute::SExt);
    8038      217885 :   if (CLI.RetZExt)
    8039        9719 :     Attrs.push_back(Attribute::ZExt);
    8040      217885 :   if (CLI.IsInReg)
    8041         210 :     Attrs.push_back(Attribute::InReg);
    8042             : 
    8043      217885 :   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
    8044      435770 :                             Attrs);
    8045             : }
    8046             : 
    8047             : /// TargetLowering::LowerCallTo - This is the default LowerCallTo
    8048             : /// implementation, which just calls LowerCall.
    8049             : /// FIXME: When all targets are
    8050             : /// migrated to using LowerCall, this hook should be integrated into SDISel.
    8051             : std::pair<SDValue, SDValue>
    8052      217885 : TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
    8053             :   // Handle the incoming return values from the call.
    8054             :   CLI.Ins.clear();
    8055      217885 :   Type *OrigRetTy = CLI.RetTy;
    8056             :   SmallVector<EVT, 4> RetTys;
    8057             :   SmallVector<uint64_t, 4> Offsets;
    8058      217885 :   auto &DL = CLI.DAG.getDataLayout();
    8059      217885 :   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
    8060             : 
    8061      217885 :   if (CLI.IsPostTypeLegalization) {
    8062             :     // If we are lowering a libcall after legalization, split the return type.
    8063             :     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
    8064             :     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
    8065        7083 :     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
    8066        2361 :       EVT RetVT = OldRetTys[i];
    8067        2361 :       uint64_t Offset = OldOffsets[i];
    8068        2361 :       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
    8069        2361 :       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
    8070        2361 :       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
    8071        2361 :       RetTys.append(NumRegs, RegisterVT);
    8072        7093 :       for (unsigned j = 0; j != NumRegs; ++j)
    8073        2366 :         Offsets.push_back(Offset + j * RegisterVTByteSZ);
    8074             :     }
    8075             :   }
    8076             : 
    8077             :   SmallVector<ISD::OutputArg, 4> Outs;
    8078      217885 :   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
    8079             : 
    8080             :   bool CanLowerReturn =
    8081      435770 :       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
    8082      653655 :                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
    8083             : 
    8084             :   SDValue DemoteStackSlot;
    8085             :   int DemoteStackIdx = -100;
    8086      217883 :   if (!CanLowerReturn) {
    8087             :     // FIXME: equivalent assert?
    8088             :     // assert(!CS.hasInAllocaArgument() &&
    8089             :     //        "sret demotion is incompatible with inalloca");
    8090          88 :     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
    8091          88 :     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
    8092          88 :     MachineFunction &MF = CLI.DAG.getMachineFunction();
    8093          88 :     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
    8094          88 :     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
    8095             : 
    8096         176 :     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
    8097             :     ArgListEntry Entry;
    8098          88 :     Entry.Node = DemoteStackSlot;
    8099          88 :     Entry.Ty = StackSlotPtrType;
    8100             :     Entry.IsSExt = false;
    8101             :     Entry.IsZExt = false;
    8102             :     Entry.IsInReg = false;
    8103          88 :     Entry.IsSRet = true;
    8104             :     Entry.IsNest = false;
    8105             :     Entry.IsByVal = false;
    8106             :     Entry.IsReturned = false;
    8107             :     Entry.IsSwiftSelf = false;
    8108             :     Entry.IsSwiftError = false;
    8109          88 :     Entry.Alignment = Align;
    8110          88 :     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
    8111          88 :     CLI.NumFixedArgs += 1;
    8112          88 :     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
    8113             : 
    8114             :     // sret demotion isn't compatible with tail-calls, since the sret argument
    8115             :     // points into the callers stack frame.
    8116          88 :     CLI.IsTailCall = false;
    8117             :   } else {
    8118      262760 :     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
    8119       89930 :       EVT VT = RetTys[I];
    8120             :       MVT RegisterVT =
    8121       44965 :           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
    8122             :       unsigned NumRegs =
    8123       44965 :           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
    8124      138635 :       for (unsigned i = 0; i != NumRegs; ++i) {
    8125             :         ISD::InputArg MyFlags;
    8126       46835 :         MyFlags.VT = RegisterVT;
    8127       46835 :         MyFlags.ArgVT = VT;
    8128       46835 :         MyFlags.Used = CLI.IsReturnValueUsed;
    8129       46835 :         if (CLI.RetSExt)
    8130             :           MyFlags.Flags.setSExt();
    8131       46835 :         if (CLI.RetZExt)
    8132             :           MyFlags.Flags.setZExt();
    8133       46835 :         if (CLI.IsInReg)
    8134             :           MyFlags.Flags.setInReg();
    8135       46835 :         CLI.Ins.push_back(MyFlags);
    8136             :       }
    8137             :     }
    8138             :   }
    8139             : 
    8140             :   // We push in swifterror return as the last element of CLI.Ins.
    8141             :   ArgListTy &Args = CLI.getArgs();
    8142      217883 :   if (supportSwiftError()) {
    8143      526477 :     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
    8144      546434 :       if (Args[i].IsSwiftError) {
    8145             :         ISD::InputArg MyFlags;
    8146         110 :         MyFlags.VT = getPointerTy(DL);
    8147         110 :         MyFlags.ArgVT = EVT(getPointerTy(DL));
    8148             :         MyFlags.Flags.setSwiftError();
    8149         110 :         CLI.Ins.push_back(MyFlags);
    8150             :       }
    8151             :     }
    8152             :   }
    8153             : 
    8154             :   // Handle all of the outgoing arguments.
    8155             :   CLI.Outs.clear();
    8156             :   CLI.OutVals.clear();
    8157      908857 :   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
    8158             :     SmallVector<EVT, 4> ValueVTs;
    8159      946182 :     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
    8160             :     // FIXME: Split arguments if CLI.IsPostTypeLegalization
    8161      946182 :     Type *FinalType = Args[i].Ty;
    8162      473091 :     if (Args[i].IsByVal)
    8163        1128 :       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
    8164      473091 :     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
    8165      946182 :         FinalType, CLI.CallConv, CLI.IsVarArg);
    8166      947575 :     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
    8167             :          ++Value) {
    8168      948968 :       EVT VT = ValueVTs[Value];
    8169      474484 :       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
    8170             :       SDValue Op = SDValue(Args[i].Node.getNode(),
    8171      948968 :                            Args[i].Node.getResNo() + Value);
    8172             :       ISD::ArgFlagsTy Flags;
    8173             : 
    8174             :       // Certain targets (such as MIPS), may have a different ABI alignment
    8175             :       // for a type depending on the context. Give the target a chance to
    8176             :       // specify the alignment it wants.
    8177      474484 :       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
    8178             : 
    8179      948968 :       if (Args[i].IsZExt)
    8180             :         Flags.setZExt();
    8181      474484 :       if (Args[i].IsSExt)
    8182             :         Flags.setSExt();
    8183      474484 :       if (Args[i].IsInReg) {
    8184             :         // If we are using vectorcall calling convention, a structure that is
    8185             :         // passed InReg - is surely an HVA
    8186         246 :         if (CLI.CallConv == CallingConv::X86_VectorCall &&
    8187             :             isa<StructType>(FinalType)) {
    8188             :           // The first value of a structure is marked
    8189           8 :           if (0 == Value)
    8190             :             Flags.setHvaStart();
    8191             :           Flags.setHva();
    8192             :         }
    8193             :         // Set InReg Flag
    8194             :         Flags.setInReg();
    8195             :       }
    8196      474484 :       if (Args[i].IsSRet)
    8197             :         Flags.setSRet();
    8198      474484 :       if (Args[i].IsSwiftSelf)
    8199             :         Flags.setSwiftSelf();
    8200      474484 :       if (Args[i].IsSwiftError)
    8201             :         Flags.setSwiftError();
    8202      474484 :       if (Args[i].IsByVal)
    8203             :         Flags.setByVal();
    8204      474484 :       if (Args[i].IsInAlloca) {
    8205             :         Flags.setInAlloca();
    8206             :         // Set the byval flag for CCAssignFn callbacks that don't know about
    8207             :         // inalloca.  This way we can know how many bytes we should've allocated
    8208             :         // and how many bytes a callee cleanup function will pop.  If we port
    8209             :         // inalloca to more targets, we'll have to add custom inalloca handling
    8210             :         // in the various CC lowering callbacks.
    8211             :         Flags.setByVal();
    8212             :       }
    8213      474484 :       if (Args[i].IsByVal || Args[i].IsInAlloca) {
    8214        1150 :         PointerType *Ty = cast<PointerType>(Args[i].Ty);
    8215        1150 :         Type *ElementTy = Ty->getElementType();
    8216        1150 :         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
    8217             :         // For ByVal, alignment should come from FE.  BE will guess if this
    8218             :         // info is not there but there are cases it cannot get right.
    8219             :         unsigned FrameAlign;
    8220        2300 :         if (Args[i].Alignment)
    8221         910 :           FrameAlign = Args[i].Alignment;
    8222             :         else
    8223         240 :           FrameAlign = getByValTypeAlignment(ElementTy, DL);
    8224             :         Flags.setByValAlign(FrameAlign);
    8225             :       }
    8226      948968 :       if (Args[i].IsNest)
    8227             :         Flags.setNest();
    8228      474484 :       if (NeedsRegBlock)
    8229             :         Flags.setInConsecutiveRegs();
    8230             :       Flags.setOrigAlign(OriginalAlignment);
    8231             : 
    8232      474484 :       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
    8233             :       unsigned NumParts =
    8234      474484 :           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
    8235      948968 :       SmallVector<SDValue, 4> Parts(NumParts);
    8236             :       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
    8237             : 
    8238      948968 :       if (Args[i].IsSExt)
    8239             :         ExtendKind = ISD::SIGN_EXTEND;
    8240      472775 :       else if (Args[i].IsZExt)
    8241             :         ExtendKind = ISD::ZERO_EXTEND;
    8242             : 
    8243             :       // Conservatively only handle 'returned' on non-vectors that can be lowered,
    8244             :       // for now.
    8245      474770 :       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
    8246             :           CanLowerReturn) {
    8247             :         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
    8248             :                "unexpected use of 'returned'");
    8249             :         // Before passing 'returned' to the target lowering code, ensure that
    8250             :         // either the register MVT and the actual EVT are the same size or that
    8251             :         // the return value and argument are extended in the same way; in these
    8252             :         // cases it's safe to pass the argument register value unchanged as the
    8253             :         // return register value (although it's at the target's option whether
    8254             :         // to do so)
    8255             :         // TODO: allow code generation to take advantage of partially preserved
    8256             :         // registers rather than clobbering the entire register when the
    8257             :         // parameter extension method is not compatible with the return
    8258             :         // extension method
    8259         143 :         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
    8260          24 :             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
    8261          12 :              CLI.RetZExt == Args[i].IsZExt))
    8262             :           Flags.setReturned();
    8263             :       }
    8264             : 
    8265      474484 :       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
    8266             :                      CLI.CS.getInstruction(), ExtendKind, true);
    8267             : 
    8268     1435348 :       for (unsigned j = 0; j != NumParts; ++j) {
    8269             :         // if it isn't first piece, alignment must be 1
    8270             :         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
    8271      480432 :                                i < CLI.NumFixedArgs,
    8272     2882592 :                                i, j*Parts[j].getValueType().getStoreSize());
    8273      480432 :         if (NumParts > 1 && j == 0)
    8274             :           MyFlags.Flags.setSplit();
    8275      475477 :         else if (j != 0) {
    8276             :           MyFlags.Flags.setOrigAlign(1);
    8277        5948 :           if (j == NumParts - 1)
    8278             :             MyFlags.Flags.setSplitEnd();
    8279             :         }
    8280             : 
    8281      480432 :         CLI.Outs.push_back(MyFlags);
    8282      960864 :         CLI.OutVals.push_back(Parts[j]);
    8283             :       }
    8284             : 
    8285      474484 :       if (NeedsRegBlock && Value == NumValues - 1)
    8286         636 :         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
    8287             :     }
    8288             :   }
    8289             : 
    8290             :   SmallVector<SDValue, 4> InVals;
    8291      217883 :   CLI.Chain = LowerCall(CLI, InVals);
    8292             : 
    8293             :   // Update CLI.InVals to use outside of this function.
    8294             :   CLI.InVals = InVals;
    8295             : 
    8296             :   // Verify that the target's LowerCall behaved as expected.
    8297             :   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
    8298             :          "LowerCall didn't return a valid chain!");
    8299             :   assert((!CLI.IsTailCall || InVals.empty()) &&
    8300             :          "LowerCall emitted a return value for a tail call!");
    8301             :   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
    8302             :          "LowerCall didn't emit the correct number of values!");
    8303             : 
    8304             :   // For a tail call, the return value is merely live-out and there aren't
    8305             :   // any nodes in the DAG representing it. Return a special value to
    8306             :   // indicate that a tail call has been emitted and no more Instructions
    8307             :   // should be processed in the current block.
    8308      217879 :   if (CLI.IsTailCall) {
    8309        2922 :     CLI.DAG.setRoot(CLI.Chain);
    8310        2922 :     return std::make_pair(SDValue(), SDValue());
    8311             :   }
    8312             : 
    8313             : #ifndef NDEBUG
    8314             :   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
    8315             :     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
    8316             :     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
    8317             :            "LowerCall emitted a value with the wrong type!");
    8318             :   }
    8319             : #endif
    8320             : 
    8321             :   SmallVector<SDValue, 4> ReturnValues;
    8322      214957 :   if (!CanLowerReturn) {
    8323             :     // The instruction result is the result of loading from the
    8324             :     // hidden sret parameter.
    8325             :     SmallVector<EVT, 1> PVTs;
    8326          88 :     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
    8327             : 
    8328          88 :     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
    8329             :     assert(PVTs.size() == 1 && "Pointers should fit in one register");
    8330          88 :     EVT PtrVT = PVTs[0];
    8331             : 
    8332          88 :     unsigned NumValues = RetTys.size();
    8333          88 :     ReturnValues.resize(NumValues);
    8334         176 :     SmallVector<SDValue, 4> Chains(NumValues);
    8335             : 
    8336             :     // An aggregate return value cannot wrap around the address space, so
    8337             :     // offsets to its parts don't wrap either.
    8338             :     SDNodeFlags Flags;
    8339             :     Flags.setNoUnsignedWrap(true);
    8340             : 
    8341         566 :     for (unsigned i = 0; i < NumValues; ++i) {
    8342         239 :       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
    8343         239 :                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
    8344         478 :                                                         PtrVT), Flags);
    8345         239 :       SDValue L = CLI.DAG.getLoad(
    8346             :           RetTys[i], CLI.DL, CLI.Chain, Add,
    8347             :           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
    8348             :                                             DemoteStackIdx, Offsets[i]),
    8349         478 :           /* Alignment = */ 1);
    8350         239 :       ReturnValues[i] = L;
    8351         478 :       Chains[i] = L.getValue(1);
    8352             :     }
    8353             : 
    8354         176 :     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
    8355             :   } else {
    8356             :     // Collect the legal value parts into potentially illegal values
    8357             :     // that correspond to the original function's return values.
    8358             :     Optional<ISD::NodeType> AssertOp;
    8359      214869 :     if (CLI.RetSExt)
    8360             :       AssertOp = ISD::AssertSext;
    8361      213888 :     else if (CLI.RetZExt)
    8362             :       AssertOp = ISD::AssertZext;
    8363             :     unsigned CurReg = 0;
    8364      258713 :     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
    8365       87688 :       EVT VT = RetTys[I];
    8366             :       MVT RegisterVT =
    8367       43844 :           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
    8368             :       unsigned NumRegs =
    8369       43844 :           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
    8370             : 
    8371       87688 :       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
    8372             :                                               NumRegs, RegisterVT, VT, nullptr,
    8373       87688 :                                               AssertOp, true));
    8374       43844 :       CurReg += NumRegs;
    8375             :     }
    8376             : 
    8377             :     // For a function returning void, there is no return value. We can't create
    8378             :     // such a node, so we just return a null return value in that case. In
    8379             :     // that case, nothing will actually look at the value.
    8380      214869 :     if (ReturnValues.empty())
    8381             :       return std::make_pair(SDValue(), CLI.Chain);
    8382             :   }
    8383             : 
    8384       42746 :   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
    8385       42746 :                                 CLI.DAG.getVTList(RetTys), ReturnValues);
    8386             :   return std::make_pair(Res, CLI.Chain);
    8387             : }
    8388             : 
    8389        1140 : void TargetLowering::LowerOperationWrapper(SDNode *N,
    8390             :                                            SmallVectorImpl<SDValue> &Results,
    8391             :                                            SelectionDAG &DAG) const {
    8392        2280 :   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
    8393        1034 :     Results.push_back(Res);
    8394        1140 : }
    8395             : 
    8396           0 : SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
    8397           0 :   llvm_unreachable("LowerOperation not implemented for this target!");
    8398             : }
    8399             : 
    8400             : void
    8401      128407 : SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
    8402      128407 :   SDValue Op = getNonRegisterValue(V);
    8403             :   assert((Op.getOpcode() != ISD::CopyFromReg ||
    8404             :           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
    8405             :          "Copy from a reg to the same reg!");
    8406             :   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
    8407             : 
    8408      128407 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    8409             :   // If this is an InlineAsm we have to match the registers required, not the
    8410             :   // notional registers required by the type.
    8411             : 
    8412             :   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
    8413      385221 :                    V->getType(), isABIRegCopy(V));
    8414      256814 :   SDValue Chain = DAG.getEntryNode();
    8415             : 
    8416      256814 :   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
    8417      128407 :                               FuncInfo.PreferredExtendType.end())
    8418      226274 :                                  ? ISD::ANY_EXTEND
    8419       97867 :                                  : FuncInfo.PreferredExtendType[V];
    8420      385221 :   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
    8421      128407 :   PendingExports.push_back(Chain);
    8422      128407 : }
    8423             : 
    8424             : #include "llvm/CodeGen/SelectionDAGISel.h"
    8425             : 
    8426             : /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
    8427             : /// entry block, return true.  This includes arguments used by switches, since
    8428             : /// the switch may expand into multiple basic blocks.
    8429       99663 : static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
    8430             :   // With FastISel active, we may be splitting blocks, so force creation
    8431             :   // of virtual registers for all non-dead arguments.
    8432       99663 :   if (FastISel)
    8433       29278 :     return A->use_empty();
    8434             : 
    8435       85024 :   const BasicBlock &Entry = A->getParent()->front();
    8436      177236 :   for (const User *U : A->users())
    8437       97518 :     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
    8438             :       return false;  // Use not in entry block.
    8439             : 
    8440             :   return true;
    8441             : }
    8442             : 
    8443             : using ArgCopyElisionMapTy =
    8444             :     DenseMap<const Argument *,
    8445             :              std::pair<const AllocaInst *, const StoreInst *>>;
    8446             : 
    8447             : /// Scan the entry block of the function in FuncInfo for arguments that look
    8448             : /// like copies into a local alloca. Record any copied arguments in
    8449             : /// ArgCopyElisionCandidates.
    8450             : static void
    8451      163190 : findArgumentCopyElisionCandidates(const DataLayout &DL,
    8452             :                                   FunctionLoweringInfo *FuncInfo,
    8453             :                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
    8454             :   // Record the state of every static alloca used in the entry block. Argument
    8455             :   // allocas are all used in the entry block, so we need approximately as many
    8456             :   // entries as we have arguments.
    8457             :   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
    8458             :   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
    8459      163190 :   unsigned NumArgs = FuncInfo->Fn->arg_size();
    8460      163190 :   StaticAllocas.reserve(NumArgs * 2);
    8461             : 
    8462     1585837 :   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
    8463     1585837 :     if (!V)
    8464             :       return nullptr;
    8465     1585837 :     V = V->stripPointerCasts();
    8466             :     const auto *AI = dyn_cast<AllocaInst>(V);
    8467       21987 :     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
    8468             :       return nullptr;
    8469       43244 :     auto Iter = StaticAllocas.insert({AI, Unknown});
    8470       21622 :     return &Iter.first->second;
    8471      163190 :   };
    8472             : 
    8473             :   // Look for stores of arguments to static allocas. Look through bitcasts and
    8474             :   // GEPs to handle type coercions, as long as the alloca is fully initialized
    8475             :   // by the store. Any non-store use of an alloca escapes it and any subsequent
    8476             :   // unanalyzed store might write it.
    8477             :   // FIXME: Handle structs initialized with multiple stores.
    8478     1187546 :   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
    8479             :     // Look for stores, and handle non-store uses conservatively.
    8480             :     const auto *SI = dyn_cast<StoreInst>(&I);
    8481             :     if (!SI) {
    8482             :       // We will look through cast uses, so ignore them completely.
    8483      789953 :       if (I.isCast())
    8484       82748 :         continue;
    8485             :       // Ignore debug info intrinsics, they don't escape or store to allocas.
    8486        5289 :       if (isa<DbgInfoIntrinsic>(I))
    8487        5289 :         continue;
    8488             :       // This is an unknown instruction. Assume it escapes or writes to all
    8489             :       // static alloca operands.
    8490     4286486 :       for (const Use &U : I.operands()) {
    8491     1441327 :         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
    8492       14489 :           *Info = StaticAllocaInfo::Clobbered;
    8493             :       }
    8494      701916 :       continue;
    8495             :     }
    8496             : 
    8497             :     // If the stored value is a static alloca, mark it as escaped.
    8498       72255 :     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
    8499         248 :       *Info = StaticAllocaInfo::Clobbered;
    8500             : 
    8501             :     // Check if the destination is a static alloca.
    8502       72255 :     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
    8503       72255 :     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
    8504       72255 :     if (!Info)
    8505       65370 :       continue;
    8506             :     const AllocaInst *AI = cast<AllocaInst>(Dst);
    8507             : 
    8508             :     // Skip allocas that have been initialized or clobbered.
    8509        6885 :     if (*Info != StaticAllocaInfo::Unknown)
    8510        1425 :       continue;
    8511             : 
    8512             :     // Check if the stored value is an argument, and that this store fully
    8513             :     // initializes the alloca. Don't elide copies from the same argument twice.
    8514        5460 :     const Value *Val = SI->getValueOperand()->stripPointerCasts();
    8515             :     const auto *Arg = dyn_cast<Argument>(Val);
    8516        8298 :     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
    8517        5525 :         Arg->getType()->isEmptyTy() ||
    8518        2762 :         DL.getTypeStoreSize(Arg->getType()) !=
    8519        2762 :             DL.getTypeAllocSize(AI->getAllocatedType()) ||
    8520             :         ArgCopyElisionCandidates.count(Arg)) {
    8521        2769 :       *Info = StaticAllocaInfo::Clobbered;
    8522        2769 :       continue;
    8523             :     }
    8524             : 
    8525             :     DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI << '\n');
    8526             : 
    8527             :     // Mark this alloca and store for argument copy elision.
    8528        2691 :     *Info = StaticAllocaInfo::Elidable;
    8529        2691 :     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
    8530             : 
    8531             :     // Stop scanning if we've seen all arguments. This will happen early in -O0
    8532             :     // builds, which is useful, because -O0 builds have large entry blocks and
    8533             :     // many allocas.
    8534        2691 :     if (ArgCopyElisionCandidates.size() == NumArgs)
    8535             :       break;
    8536             :   }
    8537      163190 : }
    8538             : 
    8539             : /// Try to elide argument copies from memory into a local alloca. Succeeds if
    8540             : /// ArgVal is a load from a suitable fixed stack object.
    8541        2691 : static void tryToElideArgumentCopy(
    8542             :     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
    8543             :     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
    8544             :     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
    8545             :     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
    8546             :     SDValue ArgVal, bool &ArgHasUses) {
    8547             :   // Check if this is a load from a fixed stack object.
    8548             :   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
    8549             :   if (!LNode)
    8550        2264 :     return;
    8551         465 :   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
    8552             :   if (!FINode)
    8553             :     return;
    8554             : 
    8555             :   // Check that the fixed stack object is the right size and alignment.
    8556             :   // Look at the alignment that the user wrote on the alloca instead of looking
    8557             :   // at the stack object.
    8558         465 :   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
    8559             :   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
    8560         465 :   const AllocaInst *AI = ArgCopyIter->second.first;
    8561         465 :   int FixedIndex = FINode->getIndex();
    8562         465 :   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
    8563         465 :   int OldIndex = AllocaIndex;
    8564         465 :   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
    8565         465 :   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
    8566             :     DEBUG(dbgs() << "  argument copy elision failed due to bad fixed stack "
    8567             :                     "object size\n");
    8568             :     return;
    8569             :   }
    8570         464 :   unsigned RequiredAlignment = AI->getAlignment();
    8571         464 :   if (!RequiredAlignment) {
    8572          64 :     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
    8573             :         AI->getAllocatedType());
    8574             :   }
    8575         464 :   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
    8576             :     DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
    8577             :                     "greater than stack argument alignment ("
    8578             :                  << RequiredAlignment << " vs "
    8579             :                  << MFI.getObjectAlignment(FixedIndex) << ")\n");
    8580             :     return;
    8581             :   }
    8582             : 
    8583             :   // Perform the elision. Delete the old stack object and replace its only use
    8584             :   // in the variable info map. Mark the stack object as mutable.
    8585             :   DEBUG({
    8586             :     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
    8587             :            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
    8588             :            << '\n';
    8589             :   });
    8590             :   MFI.RemoveStackObject(OldIndex);
    8591             :   MFI.setIsImmutableObjectIndex(FixedIndex, false);
    8592         427 :   AllocaIndex = FixedIndex;
    8593         427 :   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
    8594         427 :   Chains.push_back(ArgVal.getValue(1));
    8595             : 
    8596             :   // Avoid emitting code for the store implementing the copy.
    8597         427 :   const StoreInst *SI = ArgCopyIter->second.second;
    8598         427 :   ElidedArgCopyInstrs.insert(SI);
    8599             : 
    8600             :   // Check for uses of the argument again so that we can avoid exporting ArgVal
    8601             :   // if it is't used by anything other than the store.
    8602         799 :   for (const Value *U : Arg.users()) {
    8603         427 :     if (U != SI) {
    8604          55 :       ArgHasUses = true;
    8605             :       break;
    8606             :     }
    8607             :   }
    8608             : }
    8609             : 
    8610      163190 : void SelectionDAGISel::LowerArguments(const Function &F) {
    8611      163190 :   SelectionDAG &DAG = SDB->DAG;
    8612      163190 :   SDLoc dl = SDB->getCurSDLoc();
    8613      163190 :   const DataLayout &DL = DAG.getDataLayout();
    8614             :   SmallVector<ISD::InputArg, 16> Ins;
    8615             : 
    8616      163190 :   if (!FuncInfo->CanLowerReturn) {
    8617             :     // Put in an sret pointer parameter before all the other parameters.
    8618             :     SmallVector<EVT, 1> ValueVTs;
    8619        1072 :     ComputeValueVTs(*TLI, DAG.getDataLayout(),
    8620         536 :                     F.getReturnType()->getPointerTo(
    8621         536 :                         DAG.getDataLayout().getAllocaAddrSpace()),
    8622             :                     ValueVTs);
    8623             : 
    8624             :     // NOTE: Assuming that a pointer will never break down to more than one VT
    8625             :     // or one register.
    8626             :     ISD::ArgFlagsTy Flags;
    8627             :     Flags.setSRet();
    8628        1072 :     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
    8629             :     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
    8630             :                          ISD::InputArg::NoArgIndex, 0);
    8631         536 :     Ins.push_back(RetArg);
    8632             :   }
    8633             : 
    8634             :   // Look for stores of arguments to static allocas. Mark such arguments with a
    8635             :   // flag to ask the target to give us the memory location of that argument if
    8636             :   // available.
    8637             :   ArgCopyElisionMapTy ArgCopyElisionCandidates;
    8638      163190 :   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
    8639             : 
    8640             :   // Set up the incoming argument description vector.
    8641      455553 :   for (const Argument &Arg : F.args()) {
    8642      292363 :     unsigned ArgNo = Arg.getArgNo();
    8643             :     SmallVector<EVT, 4> ValueVTs;
    8644      584726 :     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
    8645      292363 :     bool isArgValueUsed = !Arg.use_empty();
    8646             :     unsigned PartBase = 0;
    8647      292363 :     Type *FinalType = Arg.getType();
    8648      292363 :     if (Arg.hasAttribute(Attribute::ByVal))
    8649         797 :       FinalType = cast<PointerType>(FinalType)->getElementType();
    8650      584726 :     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
    8651      584726 :         FinalType, F.getCallingConv(), F.isVarArg());
    8652      588188 :     for (unsigned Value = 0, NumValues = ValueVTs.size();
    8653      588188 :          Value != NumValues; ++Value) {
    8654      591650 :       EVT VT = ValueVTs[Value];
    8655      295825 :       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
    8656             :       ISD::ArgFlagsTy Flags;
    8657             : 
    8658             :       // Certain targets (such as MIPS), may have a different ABI alignment
    8659             :       // for a type depending on the context. Give the target a chance to
    8660             :       // specify the alignment it wants.
    8661             :       unsigned OriginalAlignment =
    8662      295825 :           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
    8663             : 
    8664      295825 :       if (Arg.hasAttribute(Attribute::ZExt))
    8665             :         Flags.setZExt();
    8666      295825 :       if (Arg.hasAttribute(Attribute::SExt))
    8667             :         Flags.setSExt();
    8668      295825 :       if (Arg.hasAttribute(Attribute::InReg)) {
    8669             :         // If we are using vectorcall calling convention, a structure that is
    8670             :         // passed InReg - is surely an HVA
    8671        1701 :         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
    8672          72 :             isa<StructType>(Arg.getType())) {
    8673             :           // The first value of a structure is marked
    8674          50 :           if (0 == Value)
    8675             :             Flags.setHvaStart();
    8676             :           Flags.setHva();
    8677             :         }
    8678             :         // Set InReg Flag
    8679             :         Flags.setInReg();
    8680             :       }
    8681      295825 :       if (Arg.hasAttribute(Attribute::StructRet))
    8682             :         Flags.setSRet();
    8683      295825 :       if (Arg.hasAttribute(Attribute::SwiftSelf))
    8684             :         Flags.setSwiftSelf();
    8685      295825 :       if (Arg.hasAttribute(Attribute::SwiftError))
    8686             :         Flags.setSwiftError();
    8687      295825 :       if (Arg.hasAttribute(Attribute::ByVal))
    8688             :         Flags.setByVal();
    8689      295825 :       if (Arg.hasAttribute(Attribute::InAlloca)) {
    8690             :         Flags.setInAlloca();
    8691             :         // Set the byval flag for CCAssignFn callbacks that don't know about
    8692             :         // inalloca.  This way we can know how many bytes we should've allocated
    8693             :         // and how many bytes a callee cleanup function will pop.  If we port
    8694             :         // inalloca to more targets, we'll have to add custom inalloca handling
    8695             :         // in the various CC lowering callbacks.
    8696             :         Flags.setByVal();
    8697             :       }
    8698      295825 :       if (F.getCallingConv() == CallingConv::X86_INTR) {
    8699             :         // IA Interrupt passes frame (1st parameter) by value in the stack.
    8700          36 :         if (ArgNo == 0)
    8701             :           Flags.setByVal();
    8702             :       }
    8703      590808 :       if (Flags.isByVal() || Flags.isInAlloca()) {
    8704         842 :         PointerType *Ty = cast<PointerType>(Arg.getType());
    8705         842 :         Type *ElementTy = Ty->getElementType();
    8706         842 :         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
    8707             :         // For ByVal, alignment should be passed from FE.  BE will guess if
    8708             :         // this info is not there but there are cases it cannot get right.
    8709             :         unsigned FrameAlign;
    8710         842 :         if (Arg.getParamAlignment())
    8711         314 :           FrameAlign = Arg.getParamAlignment();
    8712             :         else
    8713         528 :           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
    8714             :         Flags.setByValAlign(FrameAlign);
    8715             :       }
    8716      295825 :       if (Arg.hasAttribute(Attribute::Nest))
    8717             :         Flags.setNest();
    8718      295825 :       if (NeedsRegBlock)
    8719             :         Flags.setInConsecutiveRegs();
    8720             :       Flags.setOrigAlign(OriginalAlignment);
    8721             :       if (ArgCopyElisionCandidates.count(&Arg))
    8722             :         Flags.setCopyElisionCandidate();
    8723             : 
    8724             :       MVT RegisterVT =
    8725      295825 :           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
    8726             :       unsigned NumRegs =
    8727      295825 :           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
    8728      936693 :       for (unsigned i = 0; i != NumRegs; ++i) {
    8729             :         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
    8730      320434 :                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
    8731      320434 :         if (NumRegs > 1 && i == 0)
    8732             :           MyFlags.Flags.setSplit();
    8733             :         // if it isn't first piece, alignment must be 1
    8734      307394 :         else if (i > 0) {
    8735             :           MyFlags.Flags.setOrigAlign(1);
    8736       24609 :           if (i == NumRegs - 1)
    8737             :             MyFlags.Flags.setSplitEnd();
    8738             :         }
    8739      320434 :         Ins.push_back(MyFlags);
    8740             :       }
    8741      295825 :       if (NeedsRegBlock && Value == NumValues - 1)
    8742        2310 :         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
    8743      295825 :       PartBase += VT.getStoreSize();
    8744             :     }
    8745             :   }
    8746             : 
    8747             :   // Call the target to set up the argument values.
    8748             :   SmallVector<SDValue, 8> InVals;
    8749      163190 :   SDValue NewRoot = TLI->LowerFormalArguments(
    8750      489570 :       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
    8751             : 
    8752             :   // Verify that the target's LowerFormalArguments behaved as expected.
    8753             :   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
    8754             :          "LowerFormalArguments didn't return a valid chain!");
    8755             :   assert(InVals.size() == Ins.size() &&
    8756             :          "LowerFormalArguments didn't emit the correct number of values!");
    8757             :   DEBUG({
    8758             :       for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
    8759             :         assert(InVals[i].getNode() &&
    8760             :                "LowerFormalArguments emitted a null value!");
    8761             :         assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
    8762             :                "LowerFormalArguments emitted a value with the wrong type!");
    8763             :       }
    8764             :     });
    8765             : 
    8766             :   // Update the DAG with the new chain value resulting from argument lowering.
    8767      163186 :   DAG.setRoot(NewRoot);
    8768             : 
    8769             :   // Set up the argument values.
    8770             :   unsigned i = 0;
    8771      163186 :   if (!FuncInfo->CanLowerReturn) {
    8772             :     // Create a virtual register for the sret pointer, and put in a copy
    8773             :     // from the sret argument into it.
    8774             :     SmallVector<EVT, 1> ValueVTs;
    8775        1072 :     ComputeValueVTs(*TLI, DAG.getDataLayout(),
    8776         536 :                     F.getReturnType()->getPointerTo(
    8777         536 :                         DAG.getDataLayout().getAllocaAddrSpace()),
    8778             :                     ValueVTs);
    8779             :     MVT VT = ValueVTs[0].getSimpleVT();
    8780        1072 :     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
    8781             :     Optional<ISD::NodeType> AssertOp = None;
    8782             :     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
    8783         536 :                                         RegVT, VT, nullptr, AssertOp);
    8784             : 
    8785         536 :     MachineFunction& MF = SDB->DAG.getMachineFunction();
    8786         536 :     MachineRegisterInfo& RegInfo = MF.getRegInfo();
    8787         536 :     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
    8788         536 :     FuncInfo->DemoteRegister = SRetReg;
    8789         536 :     NewRoot =
    8790        2144 :         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
    8791         536 :     DAG.setRoot(NewRoot);
    8792             : 
    8793             :     // i indexes lowered arguments.  Bump it past the hidden sret argument.
    8794             :     ++i;
    8795             :   }
    8796             : 
    8797             :   SmallVector<SDValue, 4> Chains;
    8798             :   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
    8799      455544 :   for (const Argument &Arg : F.args()) {
    8800             :     SmallVector<SDValue, 4> ArgValues;
    8801             :     SmallVector<EVT, 4> ValueVTs;
    8802      584716 :     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
    8803      292358 :     unsigned NumValues = ValueVTs.size();
    8804      292358 :     if (NumValues == 0)
    8805          18 :       continue;
    8806             : 
    8807      292340 :     bool ArgHasUses = !Arg.use_empty();
    8808             : 
    8809             :     // Elide the copying store if the target loaded this argument from a
    8810             :     // suitable fixed stack object.
    8811      584680 :     if (Ins[i].Flags.isCopyElisionCandidate()) {
    8812        2691 :       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
    8813             :                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
    8814             :                              InVals[i], ArgHasUses);
    8815             :     }
    8816             : 
    8817             :     // If this argument is unused then remember its value. It is used to generate
    8818             :     // debugging information.
    8819             :     bool isSwiftErrorArg =
    8820      476266 :         TLI->supportSwiftError() &&
    8821      183926 :         Arg.hasAttribute(Attribute::SwiftError);
    8822      292340 :     if (!ArgHasUses && !isSwiftErrorArg) {
    8823       31348 :       SDB->setUnusedArgValue(&Arg, InVals[i]);
    8824             : 
    8825             :       // Also remember any frame index for use in FastISel.
    8826             :       if (FrameIndexSDNode *FI =
    8827       15674 :           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
    8828          85 :         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
    8829             :     }
    8830             : 
    8831      883980 :     for (unsigned Val = 0; Val != NumValues; ++Val) {
    8832      591640 :       EVT VT = ValueVTs[Val];
    8833             :       MVT PartVT =
    8834      295820 :           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
    8835             :       unsigned NumParts =
    8836      295820 :           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
    8837             : 
    8838             :       // Even an apparant 'unused' swifterror argument needs to be returned. So
    8839             :       // we do generate a copy for it that can be used on return from the
    8840             :       // function.
    8841      295820 :       if (ArgHasUses || isSwiftErrorArg) {
    8842             :         Optional<ISD::NodeType> AssertOp;
    8843      277739 :         if (Arg.hasAttribute(Attribute::SExt))
    8844             :           AssertOp = ISD::AssertSext;
    8845      270585 :         else if (Arg.hasAttribute(Attribute::ZExt))
    8846             :           AssertOp = ISD::AssertZext;
    8847             : 
    8848      555478 :         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
    8849             :                                              PartVT, VT, nullptr, AssertOp,
    8850      277739 :                                              true));
    8851             :       }
    8852             : 
    8853      295820 :       i += NumParts;
    8854             :     }
    8855             : 
    8856             :     // We don't need to do anything else for unused arguments.
    8857      292340 :     if (ArgValues.empty())
    8858       15674 :       continue;
    8859             : 
    8860             :     // Note down frame index.
    8861             :     if (FrameIndexSDNode *FI =
    8862      276666 :         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
    8863         469 :       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
    8864             : 
    8865      276666 :     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
    8866     1106664 :                                      SDB->getCurSDLoc());
    8867             : 
    8868      276666 :     SDB->setValue(&Arg, Res);
    8869      538693 :     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
    8870             :       // We want to associate the argument with the frame index, among
    8871             :       // involved operands, that correspond to the lowest address. The
    8872             :       // getCopyFromParts function, called earlier, is swapping the order of
    8873             :       // the operands to BUILD_PAIR depending on endianness. The result of
    8874             :       // that swapping is that the least significant bits of the argument will
    8875             :       // be in the first operand of the BUILD_PAIR node, and the most
    8876             :       // significant bits will be in the second operand.
    8877        7436 :       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
    8878             :       if (LoadSDNode *LNode =
    8879        3718 :           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
    8880             :         if (FrameIndexSDNode *FI =
    8881        1184 :             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
    8882         900 :           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
    8883             :     }
    8884             : 
    8885             :     // Update the SwiftErrorVRegDefMap.
    8886      276666 :     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
    8887         101 :       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
    8888         101 :       if (TargetRegisterInfo::isVirtualRegister(Reg))
    8889         101 :         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
    8890             :                                            FuncInfo->SwiftErrorArg, Reg);
    8891             :     }
    8892             : 
    8893             :     // If this argument is live outside of the entry block, insert a copy from
    8894             :     // wherever we got it to the vreg that other BB's will reference it as.
    8895      538693 :     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
    8896             :       // If we can, though, try to skip creating an unnecessary vreg.
    8897             :       // FIXME: This isn't very clean... it would be nice to make this more
    8898             :       // general.  It's also subtly incompatible with the hacks FastISel
    8899             :       // uses with vregs.
    8900      177003 :       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
    8901      354006 :       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
    8902      354006 :         FuncInfo->ValueMap[&Arg] = Reg;
    8903      177003 :         continue;
    8904             :       }
    8905             :     }
    8906       99663 :     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
    8907       19938 :       FuncInfo->InitializeRegForValue(&Arg);
    8908       19938 :       SDB->CopyToExportRegsIfNeeded(&Arg);
    8909             :     }
    8910             :   }
    8911             : 
    8912      163186 :   if (!Chains.empty()) {
    8913         240 :     Chains.push_back(NewRoot);
    8914         240 :     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
    8915             :   }
    8916             : 
    8917      163186 :   DAG.setRoot(NewRoot);
    8918             : 
    8919             :   assert(i == InVals.size() && "Argument register count mismatch!");
    8920             : 
    8921             :   // If any argument copy elisions occurred and we have debug info, update the
    8922             :   // stale frame indices used in the dbg.declare variable info table.
    8923      163186 :   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
    8924      163186 :   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
    8925           0 :     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
    8926           0 :       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
    8927           0 :       if (I != ArgCopyElisionFrameIndexMap.end())
    8928           0 :         VI.Slot = I->second;
    8929             :     }
    8930             :   }
    8931             : 
    8932             :   // Finally, if the target has anything special to do, allow it to do so.
    8933      163186 :   EmitFunctionEntryCode();
    8934      163186 : }
    8935             : 
    8936             : /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
    8937             : /// ensure constants are generated when needed.  Remember the virtual registers
    8938             : /// that need to be added to the Machine PHI nodes as input.  We cannot just
    8939             : /// directly add them, because expansion might result in multiple MBB's for one
    8940             : /// BB.  As such, the start of the BB might correspond to a different MBB than
    8941             : /// the end.
    8942             : void
    8943      312022 : SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
    8944      312022 :   const TerminatorInst *TI = LLVMBB->getTerminator();
    8945             : 
    8946             :   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
    8947             : 
    8948             :   // Check PHI nodes in successors that expect a value to be available from this
    8949             :   // block.
    8950      539193 :   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
    8951      227171 :     const BasicBlock *SuccBB = TI->getSuccessor(succ);
    8952      402897 :     if (!isa<PHINode>(SuccBB->begin())) continue;
    8953      102970 :     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
    8954             : 
    8955             :     // If this terminator has multiple identical successors (common for
    8956             :     // switches), only handle each succ once.
    8957       51485 :     if (!SuccsHandled.insert(SuccMBB).second)
    8958          40 :       continue;
    8959             : 
    8960       51445 :     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
    8961             : 
    8962             :     // At this point we know that there is a 1-1 correspondence between LLVM PHI
    8963             :     // nodes and Machine PHI nodes, but the incoming operands have not been
    8964             :     // emitted yet.
    8965      194411 :     for (const PHINode &PN : SuccBB->phis()) {
    8966             :       // Ignore dead phi's.
    8967       91521 :       if (PN.use_empty())
    8968        7694 :         continue;
    8969             : 
    8970             :       // Skip empty types
    8971       87676 :       if (PN.getType()->isEmptyTy())
    8972           4 :         continue;
    8973             : 
    8974             :       unsigned Reg;
    8975       87672 :       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
    8976             : 
    8977       87672 :       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
    8978       13131 :         unsigned &RegOut = ConstantsOut[C];
    8979       13131 :         if (RegOut == 0) {
    8980       10596 :           RegOut = FuncInfo.CreateRegs(C->getType());
    8981       10596 :           CopyValueToVirtualRegister(C, RegOut);
    8982             :         }
    8983       13131 :         Reg = RegOut;
    8984             :       } else {
    8985             :         DenseMap<const Value *, unsigned>::iterator I =
    8986       74541 :           FuncInfo.ValueMap.find(PHIOp);
    8987      149082 :         if (I != FuncInfo.ValueMap.end())
    8988       74478 :           Reg = I->second;
    8989             :         else {
    8990             :           assert(isa<AllocaInst>(PHIOp) &&
    8991             :                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
    8992             :                  "Didn't codegen value into a register!??");
    8993          63 :           Reg = FuncInfo.CreateRegs(PHIOp->getType());
    8994          63 :           CopyValueToVirtualRegister(PHIOp, Reg);
    8995             :         }
    8996             :       }
    8997             : 
    8998             :       // Remember that this register needs to added to the machine PHI node as
    8999             :       // the input for this MBB.
    9000             :       SmallVector<EVT, 4> ValueVTs;
    9001       87672 :       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9002      175344 :       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
    9003      176394 :       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
    9004      177444 :         EVT VT = ValueVTs[vti];
    9005       88722 :         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
    9006      269594 :         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
    9007       90436 :           FuncInfo.PHINodesToUpdate.push_back(
    9008      271308 :               std::make_pair(&*MBBI++, Reg + i));
    9009       88722 :         Reg += NumRegisters;
    9010             :       }
    9011             :     }
    9012             :   }
    9013             : 
    9014      312022 :   ConstantsOut.clear();
    9015      312022 : }
    9016             : 
    9017             : /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
    9018             : /// is 0.
    9019             : MachineBasicBlock *
    9020         380 : SelectionDAGBuilder::StackProtectorDescriptor::
    9021             : AddSuccessorMBB(const BasicBlock *BB,
    9022             :                 MachineBasicBlock *ParentMBB,
    9023             :                 bool IsLikely,
    9024             :                 MachineBasicBlock *SuccMBB) {
    9025             :   // If SuccBB has not been created yet, create it.
    9026         380 :   if (!SuccMBB) {
    9027         375 :     MachineFunction *MF = ParentMBB->getParent();
    9028             :     MachineFunction::iterator BBI(ParentMBB);
    9029         375 :     SuccMBB = MF->CreateMachineBasicBlock(BB);
    9030             :     MF->insert(++BBI, SuccMBB);
    9031             :   }
    9032             :   // Add it as a successor of ParentMBB.
    9033         380 :   ParentMBB->addSuccessor(
    9034             :       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
    9035         380 :   return SuccMBB;
    9036             : }
    9037             : 
    9038      101926 : MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
    9039             :   MachineFunction::iterator I(MBB);
    9040      203852 :   if (++I == FuncInfo.MF->end())
    9041             :     return nullptr;
    9042      101296 :   return &*I;
    9043             : }
    9044             : 
    9045             : /// During lowering new call nodes can be created (such as memset, etc.).
    9046             : /// Those will become new roots of the current DAG, but complications arise
    9047             : /// when they are tail calls. In such cases, the call lowering will update
    9048             : /// the root, but the builder still needs to know that a tail call has been
    9049             : /// lowered in order to avoid generating an additional return.
    9050       25605 : void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
    9051             :   // If the node is null, we do have a tail call.
    9052       25605 :   if (MaybeTC.getNode() != nullptr)
    9053       25571 :     DAG.setRoot(MaybeTC);
    9054             :   else
    9055          34 :     HasTailCall = true;
    9056       25605 : }
    9057             : 
    9058             : uint64_t
    9059        1856 : SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
    9060             :                                        unsigned First, unsigned Last) const {
    9061             :   assert(Last >= First);
    9062        3712 :   const APInt &LowCase = Clusters[First].Low->getValue();
    9063        3712 :   const APInt &HighCase = Clusters[Last].High->getValue();
    9064             :   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
    9065             : 
    9066             :   // FIXME: A range of consecutive cases has 100% density, but only requires one
    9067             :   // comparison to lower. We should discriminate against such consecutive ranges
    9068             :   // in jump tables.
    9069             : 
    9070        5568 :   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
    9071             : }
    9072             : 
    9073        1856 : uint64_t SelectionDAGBuilder::getJumpTableNumCases(
    9074             :     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
    9075             :     unsigned Last) const {
    9076             :   assert(Last >= First);
    9077             :   assert(TotalCases[Last] >= TotalCases[First]);
    9078             :   uint64_t NumCases =
    9079        4970 :       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
    9080        1856 :   return NumCases;
    9081             : }
    9082             : 
    9083         222 : bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
    9084             :                                          unsigned First, unsigned Last,
    9085             :                                          const SwitchInst *SI,
    9086             :                                          MachineBasicBlock *DefaultMBB,
    9087             :                                          CaseCluster &JTCluster) {
    9088             :   assert(First <= Last);
    9089             : 
    9090             :   auto Prob = BranchProbability::getZero();
    9091             :   unsigned NumCmps = 0;
    9092             :   std::vector<MachineBasicBlock*> Table;
    9093             :   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
    9094             : 
    9095             :   // Initialize probabilities in JTProbs.
    9096        3530 :   for (unsigned I = First; I <= Last; ++I)
    9097        4962 :     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
    9098             : 
    9099        3530 :   for (unsigned I = First; I <= Last; ++I) {
    9100             :     assert(Clusters[I].Kind == CC_Range);
    9101        1654 :     Prob += Clusters[I].Prob;
    9102        1654 :     const APInt &Low = Clusters[I].Low->getValue();
    9103        1654 :     const APInt &High = Clusters[I].High->getValue();
    9104        1654 :     NumCmps += (Low == High) ? 1 : 2;
    9105        1654 :     if (I != First) {
    9106             :       // Fill the gap between this and the previous cluster.
    9107        2864 :       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
    9108             :       assert(PreviousHigh.slt(Low));
    9109        4296 :       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
    9110        6462 :       for (uint64_t J = 0; J < Gap; J++)
    9111        2515 :         Table.push_back(DefaultMBB);
    9112             :     }
    9113        4962 :     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
    9114        5994 :     for (uint64_t J = 0; J < ClusterSize; ++J)
    9115        4340 :       Table.push_back(Clusters[I].MBB);
    9116        3308 :     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
    9117             :   }
    9118             : 
    9119         222 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9120             :   unsigned NumDests = JTProbs.size();
    9121         444 :   if (TLI.isSuitableForBitTests(
    9122         444 :           NumDests, NumCmps, Clusters[First].Low->getValue(),
    9123         444 :           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
    9124             :     // Clusters[First..Last] should be lowered as bit tests instead.
    9125             :     return false;
    9126             :   }
    9127             : 
    9128             :   // Create the MBB that will load from and jump through the table.
    9129             :   // Note: We create it here, but it's not inserted into the function yet.
    9130         198 :   MachineFunction *CurMF = FuncInfo.MF;
    9131             :   MachineBasicBlock *JumpTableMBB =
    9132         198 :       CurMF->CreateMachineBasicBlock(SI->getParent());
    9133             : 
    9134             :   // Add successors. Note: use table order for determinism.
    9135             :   SmallPtrSet<MachineBasicBlock *, 8> Done;
    9136        4615 :   for (MachineBasicBlock *Succ : Table) {
    9137        4417 :     if (Done.count(Succ))
    9138        2953 :       continue;
    9139        1464 :     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
    9140        1464 :     Done.insert(Succ);
    9141             :   }
    9142             :   JumpTableMBB->normalizeSuccProbs();
    9143             : 
    9144         198 :   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
    9145         198 :                      ->createJumpTableIndex(Table);
    9146             : 
    9147             :   // Set up the jump table info.
    9148             :   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
    9149         396 :   JumpTableHeader JTH(Clusters[First].Low->getValue(),
    9150         396 :                       Clusters[Last].High->getValue(), SI->getCondition(),
    9151         396 :                       nullptr, false);
    9152         198 :   JTCases.emplace_back(std::move(JTH), std::move(JT));
    9153             : 
    9154         594 :   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
    9155         396 :                                      JTCases.size() - 1, Prob);
    9156             :   return true;
    9157             : }
    9158             : 
    9159        1077 : void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
    9160             :                                          const SwitchInst *SI,
    9161             :                                          MachineBasicBlock *DefaultMBB) {
    9162             : #ifndef NDEBUG
    9163             :   // Clusters must be non-empty, sorted, and only contain Range clusters.
    9164             :   assert(!Clusters.empty());
    9165             :   for (CaseCluster &C : Clusters)
    9166             :     assert(C.Kind == CC_Range);
    9167             :   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
    9168             :     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
    9169             : #endif
    9170             : 
    9171        1077 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9172        1077 :   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
    9173        1016 :     return;
    9174             : 
    9175        1064 :   const int64_t N = Clusters.size();
    9176        1064 :   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
    9177        1064 :   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
    9178             : 
    9179        1064 :   if (N < 2 || N < MinJumpTableEntries)
    9180             :     return;
    9181             : 
    9182             :   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
    9183         494 :   SmallVector<unsigned, 8> TotalCases(N);
    9184        3999 :   for (unsigned i = 0; i < N; ++i) {
    9185        3752 :     const APInt &Hi = Clusters[i].High->getValue();
    9186        1876 :     const APInt &Lo = Clusters[i].Low->getValue();
    9187        7504 :     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
    9188        1876 :     if (i != 0)
    9189        4887 :       TotalCases[i] += TotalCases[i - 1];
    9190             :   }
    9191             : 
    9192             :   // Cheap case: the whole range may be suitable for jump table.
    9193         247 :   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
    9194         247 :   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
    9195             :   assert(NumCases < UINT64_MAX / 100);
    9196             :   assert(Range >= NumCases);
    9197         247 :   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
    9198             :     CaseCluster JTCluster;
    9199         184 :     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
    9200         170 :       Clusters[0] = JTCluster;
    9201         170 :       Clusters.resize(1);
    9202         170 :       return;
    9203             :     }
    9204             :   }
    9205             : 
    9206             :   // The algorithm below is not suitable for -O0.
    9207          77 :   if (TM.getOptLevel() == CodeGenOpt::None)
    9208             :     return;
    9209             : 
    9210             :   // Split Clusters into minimum number of dense partitions. The algorithm uses
    9211             :   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
    9212             :   // for the Case Statement'" (1994), but builds the MinPartitions array in
    9213             :   // reverse order to make it easier to reconstruct the partitions in ascending
    9214             :   // order. In the choice between two optimal partitionings, it picks the one
    9215             :   // which yields more jump tables.
    9216             : 
    9217             :   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
    9218         122 :   SmallVector<unsigned, 8> MinPartitions(N);
    9219             :   // LastElement[i] is the last element of the partition starting at i.
    9220         122 :   SmallVector<unsigned, 8> LastElement(N);
    9221             :   // PartitionsScore[i] is used to break ties when choosing between two
    9222             :   // partitionings resulting in the same number of partitions.
    9223         122 :   SmallVector<unsigned, 8> PartitionsScore(N);
    9224             :   // For PartitionsScore, a small number of comparisons is considered as good as
    9225             :   // a jump table and a single comparison is considered better than a jump
    9226             :   // table.
    9227             :   enum PartitionScores : unsigned {
    9228             :     NoTable = 0,
    9229             :     Table = 1,
    9230             :     FewCases = 1,
    9231             :     SingleCase = 2
    9232             :   };
    9233             : 
    9234             :   // Base case: There is only one way to partition Clusters[N-1].
    9235         122 :   MinPartitions[N - 1] = 1;
    9236          61 :   LastElement[N - 1] = N - 1;
    9237          61 :   PartitionsScore[N - 1] = PartitionScores::SingleCase;
    9238             : 
    9239             :   // Note: loop indexes are signed to avoid underflow.
    9240         412 :   for (int64_t i = N - 2; i >= 0; i--) {
    9241             :     // Find optimal partitioning of Clusters[i..N-1].
    9242             :     // Baseline: Put Clusters[i] into a partition on its own.
    9243        1053 :     MinPartitions[i] = MinPartitions[i + 1] + 1;
    9244         351 :     LastElement[i] = i;
    9245         702 :     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
    9246             : 
    9247             :     // Search for a solution that results in fewer partitions.
    9248        3569 :     for (int64_t j = N - 1; j > i; j--) {
    9249             :       // Try building a partition from Clusters[i..j].
    9250        1609 :       uint64_t Range = getJumpTableRange(Clusters, i, j);
    9251        1609 :       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
    9252             :       assert(NumCases < UINT64_MAX / 100);
    9253             :       assert(Range >= NumCases);
    9254        1609 :       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
    9255        1334 :         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
    9256        1334 :         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
    9257         723 :         int64_t NumEntries = j - i + 1;
    9258             : 
    9259         723 :         if (NumEntries == 1)
    9260           0 :           Score += PartitionScores::SingleCase;
    9261         723 :         else if (NumEntries <= SmallNumberOfEntries)
    9262         210 :           Score += PartitionScores::FewCases;
    9263         513 :         else if (NumEntries >= MinJumpTableEntries)
    9264         357 :           Score += PartitionScores::Table;
    9265             : 
    9266             :         // If this leads to fewer partitions, or to the same number of
    9267             :         // partitions with better score, it is a better partitioning.
    9268         723 :         if (NumPartitions < MinPartitions[i] ||
    9269          94 :             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
    9270         210 :           MinPartitions[i] = NumPartitions;
    9271         210 :           LastElement[i] = j;
    9272         210 :           PartitionsScore[i] = Score;
    9273             :         }
    9274             :       }
    9275             :     }
    9276             :   }
    9277             : 
    9278             :   // Iterate over the partitions, replacing some with jump tables in-place.
    9279             :   unsigned DstIndex = 0;
    9280         465 :   for (unsigned First = 0, Last; First < N; First = Last + 1) {
    9281         404 :     Last = LastElement[First];
    9282             :     assert(Last >= First);
    9283             :     assert(DstIndex <= First);
    9284         202 :     unsigned NumClusters = Last - First + 1;
    9285             : 
    9286             :     CaseCluster JTCluster;
    9287         240 :     if (NumClusters >= MinJumpTableEntries &&
    9288          38 :         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
    9289          56 :       Clusters[DstIndex++] = JTCluster;
    9290             :     } else {
    9291         684 :       for (unsigned I = First; I <= Last; ++I)
    9292         765 :         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
    9293             :     }
    9294             :   }
    9295          61 :   Clusters.resize(DstIndex);
    9296             : }
    9297             : 
    9298         688 : bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
    9299             :                                         unsigned First, unsigned Last,
    9300             :                                         const SwitchInst *SI,
    9301             :                                         CaseCluster &BTCluster) {
    9302             :   assert(First <= Last);
    9303         688 :   if (First == Last)
    9304             :     return false;
    9305             : 
    9306         664 :   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
    9307             :   unsigned NumCmps = 0;
    9308        1131 :   for (int64_t I = First; I <= Last; ++I) {
    9309             :     assert(Clusters[I].Kind == CC_Range);
    9310        1598 :     Dests.set(Clusters[I].MBB->getNumber());
    9311         799 :     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
    9312             :   }
    9313             :   unsigned NumDests = Dests.count();
    9314             : 
    9315         664 :   APInt Low = Clusters[First].Low->getValue();
    9316         664 :   APInt High = Clusters[Last].High->getValue();
    9317             :   assert(Low.slt(High));
    9318             : 
    9319         332 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9320         332 :   const DataLayout &DL = DAG.getDataLayout();
    9321         332 :   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
    9322             :     return false;
    9323             : 
    9324             :   APInt LowBound;
    9325             :   APInt CmpRange;
    9326             : 
    9327          26 :   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
    9328             :   assert(TLI.rangeFitsInWord(Low, High, DL) &&
    9329             :          "Case range must fit in bit mask!");
    9330             : 
    9331             :   // Check if the clusters cover a contiguous range such that no value in the
    9332             :   // range will jump to the default statement.
    9333          26 :   bool ContiguousRange = true;
    9334          61 :   for (int64_t I = First + 1; I <= Last; ++I) {
    9335         336 :     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
    9336          21 :       ContiguousRange = false;
    9337          21 :       break;
    9338             :     }
    9339             :   }
    9340             : 
    9341          26 :   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
    9342             :     // Optimize the case where all the case values fit in a word without having
    9343             :     // to subtract minValue. In this case, we can optimize away the subtraction.
    9344           8 :     LowBound = APInt::getNullValue(Low.getBitWidth());
    9345           4 :     CmpRange = High;
    9346           4 :     ContiguousRange = false;
    9347             :   } else {
    9348          22 :     LowBound = Low;
    9349          22 :     CmpRange = High - Low;
    9350             :   }
    9351             : 
    9352             :   CaseBitsVector CBV;
    9353          26 :   auto TotalProb = BranchProbability::getZero();
    9354         240 :   for (unsigned i = First; i <= Last; ++i) {
    9355             :     // Find the CaseBits for this destination.
    9356             :     unsigned j;
    9357         361 :     for (j = 0; j < CBV.size(); ++j)
    9358         228 :       if (CBV[j].BB == Clusters[i].MBB)
    9359             :         break;
    9360         107 :     if (j == CBV.size())
    9361             :       CBV.push_back(
    9362         126 :           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
    9363         107 :     CaseBits *CB = &CBV[j];
    9364             : 
    9365             :     // Update Mask, Bits and ExtraProb.
    9366         321 :     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
    9367         321 :     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
    9368             :     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
    9369         107 :     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
    9370         107 :     CB->Bits += Hi - Lo + 1;
    9371         107 :     CB->ExtraProb += Clusters[i].Prob;
    9372             :     TotalProb += Clusters[i].Prob;
    9373             :   }
    9374             : 
    9375             :   BitTestInfo BTI;
    9376             :   std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
    9377             :     // Sort by probability first, number of bits second, bit mask third.
    9378          32 :     if (a.ExtraProb != b.ExtraProb)
    9379             :       return a.ExtraProb > b.ExtraProb;
    9380          13 :     if (a.Bits != b.Bits)
    9381           0 :       return a.Bits > b.Bits;
    9382          13 :     return a.Mask < b.Mask;
    9383             :   });
    9384             : 
    9385          68 :   for (auto &CB : CBV) {
    9386             :     MachineBasicBlock *BitTestBB =
    9387          42 :         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
    9388          84 :     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
    9389             :   }
    9390          78 :   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
    9391          52 :                             SI->getCondition(), -1U, MVT::Other, false,
    9392             :                             ContiguousRange, nullptr, nullptr, std::move(BTI),
    9393             :                             TotalProb);
    9394             : 
    9395          52 :   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
    9396         104 :                                     BitTestCases.size() - 1, TotalProb);
    9397             :   return true;
    9398             : }
    9399             : 
    9400        1077 : void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
    9401             :                                               const SwitchInst *SI) {
    9402             : // Partition Clusters into as few subsets as possible, where each subset has a
    9403             : // range that fits in a machine word and has <= 3 unique destinations.
    9404             : 
    9405             : #ifndef NDEBUG
    9406             :   // Clusters must be sorted and contain Range or JumpTable clusters.
    9407             :   assert(!Clusters.empty());
    9408             :   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
    9409             :   for (const CaseCluster &C : Clusters)
    9410             :     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
    9411             :   for (unsigned i = 1; i < Clusters.size(); ++i)
    9412             :     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
    9413             : #endif
    9414             : 
    9415             :   // The algorithm below is not suitable for -O0.
    9416        1077 :   if (TM.getOptLevel() == CodeGenOpt::None)
    9417         533 :     return;
    9418             : 
    9419             :   // If target does not have legal shift left, do not emit bit tests at all.
    9420         546 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9421         546 :   const DataLayout &DL = DAG.getDataLayout();
    9422             : 
    9423         546 :   EVT PTy = TLI.getPointerTy(DL);
    9424             :   if (!TLI.isOperationLegal(ISD::SHL, PTy))
    9425             :     return;
    9426             : 
    9427         544 :   int BitWidth = PTy.getSizeInBits();
    9428         544 :   const int64_t N = Clusters.size();
    9429             : 
    9430             :   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
    9431        1088 :   SmallVector<unsigned, 8> MinPartitions(N);
    9432             :   // LastElement[i] is the last element of the partition starting at i.
    9433        1088 :   SmallVector<unsigned, 8> LastElement(N);
    9434             : 
    9435             :   // FIXME: This might not be the best algorithm for finding bit test clusters.
    9436             : 
    9437             :   // Base case: There is only one way to partition Clusters[N-1].
    9438        1088 :   MinPartitions[N - 1] = 1;
    9439        1088 :   LastElement[N - 1] = N - 1;
    9440             : 
    9441             :   // Note: loop indexes are signed to avoid underflow.
    9442        1155 :   for (int64_t i = N - 2; i >= 0; --i) {
    9443             :     // Find optimal partitioning of Clusters[i..N-1].
    9444             :     // Baseline: Put Clusters[i] into a partition on its own.
    9445        1833 :     MinPartitions[i] = MinPartitions[i + 1] + 1;
    9446         611 :     LastElement[i] = i;
    9447             : 
    9448             :     // Search for a solution that results in fewer partitions.
    9449             :     // Note: the search is limited by BitWidth, reducing time complexity.
    9450        2175 :     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
    9451             :       // Try building a partition from Clusters[i..j].
    9452             : 
    9453             :       // Check the range.
    9454        2006 :       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
    9455        2006 :                                Clusters[j].High->getValue(), DL))
    9456         239 :         continue;
    9457             : 
    9458             :       // Check nbr of destinations and cluster types.
    9459             :       // FIXME: This works, but doesn't seem very efficient.
    9460             :       bool RangesOnly = true;
    9461        1528 :       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
    9462        4976 :       for (int64_t k = i; k <= j; k++) {
    9463        4240 :         if (Clusters[k].Kind != CC_Range) {
    9464             :           RangesOnly = false;
    9465             :           break;
    9466             :         }
    9467        2106 :         Dests.set(Clusters[k].MBB->getNumber());
    9468             :       }
    9469        1514 :       if (!RangesOnly || Dests.count() > 3)
    9470             :         break;
    9471             : 
    9472             :       // Check if it's a better partition.
    9473        1252 :       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
    9474         714 :       if (NumPartitions < MinPartitions[i]) {
    9475             :         // Found a better partition.
    9476         467 :         MinPartitions[i] = NumPartitions;
    9477         467 :         LastElement[i] = j;
    9478             :       }
    9479             :     }
    9480             :   }
    9481             : 
    9482             :   // Iterate over the partitions, replacing with bit-test clusters in-place.
    9483             :   unsigned DstIndex = 0;
    9484        1920 :   for (unsigned First = 0, Last; First < N; First = Last + 1) {
    9485        1376 :     Last = LastElement[First];
    9486             :     assert(First <= Last);
    9487             :     assert(DstIndex <= First);
    9488             : 
    9489             :     CaseCluster BitTestCluster;
    9490         688 :     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
    9491          52 :       Clusters[DstIndex++] = BitTestCluster;
    9492             :     } else {
    9493         662 :       size_t NumClusters = Last - First + 1;
    9494        1986 :       std::memmove(&Clusters[DstIndex], &Clusters[First],
    9495             :                    sizeof(Clusters[0]) * NumClusters);
    9496         662 :       DstIndex += NumClusters;
    9497             :     }
    9498             :   }
    9499         544 :   Clusters.resize(DstIndex);
    9500             : }
    9501             : 
    9502        1136 : void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
    9503             :                                         MachineBasicBlock *SwitchMBB,
    9504             :                                         MachineBasicBlock *DefaultMBB) {
    9505        1136 :   MachineFunction *CurMF = FuncInfo.MF;
    9506             :   MachineBasicBlock *NextMBB = nullptr;
    9507             :   MachineFunction::iterator BBI(W.MBB);
    9508        1136 :   if (++BBI != FuncInfo.MF->end())
    9509             :     NextMBB = &*BBI;
    9510             : 
    9511        1136 :   unsigned Size = W.LastCluster - W.FirstCluster + 1;
    9512             : 
    9513        1136 :   BranchProbabilityInfo *BPI = FuncInfo.BPI;
    9514             : 
    9515        1136 :   if (Size == 2 && W.MBB == SwitchMBB) {
    9516             :     // If any two of the cases has the same destination, and if one value
    9517             :     // is the same as the other, but has one bit unset that the other has set,
    9518             :     // use bit manipulation to do two compares at once.  For example:
    9519             :     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
    9520             :     // TODO: This could be extended to merge any 2 cases in switches with 3
    9521             :     // cases.
    9522             :     // TODO: Handle cases where W.CaseBB != SwitchBB.
    9523             :     CaseCluster &Small = *W.FirstCluster;
    9524             :     CaseCluster &Big = *W.LastCluster;
    9525             : 
    9526        1132 :     if (Small.Low == Small.High && Big.Low == Big.High &&
    9527         439 :         Small.MBB == Big.MBB) {
    9528             :       const APInt &SmallValue = Small.Low->getValue();
    9529             :       const APInt &BigValue = Big.Low->getValue();
    9530             : 
    9531             :       // Check that there is only one bit different.
    9532          53 :       APInt CommonBit = BigValue ^ SmallValue;
    9533          53 :       if (CommonBit.isPowerOf2()) {
    9534           8 :         SDValue CondLHS = getValue(Cond);
    9535          16 :         EVT VT = CondLHS.getValueType();
    9536           8 :         SDLoc DL = getCurSDLoc();
    9537             : 
    9538           8 :         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
    9539           8 :                                  DAG.getConstant(CommonBit, DL, VT));
    9540           8 :         SDValue Cond = DAG.getSetCC(
    9541          16 :             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
    9542          16 :             ISD::SETEQ);
    9543             : 
    9544             :         // Update successor info.
    9545             :         // Both Small and Big will jump to Small.BB, so we sum up the
    9546             :         // probabilities.
    9547           8 :         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
    9548           8 :         if (BPI)
    9549           8 :           addSuccessorWithProb(
    9550             :               SwitchMBB, DefaultMBB,
    9551             :               // The default destination is the first successor in IR.
    9552             :               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
    9553             :         else
    9554           0 :           addSuccessorWithProb(SwitchMBB, DefaultMBB);
    9555             : 
    9556             :         // Insert the true branch.
    9557             :         SDValue BrCond =
    9558           8 :             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
    9559          16 :                         DAG.getBasicBlock(Small.MBB));
    9560             :         // Insert the false branch.
    9561          16 :         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
    9562          16 :                              DAG.getBasicBlock(DefaultMBB));
    9563             : 
    9564           8 :         DAG.setRoot(BrCond);
    9565             :         return;
    9566             :       }
    9567             :     }
    9568             :   }
    9569             : 
    9570        1128 :   if (TM.getOptLevel() != CodeGenOpt::None) {
    9571             :     // Here, we order cases by probability so the most likely case will be
    9572             :     // checked first. However, two clusters can have the same probability in
    9573             :     // which case their relative ordering is non-deterministic. So we use Low
    9574             :     // as a tie-breaker as clusters are guaranteed to never overlap.
    9575             :     std::sort(W.FirstCluster, W.LastCluster + 1,
    9576             :               [](const CaseCluster &a, const CaseCluster &b) {
    9577         921 :       return a.Prob != b.Prob ?
    9578             :              a.Prob > b.Prob :
    9579        1173 :              a.Low->getValue().slt(b.Low->getValue());
    9580             :     });
    9581             : 
    9582             :     // Rearrange the case blocks so that the last one falls through if possible
    9583             :     // without without changing the order of probabilities.
    9584         893 :     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
    9585             :       --I;
    9586         453 :       if (I->Prob > W.LastCluster->Prob)
    9587             :         break;
    9588         388 :       if (I->Kind == CC_Range && I->MBB == NextMBB) {
    9589             :         std::swap(*I, *W.LastCluster);
    9590             :         break;
    9591             :       }
    9592             :     }
    9593             :   }
    9594             : 
    9595             :   // Compute total probability.
    9596        1128 :   BranchProbability DefaultProb = W.DefaultProb;
    9597             :   BranchProbability UnhandledProbs = DefaultProb;
    9598        3409 :   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
    9599             :     UnhandledProbs += I->Prob;
    9600             : 
    9601             :   MachineBasicBlock *CurMBB = W.MBB;
    9602        3409 :   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
    9603             :     MachineBasicBlock *Fallthrough;
    9604        2281 :     if (I == W.LastCluster) {
    9605             :       // For the last cluster, fall through to the default destination.
    9606             :       Fallthrough = DefaultMBB;
    9607             :     } else {
    9608        1153 :       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
    9609             :       CurMF->insert(BBI, Fallthrough);
    9610             :       // Put Cond in a virtual register to make it available from the new blocks.
    9611        1153 :       ExportFromCurrentBlock(Cond);
    9612             :     }
    9613             :     UnhandledProbs -= I->Prob;
    9614             : 
    9615        2281 :     switch (I->Kind) {
    9616             :       case CC_JumpTable: {
    9617             :         // FIXME: Optimize away range check based on pivot comparisons.
    9618         396 :         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
    9619         198 :         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
    9620             : 
    9621             :         // The jump block hasn't been inserted yet; insert it here.
    9622         198 :         MachineBasicBlock *JumpMBB = JT->MBB;
    9623             :         CurMF->insert(BBI, JumpMBB);
    9624             : 
    9625         198 :         auto JumpProb = I->Prob;
    9626             :         auto FallthroughProb = UnhandledProbs;
    9627             : 
    9628             :         // If the default statement is a target of the jump table, we evenly
    9629             :         // distribute the default probability to successors of CurMBB. Also
    9630             :         // update the probability on the edge from JumpMBB to Fallthrough.
    9631             :         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
    9632             :                                               SE = JumpMBB->succ_end();
    9633        1036 :              SI != SE; ++SI) {
    9634         912 :           if (*SI == DefaultMBB) {
    9635             :             JumpProb += DefaultProb / 2;
    9636             :             FallthroughProb -= DefaultProb / 2;
    9637          74 :             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
    9638             :             JumpMBB->normalizeSuccProbs();
    9639             :             break;
    9640             :           }
    9641             :         }
    9642             : 
    9643         198 :         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
    9644         198 :         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
    9645             :         CurMBB->normalizeSuccProbs();
    9646             : 
    9647             :         // The jump table header will be inserted in our current block, do the
    9648             :         // range check, and fall through to our fallthrough block.
    9649         198 :         JTH->HeaderBB = CurMBB;
    9650         198 :         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
    9651             : 
    9652             :         // If we're in the right place, emit the jump table header right now.
    9653         198 :         if (CurMBB == SwitchMBB) {
    9654         185 :           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
    9655         185 :           JTH->Emitted = true;
    9656             :         }
    9657             :         break;
    9658             :       }
    9659             :       case CC_BitTests: {
    9660             :         // FIXME: Optimize away range check based on pivot comparisons.
    9661          26 :         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
    9662             : 
    9663             :         // The bit test blocks haven't been inserted yet; insert them here.
    9664         110 :         for (BitTestCase &BTC : BTB->Cases)
    9665          42 :           CurMF->insert(BBI, BTC.ThisBB);
    9666             : 
    9667             :         // Fill in fields of the BitTestBlock.
    9668          26 :         BTB->Parent = CurMBB;
    9669          26 :         BTB->Default = Fallthrough;
    9670             : 
    9671          26 :         BTB->DefaultProb = UnhandledProbs;
    9672             :         // If the cases in bit test don't form a contiguous range, we evenly
    9673             :         // distribute the probability on the edge to Fallthrough to two
    9674             :         // successors of CurMBB.
    9675          26 :         if (!BTB->ContiguousRange) {
    9676             :           BTB->Prob += DefaultProb / 2;
    9677             :           BTB->DefaultProb -= DefaultProb / 2;
    9678             :         }
    9679             : 
    9680             :         // If we're in the right place, emit the bit test header right now.
    9681          26 :         if (CurMBB == SwitchMBB) {
    9682          25 :           visitBitTestHeader(*BTB, SwitchMBB);
    9683          25 :           BTB->Emitted = true;
    9684             :         }
    9685             :         break;
    9686             :       }
    9687             :       case CC_Range: {
    9688             :         const Value *RHS, *LHS, *MHS;
    9689             :         ISD::CondCode CC;
    9690        2057 :         if (I->Low == I->High) {
    9691             :           // Check Cond == I->Low.
    9692             :           CC = ISD::SETEQ;
    9693             :           LHS = Cond;
    9694             :           RHS=I->Low;
    9695             :           MHS = nullptr;
    9696             :         } else {
    9697             :           // Check I->Low <= Cond <= I->High.
    9698             :           CC = ISD::SETLE;
    9699             :           LHS = I->Low;
    9700             :           MHS = Cond;
    9701             :           RHS = I->High;
    9702             :         }
    9703             : 
    9704             :         // The false probability is the sum of all unhandled cases.
    9705             :         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
    9706        6171 :                      getCurSDLoc(), I->Prob, UnhandledProbs);
    9707             : 
    9708        2057 :         if (CurMBB == SwitchMBB)
    9709         827 :           visitSwitchCase(CB, SwitchMBB);
    9710             :         else
    9711        1230 :           SwitchCases.push_back(CB);
    9712             : 
    9713             :         break;
    9714             :       }
    9715             :     }
    9716             :     CurMBB = Fallthrough;
    9717             :   }
    9718             : }
    9719             : 
    9720          26 : unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
    9721             :                                               CaseClusterIt First,
    9722             :                                               CaseClusterIt Last) {
    9723          88 :   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
    9724         176 :     if (X.Prob != CC.Prob)
    9725          36 :       return X.Prob > CC.Prob;
    9726             : 
    9727             :     // Ties are broken by comparing the case value.
    9728         156 :     return X.Low->getValue().slt(CC.Low->getValue());
    9729          26 :   });
    9730             : }
    9731             : 
    9732          46 : void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
    9733             :                                         const SwitchWorkListItem &W,
    9734             :                                         Value *Cond,
    9735             :                                         MachineBasicBlock *SwitchMBB) {
    9736             :   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
    9737             :          "Clusters not sorted?");
    9738             : 
    9739             :   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
    9740             : 
    9741             :   // Balance the tree based on branch probabilities to create a near-optimal (in
    9742             :   // terms of search time given key frequency) binary search tree. See e.g. Kurt
    9743             :   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
    9744          46 :   CaseClusterIt LastLeft = W.FirstCluster;
    9745          46 :   CaseClusterIt FirstRight = W.LastCluster;
    9746             :   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
    9747             :   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
    9748             : 
    9749             :   // Move LastLeft and FirstRight towards each other from opposite directions to
    9750             :   // find a partitioning of the clusters which balances the probability on both
    9751             :   // sides. If LeftProb and RightProb are equal, alternate which side is
    9752             :   // taken to ensure 0-probability nodes are distributed evenly.
    9753             :   unsigned I = 0;
    9754         332 :   while (LastLeft + 1 < FirstRight) {
    9755         143 :     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
    9756             :       LeftProb += (++LastLeft)->Prob;
    9757             :     else
    9758             :       RightProb += (--FirstRight)->Prob;
    9759         143 :     I++;
    9760             :   }
    9761             : 
    9762             :   while (true) {
    9763             :     // Our binary search tree differs from a typical BST in that ours can have up
    9764             :     // to three values in each leaf. The pivot selection above doesn't take that
    9765             :     // into account, which means the tree might require more nodes and be less
    9766             :     // efficient. We compensate for this here.
    9767             : 
    9768          56 :     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
    9769          56 :     unsigned NumRight = W.LastCluster - FirstRight + 1;
    9770             : 
    9771         100 :     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
    9772             :       // If one side has less than 3 clusters, and the other has more than 3,
    9773             :       // consider taking a cluster from the other side.
    9774             : 
    9775          13 :       if (NumLeft < NumRight) {
    9776             :         // Consider moving the first cluster on the right to the left side.
    9777             :         CaseCluster &CC = *FirstRight;
    9778           4 :         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
    9779           4 :         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
    9780           6 :         if (LeftSideRank <= RightSideRank) {
    9781             :           // Moving the cluster to the left does not demote it.
    9782             :           ++LastLeft;
    9783             :           ++FirstRight;
    9784          12 :           continue;
    9785             :         }
    9786             :       } else {
    9787             :         assert(NumRight < NumLeft);
    9788             :         // Consider moving the last element on the left to the right side.
    9789             :         CaseCluster &CC = *LastLeft;
    9790           9 :         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
    9791           9 :         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
    9792          17 :         if (RightSideRank <= LeftSideRank) {
    9793             :           // Moving the cluster to the right does not demot it.
    9794             :           --LastLeft;
    9795             :           --FirstRight;
    9796           8 :           continue;
    9797             :         }
    9798             :       }
    9799             :     }
    9800          46 :     break;
    9801          10 :   }
    9802             : 
    9803             :   assert(LastLeft + 1 == FirstRight);
    9804             :   assert(LastLeft >= W.FirstCluster);
    9805             :   assert(FirstRight <= W.LastCluster);
    9806             : 
    9807             :   // Use the first element on the right as pivot since we will make less-than
    9808             :   // comparisons against it.
    9809             :   CaseClusterIt PivotCluster = FirstRight;
    9810             :   assert(PivotCluster > W.FirstCluster);
    9811             :   assert(PivotCluster <= W.LastCluster);
    9812             : 
    9813          46 :   CaseClusterIt FirstLeft = W.FirstCluster;
    9814          46 :   CaseClusterIt LastRight = W.LastCluster;
    9815             : 
    9816          46 :   const ConstantInt *Pivot = PivotCluster->Low;
    9817             : 
    9818             :   // New blocks will be inserted immediately after the current one.
    9819          46 :   MachineFunction::iterator BBI(W.MBB);
    9820             :   ++BBI;
    9821             : 
    9822             :   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
    9823             :   // we can branch to its destination directly if it's squeezed exactly in
    9824             :   // between the known lower bound and Pivot - 1.
    9825             :   MachineBasicBlock *LeftMBB;
    9826          49 :   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
    9827          47 :       FirstLeft->Low == W.GE &&
    9828         138 :       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
    9829           0 :     LeftMBB = FirstLeft->MBB;
    9830             :   } else {
    9831          46 :     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
    9832          46 :     FuncInfo.MF->insert(BBI, LeftMBB);
    9833         138 :     WorkList.push_back(
    9834          46 :         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
    9835             :     // Put Cond in a virtual register to make it available from the new blocks.
    9836          46 :     ExportFromCurrentBlock(Cond);
    9837             :   }
    9838             : 
    9839             :   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
    9840             :   // single cluster, RHS.Low == Pivot, and we can branch to its destination
    9841             :   // directly if RHS.High equals the current upper bound.
    9842             :   MachineBasicBlock *RightMBB;
    9843          50 :   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
    9844         140 :       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
    9845           0 :     RightMBB = FirstRight->MBB;
    9846             :   } else {
    9847          46 :     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
    9848          46 :     FuncInfo.MF->insert(BBI, RightMBB);
    9849         138 :     WorkList.push_back(
    9850          46 :         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
    9851             :     // Put Cond in a virtual register to make it available from the new blocks.
    9852          46 :     ExportFromCurrentBlock(Cond);
    9853             :   }
    9854             : 
    9855             :   // Create the CaseBlock record that will be used to lower the branch.
    9856          46 :   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
    9857          92 :                getCurSDLoc(), LeftProb, RightProb);
    9858             : 
    9859          46 :   if (W.MBB == SwitchMBB)
    9860          32 :     visitSwitchCase(CB, SwitchMBB);
    9861             :   else
    9862          14 :     SwitchCases.push_back(CB);
    9863          46 : }
    9864             : 
    9865             : // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
    9866             : // from the swith statement.
    9867          45 : static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
    9868             :                                             BranchProbability PeeledCaseProb) {
    9869          45 :   if (PeeledCaseProb == BranchProbability::getOne())
    9870             :     return BranchProbability::getZero();
    9871          45 :   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
    9872             : 
    9873          45 :   uint32_t Numerator = CaseProb.getNumerator();
    9874          45 :   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
    9875          45 :   return BranchProbability(Numerator, std::max(Numerator, Denominator));
    9876             : }
    9877