1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Triple.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Analysis/AliasAnalysis.h" 30 #include "llvm/Analysis/BranchProbabilityInfo.h" 31 #include "llvm/Analysis/ConstantFolding.h" 32 #include "llvm/Analysis/EHPersonalities.h" 33 #include "llvm/Analysis/Loads.h" 34 #include "llvm/Analysis/MemoryLocation.h" 35 #include "llvm/Analysis/TargetLibraryInfo.h" 36 #include "llvm/Analysis/ValueTracking.h" 37 #include "llvm/Analysis/VectorUtils.h" 38 #include "llvm/CodeGen/Analysis.h" 39 #include "llvm/CodeGen/FunctionLoweringInfo.h" 40 #include "llvm/CodeGen/GCMetadata.h" 41 #include "llvm/CodeGen/ISDOpcodes.h" 42 #include "llvm/CodeGen/MachineBasicBlock.h" 43 #include "llvm/CodeGen/MachineFrameInfo.h" 44 #include "llvm/CodeGen/MachineFunction.h" 45 #include "llvm/CodeGen/MachineInstr.h" 46 #include "llvm/CodeGen/MachineInstrBuilder.h" 47 #include "llvm/CodeGen/MachineJumpTableInfo.h" 48 #include "llvm/CodeGen/MachineMemOperand.h" 49 #include "llvm/CodeGen/MachineModuleInfo.h" 50 #include "llvm/CodeGen/MachineOperand.h" 51 #include "llvm/CodeGen/MachineRegisterInfo.h" 52 #include "llvm/CodeGen/RuntimeLibcalls.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 56 #include "llvm/CodeGen/StackMaps.h" 57 #include "llvm/CodeGen/TargetFrameLowering.h" 58 #include "llvm/CodeGen/TargetInstrInfo.h" 59 #include "llvm/CodeGen/TargetLowering.h" 60 #include "llvm/CodeGen/TargetOpcodes.h" 61 #include "llvm/CodeGen/TargetRegisterInfo.h" 62 #include "llvm/CodeGen/TargetSubtargetInfo.h" 63 #include "llvm/CodeGen/ValueTypes.h" 64 #include "llvm/CodeGen/WinEHFuncInfo.h" 65 #include "llvm/IR/Argument.h" 66 #include "llvm/IR/Attributes.h" 67 #include "llvm/IR/BasicBlock.h" 68 #include "llvm/IR/CFG.h" 69 #include "llvm/IR/CallSite.h" 70 #include "llvm/IR/CallingConv.h" 71 #include "llvm/IR/Constant.h" 72 #include "llvm/IR/ConstantRange.h" 73 #include "llvm/IR/Constants.h" 74 #include "llvm/IR/DataLayout.h" 75 #include "llvm/IR/DebugInfoMetadata.h" 76 #include "llvm/IR/DebugLoc.h" 77 #include "llvm/IR/DerivedTypes.h" 78 #include "llvm/IR/Function.h" 79 #include "llvm/IR/GetElementPtrTypeIterator.h" 80 #include "llvm/IR/InlineAsm.h" 81 #include "llvm/IR/InstrTypes.h" 82 #include "llvm/IR/Instruction.h" 83 #include "llvm/IR/Instructions.h" 84 #include "llvm/IR/IntrinsicInst.h" 85 #include "llvm/IR/Intrinsics.h" 86 #include "llvm/IR/LLVMContext.h" 87 #include "llvm/IR/Metadata.h" 88 #include "llvm/IR/Module.h" 89 #include "llvm/IR/Operator.h" 90 #include "llvm/IR/PatternMatch.h" 91 #include "llvm/IR/Statepoint.h" 92 #include "llvm/IR/Type.h" 93 #include "llvm/IR/User.h" 94 #include "llvm/IR/Value.h" 95 #include "llvm/MC/MCContext.h" 96 #include "llvm/MC/MCSymbol.h" 97 #include "llvm/Support/AtomicOrdering.h" 98 #include "llvm/Support/BranchProbability.h" 99 #include "llvm/Support/Casting.h" 100 #include "llvm/Support/CodeGen.h" 101 #include "llvm/Support/CommandLine.h" 102 #include "llvm/Support/Compiler.h" 103 #include "llvm/Support/Debug.h" 104 #include "llvm/Support/ErrorHandling.h" 105 #include "llvm/Support/MachineValueType.h" 106 #include "llvm/Support/MathExtras.h" 107 #include "llvm/Support/raw_ostream.h" 108 #include "llvm/Target/TargetIntrinsicInfo.h" 109 #include "llvm/Target/TargetMachine.h" 110 #include "llvm/Target/TargetOptions.h" 111 #include <algorithm> 112 #include <cassert> 113 #include <cstddef> 114 #include <cstdint> 115 #include <cstring> 116 #include <iterator> 117 #include <limits> 118 #include <numeric> 119 #include <tuple> 120 #include <utility> 121 #include <vector> 122 123 using namespace llvm; 124 using namespace PatternMatch; 125 126 #define DEBUG_TYPE "isel" 127 128 /// LimitFloatPrecision - Generate low-precision inline sequences for 129 /// some float libcalls (6, 8 or 12 bits). 130 static unsigned LimitFloatPrecision; 131 132 static cl::opt<unsigned, true> 133 LimitFPPrecision("limit-float-precision", 134 cl::desc("Generate low-precision inline sequences " 135 "for some float libcalls"), 136 cl::location(LimitFloatPrecision), cl::Hidden, 137 cl::init(0)); 138 139 static cl::opt<unsigned> SwitchPeelThreshold( 140 "switch-peel-threshold", cl::Hidden, cl::init(66), 141 cl::desc("Set the case probability threshold for peeling the case from a " 142 "switch statement. A value greater than 100 will void this " 143 "optimization")); 144 145 // Limit the width of DAG chains. This is important in general to prevent 146 // DAG-based analysis from blowing up. For example, alias analysis and 147 // load clustering may not complete in reasonable time. It is difficult to 148 // recognize and avoid this situation within each individual analysis, and 149 // future analyses are likely to have the same behavior. Limiting DAG width is 150 // the safe approach and will be especially important with global DAGs. 151 // 152 // MaxParallelChains default is arbitrarily high to avoid affecting 153 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 154 // sequence over this should have been converted to llvm.memcpy by the 155 // frontend. It is easy to induce this behavior with .ll code such as: 156 // %buffer = alloca [4096 x i8] 157 // %data = load [4096 x i8]* %argPtr 158 // store [4096 x i8] %data, [4096 x i8]* %buffer 159 static const unsigned MaxParallelChains = 64; 160 161 // Return the calling convention if the Value passed requires ABI mangling as it 162 // is a parameter to a function or a return value from a function which is not 163 // an intrinsic. 164 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 165 if (auto *R = dyn_cast<ReturnInst>(V)) 166 return R->getParent()->getParent()->getCallingConv(); 167 168 if (auto *CI = dyn_cast<CallInst>(V)) { 169 const bool IsInlineAsm = CI->isInlineAsm(); 170 const bool IsIndirectFunctionCall = 171 !IsInlineAsm && !CI->getCalledFunction(); 172 173 // It is possible that the call instruction is an inline asm statement or an 174 // indirect function call in which case the return value of 175 // getCalledFunction() would be nullptr. 176 const bool IsInstrinsicCall = 177 !IsInlineAsm && !IsIndirectFunctionCall && 178 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 179 180 if (!IsInlineAsm && !IsInstrinsicCall) 181 return CI->getCallingConv(); 182 } 183 184 return None; 185 } 186 187 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 188 const SDValue *Parts, unsigned NumParts, 189 MVT PartVT, EVT ValueVT, const Value *V, 190 Optional<CallingConv::ID> CC); 191 192 /// getCopyFromParts - Create a value that contains the specified legal parts 193 /// combined into the value they represent. If the parts combine to a type 194 /// larger than ValueVT then AssertOp can be used to specify whether the extra 195 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 196 /// (ISD::AssertSext). 197 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 198 const SDValue *Parts, unsigned NumParts, 199 MVT PartVT, EVT ValueVT, const Value *V, 200 Optional<CallingConv::ID> CC = None, 201 Optional<ISD::NodeType> AssertOp = None) { 202 if (ValueVT.isVector()) 203 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 204 CC); 205 206 assert(NumParts > 0 && "No parts to assemble!"); 207 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 208 SDValue Val = Parts[0]; 209 210 if (NumParts > 1) { 211 // Assemble the value from multiple parts. 212 if (ValueVT.isInteger()) { 213 unsigned PartBits = PartVT.getSizeInBits(); 214 unsigned ValueBits = ValueVT.getSizeInBits(); 215 216 // Assemble the power of 2 part. 217 unsigned RoundParts = NumParts & (NumParts - 1) ? 218 1 << Log2_32(NumParts) : NumParts; 219 unsigned RoundBits = PartBits * RoundParts; 220 EVT RoundVT = RoundBits == ValueBits ? 221 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 222 SDValue Lo, Hi; 223 224 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 225 226 if (RoundParts > 2) { 227 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 228 PartVT, HalfVT, V); 229 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 230 RoundParts / 2, PartVT, HalfVT, V); 231 } else { 232 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 233 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 234 } 235 236 if (DAG.getDataLayout().isBigEndian()) 237 std::swap(Lo, Hi); 238 239 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 240 241 if (RoundParts < NumParts) { 242 // Assemble the trailing non-power-of-2 part. 243 unsigned OddParts = NumParts - RoundParts; 244 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 245 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 246 OddVT, V, CC); 247 248 // Combine the round and odd parts. 249 Lo = Val; 250 if (DAG.getDataLayout().isBigEndian()) 251 std::swap(Lo, Hi); 252 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 253 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 254 Hi = 255 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 256 DAG.getConstant(Lo.getValueSizeInBits(), DL, 257 TLI.getPointerTy(DAG.getDataLayout()))); 258 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 259 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 260 } 261 } else if (PartVT.isFloatingPoint()) { 262 // FP split into multiple FP parts (for ppcf128) 263 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 264 "Unexpected split"); 265 SDValue Lo, Hi; 266 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 267 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 268 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 269 std::swap(Lo, Hi); 270 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 271 } else { 272 // FP split into integer parts (soft fp) 273 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 274 !PartVT.isVector() && "Unexpected split"); 275 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 276 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 277 } 278 } 279 280 // There is now one part, held in Val. Correct it to match ValueVT. 281 // PartEVT is the type of the register class that holds the value. 282 // ValueVT is the type of the inline asm operation. 283 EVT PartEVT = Val.getValueType(); 284 285 if (PartEVT == ValueVT) 286 return Val; 287 288 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 289 ValueVT.bitsLT(PartEVT)) { 290 // For an FP value in an integer part, we need to truncate to the right 291 // width first. 292 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 293 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 294 } 295 296 // Handle types that have the same size. 297 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 298 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 299 300 // Handle types with different sizes. 301 if (PartEVT.isInteger() && ValueVT.isInteger()) { 302 if (ValueVT.bitsLT(PartEVT)) { 303 // For a truncate, see if we have any information to 304 // indicate whether the truncated bits will always be 305 // zero or sign-extension. 306 if (AssertOp.hasValue()) 307 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 308 DAG.getValueType(ValueVT)); 309 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 310 } 311 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 312 } 313 314 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 315 // FP_ROUND's are always exact here. 316 if (ValueVT.bitsLT(Val.getValueType())) 317 return DAG.getNode( 318 ISD::FP_ROUND, DL, ValueVT, Val, 319 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 320 321 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 322 } 323 324 llvm_unreachable("Unknown mismatch!"); 325 } 326 327 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 328 const Twine &ErrMsg) { 329 const Instruction *I = dyn_cast_or_null<Instruction>(V); 330 if (!V) 331 return Ctx.emitError(ErrMsg); 332 333 const char *AsmError = ", possible invalid constraint for vector type"; 334 if (const CallInst *CI = dyn_cast<CallInst>(I)) 335 if (isa<InlineAsm>(CI->getCalledValue())) 336 return Ctx.emitError(I, ErrMsg + AsmError); 337 338 return Ctx.emitError(I, ErrMsg); 339 } 340 341 /// getCopyFromPartsVector - Create a value that contains the specified legal 342 /// parts combined into the value they represent. If the parts combine to a 343 /// type larger than ValueVT then AssertOp can be used to specify whether the 344 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 345 /// ValueVT (ISD::AssertSext). 346 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 347 const SDValue *Parts, unsigned NumParts, 348 MVT PartVT, EVT ValueVT, const Value *V, 349 Optional<CallingConv::ID> CallConv) { 350 assert(ValueVT.isVector() && "Not a vector value"); 351 assert(NumParts > 0 && "No parts to assemble!"); 352 const bool IsABIRegCopy = CallConv.hasValue(); 353 354 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 355 SDValue Val = Parts[0]; 356 357 // Handle a multi-element vector. 358 if (NumParts > 1) { 359 EVT IntermediateVT; 360 MVT RegisterVT; 361 unsigned NumIntermediates; 362 unsigned NumRegs; 363 364 if (IsABIRegCopy) { 365 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 366 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 367 NumIntermediates, RegisterVT); 368 } else { 369 NumRegs = 370 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 371 NumIntermediates, RegisterVT); 372 } 373 374 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 375 NumParts = NumRegs; // Silence a compiler warning. 376 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 377 assert(RegisterVT.getSizeInBits() == 378 Parts[0].getSimpleValueType().getSizeInBits() && 379 "Part type sizes don't match!"); 380 381 // Assemble the parts into intermediate operands. 382 SmallVector<SDValue, 8> Ops(NumIntermediates); 383 if (NumIntermediates == NumParts) { 384 // If the register was not expanded, truncate or copy the value, 385 // as appropriate. 386 for (unsigned i = 0; i != NumParts; ++i) 387 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 388 PartVT, IntermediateVT, V); 389 } else if (NumParts > 0) { 390 // If the intermediate type was expanded, build the intermediate 391 // operands from the parts. 392 assert(NumParts % NumIntermediates == 0 && 393 "Must expand into a divisible number of parts!"); 394 unsigned Factor = NumParts / NumIntermediates; 395 for (unsigned i = 0; i != NumIntermediates; ++i) 396 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 397 PartVT, IntermediateVT, V); 398 } 399 400 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 401 // intermediate operands. 402 EVT BuiltVectorTy = 403 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 404 (IntermediateVT.isVector() 405 ? IntermediateVT.getVectorNumElements() * NumParts 406 : NumIntermediates)); 407 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 408 : ISD::BUILD_VECTOR, 409 DL, BuiltVectorTy, Ops); 410 } 411 412 // There is now one part, held in Val. Correct it to match ValueVT. 413 EVT PartEVT = Val.getValueType(); 414 415 if (PartEVT == ValueVT) 416 return Val; 417 418 if (PartEVT.isVector()) { 419 // If the element type of the source/dest vectors are the same, but the 420 // parts vector has more elements than the value vector, then we have a 421 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 422 // elements we want. 423 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 424 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 425 "Cannot narrow, it would be a lossy transformation"); 426 return DAG.getNode( 427 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 428 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 429 } 430 431 // Vector/Vector bitcast. 432 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 433 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 434 435 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 436 "Cannot handle this kind of promotion"); 437 // Promoted vector extract 438 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 439 440 } 441 442 // Trivial bitcast if the types are the same size and the destination 443 // vector type is legal. 444 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 445 TLI.isTypeLegal(ValueVT)) 446 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 447 448 if (ValueVT.getVectorNumElements() != 1) { 449 // Certain ABIs require that vectors are passed as integers. For vectors 450 // are the same size, this is an obvious bitcast. 451 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 452 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 453 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 454 // Bitcast Val back the original type and extract the corresponding 455 // vector we want. 456 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 457 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 458 ValueVT.getVectorElementType(), Elts); 459 Val = DAG.getBitcast(WiderVecType, Val); 460 return DAG.getNode( 461 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 462 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 463 } 464 465 diagnosePossiblyInvalidConstraint( 466 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 467 return DAG.getUNDEF(ValueVT); 468 } 469 470 // Handle cases such as i8 -> <1 x i1> 471 EVT ValueSVT = ValueVT.getVectorElementType(); 472 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 473 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 474 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 475 476 return DAG.getBuildVector(ValueVT, DL, Val); 477 } 478 479 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 480 SDValue Val, SDValue *Parts, unsigned NumParts, 481 MVT PartVT, const Value *V, 482 Optional<CallingConv::ID> CallConv); 483 484 /// getCopyToParts - Create a series of nodes that contain the specified value 485 /// split into legal parts. If the parts contain more bits than Val, then, for 486 /// integers, ExtendKind can be used to specify how to generate the extra bits. 487 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 488 SDValue *Parts, unsigned NumParts, MVT PartVT, 489 const Value *V, 490 Optional<CallingConv::ID> CallConv = None, 491 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 492 EVT ValueVT = Val.getValueType(); 493 494 // Handle the vector case separately. 495 if (ValueVT.isVector()) 496 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 497 CallConv); 498 499 unsigned PartBits = PartVT.getSizeInBits(); 500 unsigned OrigNumParts = NumParts; 501 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 502 "Copying to an illegal type!"); 503 504 if (NumParts == 0) 505 return; 506 507 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 508 EVT PartEVT = PartVT; 509 if (PartEVT == ValueVT) { 510 assert(NumParts == 1 && "No-op copy with multiple parts!"); 511 Parts[0] = Val; 512 return; 513 } 514 515 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 516 // If the parts cover more bits than the value has, promote the value. 517 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 518 assert(NumParts == 1 && "Do not know what to promote to!"); 519 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 520 } else { 521 if (ValueVT.isFloatingPoint()) { 522 // FP values need to be bitcast, then extended if they are being put 523 // into a larger container. 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 525 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 526 } 527 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 528 ValueVT.isInteger() && 529 "Unknown mismatch!"); 530 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 531 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 532 if (PartVT == MVT::x86mmx) 533 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 534 } 535 } else if (PartBits == ValueVT.getSizeInBits()) { 536 // Different types of the same size. 537 assert(NumParts == 1 && PartEVT != ValueVT); 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 540 // If the parts cover less bits than value has, truncate the value. 541 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 542 ValueVT.isInteger() && 543 "Unknown mismatch!"); 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 545 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 546 if (PartVT == MVT::x86mmx) 547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 548 } 549 550 // The value may have changed - recompute ValueVT. 551 ValueVT = Val.getValueType(); 552 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 553 "Failed to tile the value with PartVT!"); 554 555 if (NumParts == 1) { 556 if (PartEVT != ValueVT) { 557 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 558 "scalar-to-vector conversion failed"); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } 561 562 Parts[0] = Val; 563 return; 564 } 565 566 // Expand the value into multiple parts. 567 if (NumParts & (NumParts - 1)) { 568 // The number of parts is not a power of 2. Split off and copy the tail. 569 assert(PartVT.isInteger() && ValueVT.isInteger() && 570 "Do not know what to expand to!"); 571 unsigned RoundParts = 1 << Log2_32(NumParts); 572 unsigned RoundBits = RoundParts * PartBits; 573 unsigned OddParts = NumParts - RoundParts; 574 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 575 DAG.getIntPtrConstant(RoundBits, DL)); 576 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 577 CallConv); 578 579 if (DAG.getDataLayout().isBigEndian()) 580 // The odd parts were reversed by getCopyToParts - unreverse them. 581 std::reverse(Parts + RoundParts, Parts + NumParts); 582 583 NumParts = RoundParts; 584 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 585 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 586 } 587 588 // The number of parts is a power of 2. Repeatedly bisect the value using 589 // EXTRACT_ELEMENT. 590 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 591 EVT::getIntegerVT(*DAG.getContext(), 592 ValueVT.getSizeInBits()), 593 Val); 594 595 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 596 for (unsigned i = 0; i < NumParts; i += StepSize) { 597 unsigned ThisBits = StepSize * PartBits / 2; 598 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 599 SDValue &Part0 = Parts[i]; 600 SDValue &Part1 = Parts[i+StepSize/2]; 601 602 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 603 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 604 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 605 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 606 607 if (ThisBits == PartBits && ThisVT != PartVT) { 608 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 609 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 610 } 611 } 612 } 613 614 if (DAG.getDataLayout().isBigEndian()) 615 std::reverse(Parts, Parts + OrigNumParts); 616 } 617 618 static SDValue widenVectorToPartType(SelectionDAG &DAG, 619 SDValue Val, const SDLoc &DL, EVT PartVT) { 620 if (!PartVT.isVector()) 621 return SDValue(); 622 623 EVT ValueVT = Val.getValueType(); 624 unsigned PartNumElts = PartVT.getVectorNumElements(); 625 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 626 if (PartNumElts > ValueNumElts && 627 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 628 EVT ElementVT = PartVT.getVectorElementType(); 629 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 630 // undef elements. 631 SmallVector<SDValue, 16> Ops; 632 DAG.ExtractVectorElements(Val, Ops); 633 SDValue EltUndef = DAG.getUNDEF(ElementVT); 634 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 635 Ops.push_back(EltUndef); 636 637 // FIXME: Use CONCAT for 2x -> 4x. 638 return DAG.getBuildVector(PartVT, DL, Ops); 639 } 640 641 return SDValue(); 642 } 643 644 /// getCopyToPartsVector - Create a series of nodes that contain the specified 645 /// value split into legal parts. 646 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 647 SDValue Val, SDValue *Parts, unsigned NumParts, 648 MVT PartVT, const Value *V, 649 Optional<CallingConv::ID> CallConv) { 650 EVT ValueVT = Val.getValueType(); 651 assert(ValueVT.isVector() && "Not a vector"); 652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 653 const bool IsABIRegCopy = CallConv.hasValue(); 654 655 if (NumParts == 1) { 656 EVT PartEVT = PartVT; 657 if (PartEVT == ValueVT) { 658 // Nothing to do. 659 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 660 // Bitconvert vector->vector case. 661 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 662 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 663 Val = Widened; 664 } else if (PartVT.isVector() && 665 PartEVT.getVectorElementType().bitsGE( 666 ValueVT.getVectorElementType()) && 667 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 668 669 // Promoted vector extract 670 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 671 } else { 672 if (ValueVT.getVectorNumElements() == 1) { 673 Val = DAG.getNode( 674 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 675 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 676 } else { 677 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 678 "lossy conversion of vector to scalar type"); 679 EVT IntermediateType = 680 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 681 Val = DAG.getBitcast(IntermediateType, Val); 682 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 683 } 684 } 685 686 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 687 Parts[0] = Val; 688 return; 689 } 690 691 // Handle a multi-element vector. 692 EVT IntermediateVT; 693 MVT RegisterVT; 694 unsigned NumIntermediates; 695 unsigned NumRegs; 696 if (IsABIRegCopy) { 697 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 698 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 699 NumIntermediates, RegisterVT); 700 } else { 701 NumRegs = 702 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 703 NumIntermediates, RegisterVT); 704 } 705 706 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 707 NumParts = NumRegs; // Silence a compiler warning. 708 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 709 710 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 711 IntermediateVT.getVectorNumElements() : 1; 712 713 // Convert the vector to the appropiate type if necessary. 714 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 715 716 EVT BuiltVectorTy = EVT::getVectorVT( 717 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 718 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 719 if (ValueVT != BuiltVectorTy) { 720 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 721 Val = Widened; 722 723 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 724 } 725 726 // Split the vector into intermediate operands. 727 SmallVector<SDValue, 8> Ops(NumIntermediates); 728 for (unsigned i = 0; i != NumIntermediates; ++i) { 729 if (IntermediateVT.isVector()) { 730 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 731 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 732 } else { 733 Ops[i] = DAG.getNode( 734 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 735 DAG.getConstant(i, DL, IdxVT)); 736 } 737 } 738 739 // Split the intermediate operands into legal parts. 740 if (NumParts == NumIntermediates) { 741 // If the register was not expanded, promote or copy the value, 742 // as appropriate. 743 for (unsigned i = 0; i != NumParts; ++i) 744 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 745 } else if (NumParts > 0) { 746 // If the intermediate type was expanded, split each the value into 747 // legal parts. 748 assert(NumIntermediates != 0 && "division by zero"); 749 assert(NumParts % NumIntermediates == 0 && 750 "Must expand into a divisible number of parts!"); 751 unsigned Factor = NumParts / NumIntermediates; 752 for (unsigned i = 0; i != NumIntermediates; ++i) 753 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 754 CallConv); 755 } 756 } 757 758 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 759 EVT valuevt, Optional<CallingConv::ID> CC) 760 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 761 RegCount(1, regs.size()), CallConv(CC) {} 762 763 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 764 const DataLayout &DL, unsigned Reg, Type *Ty, 765 Optional<CallingConv::ID> CC) { 766 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 767 768 CallConv = CC; 769 770 for (EVT ValueVT : ValueVTs) { 771 unsigned NumRegs = 772 isABIMangled() 773 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 774 : TLI.getNumRegisters(Context, ValueVT); 775 MVT RegisterVT = 776 isABIMangled() 777 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 778 : TLI.getRegisterType(Context, ValueVT); 779 for (unsigned i = 0; i != NumRegs; ++i) 780 Regs.push_back(Reg + i); 781 RegVTs.push_back(RegisterVT); 782 RegCount.push_back(NumRegs); 783 Reg += NumRegs; 784 } 785 } 786 787 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 788 FunctionLoweringInfo &FuncInfo, 789 const SDLoc &dl, SDValue &Chain, 790 SDValue *Flag, const Value *V) const { 791 // A Value with type {} or [0 x %t] needs no registers. 792 if (ValueVTs.empty()) 793 return SDValue(); 794 795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 796 797 // Assemble the legal parts into the final values. 798 SmallVector<SDValue, 4> Values(ValueVTs.size()); 799 SmallVector<SDValue, 8> Parts; 800 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 801 // Copy the legal parts from the registers. 802 EVT ValueVT = ValueVTs[Value]; 803 unsigned NumRegs = RegCount[Value]; 804 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 805 *DAG.getContext(), 806 CallConv.getValue(), RegVTs[Value]) 807 : RegVTs[Value]; 808 809 Parts.resize(NumRegs); 810 for (unsigned i = 0; i != NumRegs; ++i) { 811 SDValue P; 812 if (!Flag) { 813 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 814 } else { 815 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 816 *Flag = P.getValue(2); 817 } 818 819 Chain = P.getValue(1); 820 Parts[i] = P; 821 822 // If the source register was virtual and if we know something about it, 823 // add an assert node. 824 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 825 !RegisterVT.isInteger()) 826 continue; 827 828 const FunctionLoweringInfo::LiveOutInfo *LOI = 829 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 830 if (!LOI) 831 continue; 832 833 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 834 unsigned NumSignBits = LOI->NumSignBits; 835 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 836 837 if (NumZeroBits == RegSize) { 838 // The current value is a zero. 839 // Explicitly express that as it would be easier for 840 // optimizations to kick in. 841 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 842 continue; 843 } 844 845 // FIXME: We capture more information than the dag can represent. For 846 // now, just use the tightest assertzext/assertsext possible. 847 bool isSExt; 848 EVT FromVT(MVT::Other); 849 if (NumZeroBits) { 850 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 851 isSExt = false; 852 } else if (NumSignBits > 1) { 853 FromVT = 854 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 855 isSExt = true; 856 } else { 857 continue; 858 } 859 // Add an assertion node. 860 assert(FromVT != MVT::Other); 861 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 862 RegisterVT, P, DAG.getValueType(FromVT)); 863 } 864 865 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 866 RegisterVT, ValueVT, V, CallConv); 867 Part += NumRegs; 868 Parts.clear(); 869 } 870 871 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 872 } 873 874 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 875 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 876 const Value *V, 877 ISD::NodeType PreferredExtendType) const { 878 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 879 ISD::NodeType ExtendKind = PreferredExtendType; 880 881 // Get the list of the values's legal parts. 882 unsigned NumRegs = Regs.size(); 883 SmallVector<SDValue, 8> Parts(NumRegs); 884 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 885 unsigned NumParts = RegCount[Value]; 886 887 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 888 *DAG.getContext(), 889 CallConv.getValue(), RegVTs[Value]) 890 : RegVTs[Value]; 891 892 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 893 ExtendKind = ISD::ZERO_EXTEND; 894 895 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 896 NumParts, RegisterVT, V, CallConv, ExtendKind); 897 Part += NumParts; 898 } 899 900 // Copy the parts into the registers. 901 SmallVector<SDValue, 8> Chains(NumRegs); 902 for (unsigned i = 0; i != NumRegs; ++i) { 903 SDValue Part; 904 if (!Flag) { 905 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 906 } else { 907 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 908 *Flag = Part.getValue(1); 909 } 910 911 Chains[i] = Part.getValue(0); 912 } 913 914 if (NumRegs == 1 || Flag) 915 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 916 // flagged to it. That is the CopyToReg nodes and the user are considered 917 // a single scheduling unit. If we create a TokenFactor and return it as 918 // chain, then the TokenFactor is both a predecessor (operand) of the 919 // user as well as a successor (the TF operands are flagged to the user). 920 // c1, f1 = CopyToReg 921 // c2, f2 = CopyToReg 922 // c3 = TokenFactor c1, c2 923 // ... 924 // = op c3, ..., f2 925 Chain = Chains[NumRegs-1]; 926 else 927 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 928 } 929 930 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 931 unsigned MatchingIdx, const SDLoc &dl, 932 SelectionDAG &DAG, 933 std::vector<SDValue> &Ops) const { 934 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 935 936 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 937 if (HasMatching) 938 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 939 else if (!Regs.empty() && 940 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 941 // Put the register class of the virtual registers in the flag word. That 942 // way, later passes can recompute register class constraints for inline 943 // assembly as well as normal instructions. 944 // Don't do this for tied operands that can use the regclass information 945 // from the def. 946 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 947 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 948 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 949 } 950 951 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 952 Ops.push_back(Res); 953 954 if (Code == InlineAsm::Kind_Clobber) { 955 // Clobbers should always have a 1:1 mapping with registers, and may 956 // reference registers that have illegal (e.g. vector) types. Hence, we 957 // shouldn't try to apply any sort of splitting logic to them. 958 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 959 "No 1:1 mapping from clobbers to regs?"); 960 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 961 (void)SP; 962 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 963 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 964 assert( 965 (Regs[I] != SP || 966 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 967 "If we clobbered the stack pointer, MFI should know about it."); 968 } 969 return; 970 } 971 972 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 973 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 974 MVT RegisterVT = RegVTs[Value]; 975 for (unsigned i = 0; i != NumRegs; ++i) { 976 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 977 unsigned TheReg = Regs[Reg++]; 978 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 979 } 980 } 981 } 982 983 SmallVector<std::pair<unsigned, unsigned>, 4> 984 RegsForValue::getRegsAndSizes() const { 985 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 986 unsigned I = 0; 987 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 988 unsigned RegCount = std::get<0>(CountAndVT); 989 MVT RegisterVT = std::get<1>(CountAndVT); 990 unsigned RegisterSize = RegisterVT.getSizeInBits(); 991 for (unsigned E = I + RegCount; I != E; ++I) 992 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 993 } 994 return OutVec; 995 } 996 997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 998 const TargetLibraryInfo *li) { 999 AA = aa; 1000 GFI = gfi; 1001 LibInfo = li; 1002 DL = &DAG.getDataLayout(); 1003 Context = DAG.getContext(); 1004 LPadToCallSiteMap.clear(); 1005 } 1006 1007 void SelectionDAGBuilder::clear() { 1008 NodeMap.clear(); 1009 UnusedArgNodeMap.clear(); 1010 PendingLoads.clear(); 1011 PendingExports.clear(); 1012 CurInst = nullptr; 1013 HasTailCall = false; 1014 SDNodeOrder = LowestSDNodeOrder; 1015 StatepointLowering.clear(); 1016 } 1017 1018 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1019 DanglingDebugInfoMap.clear(); 1020 } 1021 1022 SDValue SelectionDAGBuilder::getRoot() { 1023 if (PendingLoads.empty()) 1024 return DAG.getRoot(); 1025 1026 if (PendingLoads.size() == 1) { 1027 SDValue Root = PendingLoads[0]; 1028 DAG.setRoot(Root); 1029 PendingLoads.clear(); 1030 return Root; 1031 } 1032 1033 // Otherwise, we have to make a token factor node. 1034 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); 1035 PendingLoads.clear(); 1036 DAG.setRoot(Root); 1037 return Root; 1038 } 1039 1040 SDValue SelectionDAGBuilder::getControlRoot() { 1041 SDValue Root = DAG.getRoot(); 1042 1043 if (PendingExports.empty()) 1044 return Root; 1045 1046 // Turn all of the CopyToReg chains into one factored node. 1047 if (Root.getOpcode() != ISD::EntryToken) { 1048 unsigned i = 0, e = PendingExports.size(); 1049 for (; i != e; ++i) { 1050 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1051 if (PendingExports[i].getNode()->getOperand(0) == Root) 1052 break; // Don't add the root if we already indirectly depend on it. 1053 } 1054 1055 if (i == e) 1056 PendingExports.push_back(Root); 1057 } 1058 1059 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1060 PendingExports); 1061 PendingExports.clear(); 1062 DAG.setRoot(Root); 1063 return Root; 1064 } 1065 1066 void SelectionDAGBuilder::visit(const Instruction &I) { 1067 // Set up outgoing PHI node register values before emitting the terminator. 1068 if (I.isTerminator()) { 1069 HandlePHINodesInSuccessorBlocks(I.getParent()); 1070 } 1071 1072 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1073 if (!isa<DbgInfoIntrinsic>(I)) 1074 ++SDNodeOrder; 1075 1076 CurInst = &I; 1077 1078 visit(I.getOpcode(), I); 1079 1080 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1081 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1082 // maps to this instruction. 1083 // TODO: We could handle all flags (nsw, etc) here. 1084 // TODO: If an IR instruction maps to >1 node, only the final node will have 1085 // flags set. 1086 if (SDNode *Node = getNodeForIRValue(&I)) { 1087 SDNodeFlags IncomingFlags; 1088 IncomingFlags.copyFMF(*FPMO); 1089 if (!Node->getFlags().isDefined()) 1090 Node->setFlags(IncomingFlags); 1091 else 1092 Node->intersectFlagsWith(IncomingFlags); 1093 } 1094 } 1095 1096 if (!I.isTerminator() && !HasTailCall && 1097 !isStatepoint(&I)) // statepoints handle their exports internally 1098 CopyToExportRegsIfNeeded(&I); 1099 1100 CurInst = nullptr; 1101 } 1102 1103 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1104 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1105 } 1106 1107 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1108 // Note: this doesn't use InstVisitor, because it has to work with 1109 // ConstantExpr's in addition to instructions. 1110 switch (Opcode) { 1111 default: llvm_unreachable("Unknown instruction type encountered!"); 1112 // Build the switch statement using the Instruction.def file. 1113 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1114 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1115 #include "llvm/IR/Instruction.def" 1116 } 1117 } 1118 1119 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1120 const DIExpression *Expr) { 1121 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1122 const DbgValueInst *DI = DDI.getDI(); 1123 DIVariable *DanglingVariable = DI->getVariable(); 1124 DIExpression *DanglingExpr = DI->getExpression(); 1125 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1126 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1127 return true; 1128 } 1129 return false; 1130 }; 1131 1132 for (auto &DDIMI : DanglingDebugInfoMap) { 1133 DanglingDebugInfoVector &DDIV = DDIMI.second; 1134 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1135 } 1136 } 1137 1138 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1139 // generate the debug data structures now that we've seen its definition. 1140 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1141 SDValue Val) { 1142 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1143 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1144 return; 1145 1146 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1147 for (auto &DDI : DDIV) { 1148 const DbgValueInst *DI = DDI.getDI(); 1149 assert(DI && "Ill-formed DanglingDebugInfo"); 1150 DebugLoc dl = DDI.getdl(); 1151 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1152 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1153 DILocalVariable *Variable = DI->getVariable(); 1154 DIExpression *Expr = DI->getExpression(); 1155 assert(Variable->isValidLocationForIntrinsic(dl) && 1156 "Expected inlined-at fields to agree"); 1157 SDDbgValue *SDV; 1158 if (Val.getNode()) { 1159 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1160 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1161 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1162 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1163 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1164 // inserted after the definition of Val when emitting the instructions 1165 // after ISel. An alternative could be to teach 1166 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1167 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1168 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1169 << ValSDNodeOrder << "\n"); 1170 SDV = getDbgValue(Val, Variable, Expr, dl, 1171 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1172 DAG.AddDbgValue(SDV, Val.getNode(), false); 1173 } else 1174 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1175 << "in EmitFuncArgumentDbgValue\n"); 1176 } else 1177 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1178 } 1179 DDIV.clear(); 1180 } 1181 1182 /// getCopyFromRegs - If there was virtual register allocated for the value V 1183 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1184 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1185 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1186 SDValue Result; 1187 1188 if (It != FuncInfo.ValueMap.end()) { 1189 unsigned InReg = It->second; 1190 1191 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1192 DAG.getDataLayout(), InReg, Ty, 1193 None); // This is not an ABI copy. 1194 SDValue Chain = DAG.getEntryNode(); 1195 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1196 V); 1197 resolveDanglingDebugInfo(V, Result); 1198 } 1199 1200 return Result; 1201 } 1202 1203 /// getValue - Return an SDValue for the given Value. 1204 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1205 // If we already have an SDValue for this value, use it. It's important 1206 // to do this first, so that we don't create a CopyFromReg if we already 1207 // have a regular SDValue. 1208 SDValue &N = NodeMap[V]; 1209 if (N.getNode()) return N; 1210 1211 // If there's a virtual register allocated and initialized for this 1212 // value, use it. 1213 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1214 return copyFromReg; 1215 1216 // Otherwise create a new SDValue and remember it. 1217 SDValue Val = getValueImpl(V); 1218 NodeMap[V] = Val; 1219 resolveDanglingDebugInfo(V, Val); 1220 return Val; 1221 } 1222 1223 // Return true if SDValue exists for the given Value 1224 bool SelectionDAGBuilder::findValue(const Value *V) const { 1225 return (NodeMap.find(V) != NodeMap.end()) || 1226 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1227 } 1228 1229 /// getNonRegisterValue - Return an SDValue for the given Value, but 1230 /// don't look in FuncInfo.ValueMap for a virtual register. 1231 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1232 // If we already have an SDValue for this value, use it. 1233 SDValue &N = NodeMap[V]; 1234 if (N.getNode()) { 1235 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1236 // Remove the debug location from the node as the node is about to be used 1237 // in a location which may differ from the original debug location. This 1238 // is relevant to Constant and ConstantFP nodes because they can appear 1239 // as constant expressions inside PHI nodes. 1240 N->setDebugLoc(DebugLoc()); 1241 } 1242 return N; 1243 } 1244 1245 // Otherwise create a new SDValue and remember it. 1246 SDValue Val = getValueImpl(V); 1247 NodeMap[V] = Val; 1248 resolveDanglingDebugInfo(V, Val); 1249 return Val; 1250 } 1251 1252 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1253 /// Create an SDValue for the given value. 1254 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1255 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1256 1257 if (const Constant *C = dyn_cast<Constant>(V)) { 1258 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1259 1260 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1261 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1262 1263 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1264 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1265 1266 if (isa<ConstantPointerNull>(C)) { 1267 unsigned AS = V->getType()->getPointerAddressSpace(); 1268 return DAG.getConstant(0, getCurSDLoc(), 1269 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1270 } 1271 1272 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1273 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1274 1275 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1276 return DAG.getUNDEF(VT); 1277 1278 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1279 visit(CE->getOpcode(), *CE); 1280 SDValue N1 = NodeMap[V]; 1281 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1282 return N1; 1283 } 1284 1285 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1286 SmallVector<SDValue, 4> Constants; 1287 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1288 OI != OE; ++OI) { 1289 SDNode *Val = getValue(*OI).getNode(); 1290 // If the operand is an empty aggregate, there are no values. 1291 if (!Val) continue; 1292 // Add each leaf value from the operand to the Constants list 1293 // to form a flattened list of all the values. 1294 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1295 Constants.push_back(SDValue(Val, i)); 1296 } 1297 1298 return DAG.getMergeValues(Constants, getCurSDLoc()); 1299 } 1300 1301 if (const ConstantDataSequential *CDS = 1302 dyn_cast<ConstantDataSequential>(C)) { 1303 SmallVector<SDValue, 4> Ops; 1304 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1305 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1306 // Add each leaf value from the operand to the Constants list 1307 // to form a flattened list of all the values. 1308 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1309 Ops.push_back(SDValue(Val, i)); 1310 } 1311 1312 if (isa<ArrayType>(CDS->getType())) 1313 return DAG.getMergeValues(Ops, getCurSDLoc()); 1314 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1315 } 1316 1317 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1318 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1319 "Unknown struct or array constant!"); 1320 1321 SmallVector<EVT, 4> ValueVTs; 1322 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1323 unsigned NumElts = ValueVTs.size(); 1324 if (NumElts == 0) 1325 return SDValue(); // empty struct 1326 SmallVector<SDValue, 4> Constants(NumElts); 1327 for (unsigned i = 0; i != NumElts; ++i) { 1328 EVT EltVT = ValueVTs[i]; 1329 if (isa<UndefValue>(C)) 1330 Constants[i] = DAG.getUNDEF(EltVT); 1331 else if (EltVT.isFloatingPoint()) 1332 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1333 else 1334 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1335 } 1336 1337 return DAG.getMergeValues(Constants, getCurSDLoc()); 1338 } 1339 1340 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1341 return DAG.getBlockAddress(BA, VT); 1342 1343 VectorType *VecTy = cast<VectorType>(V->getType()); 1344 unsigned NumElements = VecTy->getNumElements(); 1345 1346 // Now that we know the number and type of the elements, get that number of 1347 // elements into the Ops array based on what kind of constant it is. 1348 SmallVector<SDValue, 16> Ops; 1349 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1350 for (unsigned i = 0; i != NumElements; ++i) 1351 Ops.push_back(getValue(CV->getOperand(i))); 1352 } else { 1353 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1354 EVT EltVT = 1355 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1356 1357 SDValue Op; 1358 if (EltVT.isFloatingPoint()) 1359 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1360 else 1361 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1362 Ops.assign(NumElements, Op); 1363 } 1364 1365 // Create a BUILD_VECTOR node. 1366 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1367 } 1368 1369 // If this is a static alloca, generate it as the frameindex instead of 1370 // computation. 1371 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1372 DenseMap<const AllocaInst*, int>::iterator SI = 1373 FuncInfo.StaticAllocaMap.find(AI); 1374 if (SI != FuncInfo.StaticAllocaMap.end()) 1375 return DAG.getFrameIndex(SI->second, 1376 TLI.getFrameIndexTy(DAG.getDataLayout())); 1377 } 1378 1379 // If this is an instruction which fast-isel has deferred, select it now. 1380 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1381 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1382 1383 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1384 Inst->getType(), getABIRegCopyCC(V)); 1385 SDValue Chain = DAG.getEntryNode(); 1386 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1387 } 1388 1389 llvm_unreachable("Can't get register for value!"); 1390 } 1391 1392 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1393 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1394 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1395 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1396 bool IsSEH = isAsynchronousEHPersonality(Pers); 1397 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1398 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1399 if (!IsSEH) 1400 CatchPadMBB->setIsEHScopeEntry(); 1401 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1402 if (IsMSVCCXX || IsCoreCLR) 1403 CatchPadMBB->setIsEHFuncletEntry(); 1404 // Wasm does not need catchpads anymore 1405 if (!IsWasmCXX) 1406 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1407 getControlRoot())); 1408 } 1409 1410 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1411 // Update machine-CFG edge. 1412 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1413 FuncInfo.MBB->addSuccessor(TargetMBB); 1414 1415 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1416 bool IsSEH = isAsynchronousEHPersonality(Pers); 1417 if (IsSEH) { 1418 // If this is not a fall-through branch or optimizations are switched off, 1419 // emit the branch. 1420 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1421 TM.getOptLevel() == CodeGenOpt::None) 1422 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1423 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1424 return; 1425 } 1426 1427 // Figure out the funclet membership for the catchret's successor. 1428 // This will be used by the FuncletLayout pass to determine how to order the 1429 // BB's. 1430 // A 'catchret' returns to the outer scope's color. 1431 Value *ParentPad = I.getCatchSwitchParentPad(); 1432 const BasicBlock *SuccessorColor; 1433 if (isa<ConstantTokenNone>(ParentPad)) 1434 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1435 else 1436 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1437 assert(SuccessorColor && "No parent funclet for catchret!"); 1438 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1439 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1440 1441 // Create the terminator node. 1442 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1443 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1444 DAG.getBasicBlock(SuccessorColorMBB)); 1445 DAG.setRoot(Ret); 1446 } 1447 1448 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1449 // Don't emit any special code for the cleanuppad instruction. It just marks 1450 // the start of an EH scope/funclet. 1451 FuncInfo.MBB->setIsEHScopeEntry(); 1452 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1453 if (Pers != EHPersonality::Wasm_CXX) { 1454 FuncInfo.MBB->setIsEHFuncletEntry(); 1455 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1456 } 1457 } 1458 1459 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1460 /// many places it could ultimately go. In the IR, we have a single unwind 1461 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1462 /// This function skips over imaginary basic blocks that hold catchswitch 1463 /// instructions, and finds all the "real" machine 1464 /// basic block destinations. As those destinations may not be successors of 1465 /// EHPadBB, here we also calculate the edge probability to those destinations. 1466 /// The passed-in Prob is the edge probability to EHPadBB. 1467 static void findUnwindDestinations( 1468 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1469 BranchProbability Prob, 1470 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1471 &UnwindDests) { 1472 EHPersonality Personality = 1473 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1474 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1475 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1476 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1477 bool IsSEH = isAsynchronousEHPersonality(Personality); 1478 1479 while (EHPadBB) { 1480 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1481 BasicBlock *NewEHPadBB = nullptr; 1482 if (isa<LandingPadInst>(Pad)) { 1483 // Stop on landingpads. They are not funclets. 1484 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1485 break; 1486 } else if (isa<CleanupPadInst>(Pad)) { 1487 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1488 // personalities. 1489 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1490 UnwindDests.back().first->setIsEHScopeEntry(); 1491 if (!IsWasmCXX) 1492 UnwindDests.back().first->setIsEHFuncletEntry(); 1493 break; 1494 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1495 // Add the catchpad handlers to the possible destinations. 1496 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1497 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1498 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1499 if (IsMSVCCXX || IsCoreCLR) 1500 UnwindDests.back().first->setIsEHFuncletEntry(); 1501 if (!IsSEH) 1502 UnwindDests.back().first->setIsEHScopeEntry(); 1503 } 1504 NewEHPadBB = CatchSwitch->getUnwindDest(); 1505 } else { 1506 continue; 1507 } 1508 1509 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1510 if (BPI && NewEHPadBB) 1511 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1512 EHPadBB = NewEHPadBB; 1513 } 1514 } 1515 1516 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1517 // Update successor info. 1518 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1519 auto UnwindDest = I.getUnwindDest(); 1520 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1521 BranchProbability UnwindDestProb = 1522 (BPI && UnwindDest) 1523 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1524 : BranchProbability::getZero(); 1525 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1526 for (auto &UnwindDest : UnwindDests) { 1527 UnwindDest.first->setIsEHPad(); 1528 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1529 } 1530 FuncInfo.MBB->normalizeSuccProbs(); 1531 1532 // Create the terminator node. 1533 SDValue Ret = 1534 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1535 DAG.setRoot(Ret); 1536 } 1537 1538 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1539 report_fatal_error("visitCatchSwitch not yet implemented!"); 1540 } 1541 1542 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1543 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1544 auto &DL = DAG.getDataLayout(); 1545 SDValue Chain = getControlRoot(); 1546 SmallVector<ISD::OutputArg, 8> Outs; 1547 SmallVector<SDValue, 8> OutVals; 1548 1549 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1550 // lower 1551 // 1552 // %val = call <ty> @llvm.experimental.deoptimize() 1553 // ret <ty> %val 1554 // 1555 // differently. 1556 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1557 LowerDeoptimizingReturn(); 1558 return; 1559 } 1560 1561 if (!FuncInfo.CanLowerReturn) { 1562 unsigned DemoteReg = FuncInfo.DemoteRegister; 1563 const Function *F = I.getParent()->getParent(); 1564 1565 // Emit a store of the return value through the virtual register. 1566 // Leave Outs empty so that LowerReturn won't try to load return 1567 // registers the usual way. 1568 SmallVector<EVT, 1> PtrValueVTs; 1569 ComputeValueVTs(TLI, DL, 1570 F->getReturnType()->getPointerTo( 1571 DAG.getDataLayout().getAllocaAddrSpace()), 1572 PtrValueVTs); 1573 1574 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1575 DemoteReg, PtrValueVTs[0]); 1576 SDValue RetOp = getValue(I.getOperand(0)); 1577 1578 SmallVector<EVT, 4> ValueVTs; 1579 SmallVector<uint64_t, 4> Offsets; 1580 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1581 unsigned NumValues = ValueVTs.size(); 1582 1583 SmallVector<SDValue, 4> Chains(NumValues); 1584 for (unsigned i = 0; i != NumValues; ++i) { 1585 // An aggregate return value cannot wrap around the address space, so 1586 // offsets to its parts don't wrap either. 1587 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1588 Chains[i] = DAG.getStore( 1589 Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1590 // FIXME: better loc info would be nice. 1591 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1592 } 1593 1594 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1595 MVT::Other, Chains); 1596 } else if (I.getNumOperands() != 0) { 1597 SmallVector<EVT, 4> ValueVTs; 1598 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1599 unsigned NumValues = ValueVTs.size(); 1600 if (NumValues) { 1601 SDValue RetOp = getValue(I.getOperand(0)); 1602 1603 const Function *F = I.getParent()->getParent(); 1604 1605 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1606 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1607 Attribute::SExt)) 1608 ExtendKind = ISD::SIGN_EXTEND; 1609 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1610 Attribute::ZExt)) 1611 ExtendKind = ISD::ZERO_EXTEND; 1612 1613 LLVMContext &Context = F->getContext(); 1614 bool RetInReg = F->getAttributes().hasAttribute( 1615 AttributeList::ReturnIndex, Attribute::InReg); 1616 1617 for (unsigned j = 0; j != NumValues; ++j) { 1618 EVT VT = ValueVTs[j]; 1619 1620 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1621 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1622 1623 CallingConv::ID CC = F->getCallingConv(); 1624 1625 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1626 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1627 SmallVector<SDValue, 4> Parts(NumParts); 1628 getCopyToParts(DAG, getCurSDLoc(), 1629 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1630 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1631 1632 // 'inreg' on function refers to return value 1633 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1634 if (RetInReg) 1635 Flags.setInReg(); 1636 1637 // Propagate extension type if any 1638 if (ExtendKind == ISD::SIGN_EXTEND) 1639 Flags.setSExt(); 1640 else if (ExtendKind == ISD::ZERO_EXTEND) 1641 Flags.setZExt(); 1642 1643 for (unsigned i = 0; i < NumParts; ++i) { 1644 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1645 VT, /*isfixed=*/true, 0, 0)); 1646 OutVals.push_back(Parts[i]); 1647 } 1648 } 1649 } 1650 } 1651 1652 // Push in swifterror virtual register as the last element of Outs. This makes 1653 // sure swifterror virtual register will be returned in the swifterror 1654 // physical register. 1655 const Function *F = I.getParent()->getParent(); 1656 if (TLI.supportSwiftError() && 1657 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1658 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument"); 1659 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1660 Flags.setSwiftError(); 1661 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1662 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1663 true /*isfixed*/, 1 /*origidx*/, 1664 0 /*partOffs*/)); 1665 // Create SDNode for the swifterror virtual register. 1666 OutVals.push_back( 1667 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt( 1668 &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first, 1669 EVT(TLI.getPointerTy(DL)))); 1670 } 1671 1672 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1673 CallingConv::ID CallConv = 1674 DAG.getMachineFunction().getFunction().getCallingConv(); 1675 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1676 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1677 1678 // Verify that the target's LowerReturn behaved as expected. 1679 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1680 "LowerReturn didn't return a valid chain!"); 1681 1682 // Update the DAG with the new chain value resulting from return lowering. 1683 DAG.setRoot(Chain); 1684 } 1685 1686 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1687 /// created for it, emit nodes to copy the value into the virtual 1688 /// registers. 1689 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1690 // Skip empty types 1691 if (V->getType()->isEmptyTy()) 1692 return; 1693 1694 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1695 if (VMI != FuncInfo.ValueMap.end()) { 1696 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1697 CopyValueToVirtualRegister(V, VMI->second); 1698 } 1699 } 1700 1701 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1702 /// the current basic block, add it to ValueMap now so that we'll get a 1703 /// CopyTo/FromReg. 1704 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1705 // No need to export constants. 1706 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1707 1708 // Already exported? 1709 if (FuncInfo.isExportedInst(V)) return; 1710 1711 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1712 CopyValueToVirtualRegister(V, Reg); 1713 } 1714 1715 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1716 const BasicBlock *FromBB) { 1717 // The operands of the setcc have to be in this block. We don't know 1718 // how to export them from some other block. 1719 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1720 // Can export from current BB. 1721 if (VI->getParent() == FromBB) 1722 return true; 1723 1724 // Is already exported, noop. 1725 return FuncInfo.isExportedInst(V); 1726 } 1727 1728 // If this is an argument, we can export it if the BB is the entry block or 1729 // if it is already exported. 1730 if (isa<Argument>(V)) { 1731 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1732 return true; 1733 1734 // Otherwise, can only export this if it is already exported. 1735 return FuncInfo.isExportedInst(V); 1736 } 1737 1738 // Otherwise, constants can always be exported. 1739 return true; 1740 } 1741 1742 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1743 BranchProbability 1744 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1745 const MachineBasicBlock *Dst) const { 1746 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1747 const BasicBlock *SrcBB = Src->getBasicBlock(); 1748 const BasicBlock *DstBB = Dst->getBasicBlock(); 1749 if (!BPI) { 1750 // If BPI is not available, set the default probability as 1 / N, where N is 1751 // the number of successors. 1752 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1753 return BranchProbability(1, SuccSize); 1754 } 1755 return BPI->getEdgeProbability(SrcBB, DstBB); 1756 } 1757 1758 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1759 MachineBasicBlock *Dst, 1760 BranchProbability Prob) { 1761 if (!FuncInfo.BPI) 1762 Src->addSuccessorWithoutProb(Dst); 1763 else { 1764 if (Prob.isUnknown()) 1765 Prob = getEdgeProbability(Src, Dst); 1766 Src->addSuccessor(Dst, Prob); 1767 } 1768 } 1769 1770 static bool InBlock(const Value *V, const BasicBlock *BB) { 1771 if (const Instruction *I = dyn_cast<Instruction>(V)) 1772 return I->getParent() == BB; 1773 return true; 1774 } 1775 1776 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1777 /// This function emits a branch and is used at the leaves of an OR or an 1778 /// AND operator tree. 1779 void 1780 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1781 MachineBasicBlock *TBB, 1782 MachineBasicBlock *FBB, 1783 MachineBasicBlock *CurBB, 1784 MachineBasicBlock *SwitchBB, 1785 BranchProbability TProb, 1786 BranchProbability FProb, 1787 bool InvertCond) { 1788 const BasicBlock *BB = CurBB->getBasicBlock(); 1789 1790 // If the leaf of the tree is a comparison, merge the condition into 1791 // the caseblock. 1792 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1793 // The operands of the cmp have to be in this block. We don't know 1794 // how to export them from some other block. If this is the first block 1795 // of the sequence, no exporting is needed. 1796 if (CurBB == SwitchBB || 1797 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1798 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1799 ISD::CondCode Condition; 1800 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1801 ICmpInst::Predicate Pred = 1802 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 1803 Condition = getICmpCondCode(Pred); 1804 } else { 1805 const FCmpInst *FC = cast<FCmpInst>(Cond); 1806 FCmpInst::Predicate Pred = 1807 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 1808 Condition = getFCmpCondCode(Pred); 1809 if (TM.Options.NoNaNsFPMath) 1810 Condition = getFCmpCodeWithoutNaN(Condition); 1811 } 1812 1813 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 1814 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1815 SwitchCases.push_back(CB); 1816 return; 1817 } 1818 } 1819 1820 // Create a CaseBlock record representing this branch. 1821 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 1822 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 1823 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1824 SwitchCases.push_back(CB); 1825 } 1826 1827 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1828 MachineBasicBlock *TBB, 1829 MachineBasicBlock *FBB, 1830 MachineBasicBlock *CurBB, 1831 MachineBasicBlock *SwitchBB, 1832 Instruction::BinaryOps Opc, 1833 BranchProbability TProb, 1834 BranchProbability FProb, 1835 bool InvertCond) { 1836 // Skip over not part of the tree and remember to invert op and operands at 1837 // next level. 1838 Value *NotCond; 1839 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 1840 InBlock(NotCond, CurBB->getBasicBlock())) { 1841 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 1842 !InvertCond); 1843 return; 1844 } 1845 1846 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1847 // Compute the effective opcode for Cond, taking into account whether it needs 1848 // to be inverted, e.g. 1849 // and (not (or A, B)), C 1850 // gets lowered as 1851 // and (and (not A, not B), C) 1852 unsigned BOpc = 0; 1853 if (BOp) { 1854 BOpc = BOp->getOpcode(); 1855 if (InvertCond) { 1856 if (BOpc == Instruction::And) 1857 BOpc = Instruction::Or; 1858 else if (BOpc == Instruction::Or) 1859 BOpc = Instruction::And; 1860 } 1861 } 1862 1863 // If this node is not part of the or/and tree, emit it as a branch. 1864 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1865 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 1866 BOp->getParent() != CurBB->getBasicBlock() || 1867 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1868 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1869 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 1870 TProb, FProb, InvertCond); 1871 return; 1872 } 1873 1874 // Create TmpBB after CurBB. 1875 MachineFunction::iterator BBI(CurBB); 1876 MachineFunction &MF = DAG.getMachineFunction(); 1877 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1878 CurBB->getParent()->insert(++BBI, TmpBB); 1879 1880 if (Opc == Instruction::Or) { 1881 // Codegen X | Y as: 1882 // BB1: 1883 // jmp_if_X TBB 1884 // jmp TmpBB 1885 // TmpBB: 1886 // jmp_if_Y TBB 1887 // jmp FBB 1888 // 1889 1890 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1891 // The requirement is that 1892 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 1893 // = TrueProb for original BB. 1894 // Assuming the original probabilities are A and B, one choice is to set 1895 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 1896 // A/(1+B) and 2B/(1+B). This choice assumes that 1897 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 1898 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 1899 // TmpBB, but the math is more complicated. 1900 1901 auto NewTrueProb = TProb / 2; 1902 auto NewFalseProb = TProb / 2 + FProb; 1903 // Emit the LHS condition. 1904 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 1905 NewTrueProb, NewFalseProb, InvertCond); 1906 1907 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 1908 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 1909 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1910 // Emit the RHS condition into TmpBB. 1911 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1912 Probs[0], Probs[1], InvertCond); 1913 } else { 1914 assert(Opc == Instruction::And && "Unknown merge op!"); 1915 // Codegen X & Y as: 1916 // BB1: 1917 // jmp_if_X TmpBB 1918 // jmp FBB 1919 // TmpBB: 1920 // jmp_if_Y TBB 1921 // jmp FBB 1922 // 1923 // This requires creation of TmpBB after CurBB. 1924 1925 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1926 // The requirement is that 1927 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 1928 // = FalseProb for original BB. 1929 // Assuming the original probabilities are A and B, one choice is to set 1930 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 1931 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 1932 // TrueProb for BB1 * FalseProb for TmpBB. 1933 1934 auto NewTrueProb = TProb + FProb / 2; 1935 auto NewFalseProb = FProb / 2; 1936 // Emit the LHS condition. 1937 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 1938 NewTrueProb, NewFalseProb, InvertCond); 1939 1940 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 1941 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 1942 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1943 // Emit the RHS condition into TmpBB. 1944 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1945 Probs[0], Probs[1], InvertCond); 1946 } 1947 } 1948 1949 /// If the set of cases should be emitted as a series of branches, return true. 1950 /// If we should emit this as a bunch of and/or'd together conditions, return 1951 /// false. 1952 bool 1953 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1954 if (Cases.size() != 2) return true; 1955 1956 // If this is two comparisons of the same values or'd or and'd together, they 1957 // will get folded into a single comparison, so don't emit two blocks. 1958 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1959 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1960 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1961 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1962 return false; 1963 } 1964 1965 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1966 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1967 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1968 Cases[0].CC == Cases[1].CC && 1969 isa<Constant>(Cases[0].CmpRHS) && 1970 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1971 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1972 return false; 1973 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1974 return false; 1975 } 1976 1977 return true; 1978 } 1979 1980 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1981 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1982 1983 // Update machine-CFG edges. 1984 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1985 1986 if (I.isUnconditional()) { 1987 // Update machine-CFG edges. 1988 BrMBB->addSuccessor(Succ0MBB); 1989 1990 // If this is not a fall-through branch or optimizations are switched off, 1991 // emit the branch. 1992 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 1993 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 1994 MVT::Other, getControlRoot(), 1995 DAG.getBasicBlock(Succ0MBB))); 1996 1997 return; 1998 } 1999 2000 // If this condition is one of the special cases we handle, do special stuff 2001 // now. 2002 const Value *CondVal = I.getCondition(); 2003 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2004 2005 // If this is a series of conditions that are or'd or and'd together, emit 2006 // this as a sequence of branches instead of setcc's with and/or operations. 2007 // As long as jumps are not expensive, this should improve performance. 2008 // For example, instead of something like: 2009 // cmp A, B 2010 // C = seteq 2011 // cmp D, E 2012 // F = setle 2013 // or C, F 2014 // jnz foo 2015 // Emit: 2016 // cmp A, B 2017 // je foo 2018 // cmp D, E 2019 // jle foo 2020 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2021 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2022 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2023 !I.getMetadata(LLVMContext::MD_unpredictable) && 2024 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2025 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2026 Opcode, 2027 getEdgeProbability(BrMBB, Succ0MBB), 2028 getEdgeProbability(BrMBB, Succ1MBB), 2029 /*InvertCond=*/false); 2030 // If the compares in later blocks need to use values not currently 2031 // exported from this block, export them now. This block should always 2032 // be the first entry. 2033 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2034 2035 // Allow some cases to be rejected. 2036 if (ShouldEmitAsBranches(SwitchCases)) { 2037 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 2038 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 2039 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 2040 } 2041 2042 // Emit the branch for this block. 2043 visitSwitchCase(SwitchCases[0], BrMBB); 2044 SwitchCases.erase(SwitchCases.begin()); 2045 return; 2046 } 2047 2048 // Okay, we decided not to do this, remove any inserted MBB's and clear 2049 // SwitchCases. 2050 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 2051 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 2052 2053 SwitchCases.clear(); 2054 } 2055 } 2056 2057 // Create a CaseBlock record representing this branch. 2058 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2059 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2060 2061 // Use visitSwitchCase to actually insert the fast branch sequence for this 2062 // cond branch. 2063 visitSwitchCase(CB, BrMBB); 2064 } 2065 2066 /// visitSwitchCase - Emits the necessary code to represent a single node in 2067 /// the binary search tree resulting from lowering a switch instruction. 2068 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2069 MachineBasicBlock *SwitchBB) { 2070 SDValue Cond; 2071 SDValue CondLHS = getValue(CB.CmpLHS); 2072 SDLoc dl = CB.DL; 2073 2074 // Build the setcc now. 2075 if (!CB.CmpMHS) { 2076 // Fold "(X == true)" to X and "(X == false)" to !X to 2077 // handle common cases produced by branch lowering. 2078 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2079 CB.CC == ISD::SETEQ) 2080 Cond = CondLHS; 2081 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2082 CB.CC == ISD::SETEQ) { 2083 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2084 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2085 } else 2086 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 2087 } else { 2088 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2089 2090 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2091 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2092 2093 SDValue CmpOp = getValue(CB.CmpMHS); 2094 EVT VT = CmpOp.getValueType(); 2095 2096 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2097 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2098 ISD::SETLE); 2099 } else { 2100 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2101 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2102 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2103 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2104 } 2105 } 2106 2107 // Update successor info 2108 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2109 // TrueBB and FalseBB are always different unless the incoming IR is 2110 // degenerate. This only happens when running llc on weird IR. 2111 if (CB.TrueBB != CB.FalseBB) 2112 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2113 SwitchBB->normalizeSuccProbs(); 2114 2115 // If the lhs block is the next block, invert the condition so that we can 2116 // fall through to the lhs instead of the rhs block. 2117 if (CB.TrueBB == NextBlock(SwitchBB)) { 2118 std::swap(CB.TrueBB, CB.FalseBB); 2119 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2120 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2121 } 2122 2123 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2124 MVT::Other, getControlRoot(), Cond, 2125 DAG.getBasicBlock(CB.TrueBB)); 2126 2127 // Insert the false branch. Do this even if it's a fall through branch, 2128 // this makes it easier to do DAG optimizations which require inverting 2129 // the branch condition. 2130 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2131 DAG.getBasicBlock(CB.FalseBB)); 2132 2133 DAG.setRoot(BrCond); 2134 } 2135 2136 /// visitJumpTable - Emit JumpTable node in the current MBB 2137 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 2138 // Emit the code for the jump table 2139 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2140 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2141 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2142 JT.Reg, PTy); 2143 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2144 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2145 MVT::Other, Index.getValue(1), 2146 Table, Index); 2147 DAG.setRoot(BrJumpTable); 2148 } 2149 2150 /// visitJumpTableHeader - This function emits necessary code to produce index 2151 /// in the JumpTable from switch case. 2152 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 2153 JumpTableHeader &JTH, 2154 MachineBasicBlock *SwitchBB) { 2155 SDLoc dl = getCurSDLoc(); 2156 2157 // Subtract the lowest switch case value from the value being switched on and 2158 // conditional branch to default mbb if the result is greater than the 2159 // difference between smallest and largest cases. 2160 SDValue SwitchOp = getValue(JTH.SValue); 2161 EVT VT = SwitchOp.getValueType(); 2162 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2163 DAG.getConstant(JTH.First, dl, VT)); 2164 2165 // The SDNode we just created, which holds the value being switched on minus 2166 // the smallest case value, needs to be copied to a virtual register so it 2167 // can be used as an index into the jump table in a subsequent basic block. 2168 // This value may be smaller or larger than the target's pointer type, and 2169 // therefore require extension or truncating. 2170 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2171 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2172 2173 unsigned JumpTableReg = 2174 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2175 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2176 JumpTableReg, SwitchOp); 2177 JT.Reg = JumpTableReg; 2178 2179 // Emit the range check for the jump table, and branch to the default block 2180 // for the switch statement if the value being switched on exceeds the largest 2181 // case in the switch. 2182 SDValue CMP = DAG.getSetCC( 2183 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2184 Sub.getValueType()), 2185 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2186 2187 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2188 MVT::Other, CopyTo, CMP, 2189 DAG.getBasicBlock(JT.Default)); 2190 2191 // Avoid emitting unnecessary branches to the next block. 2192 if (JT.MBB != NextBlock(SwitchBB)) 2193 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2194 DAG.getBasicBlock(JT.MBB)); 2195 2196 DAG.setRoot(BrCond); 2197 } 2198 2199 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2200 /// variable if there exists one. 2201 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2202 SDValue &Chain) { 2203 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2204 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2205 MachineFunction &MF = DAG.getMachineFunction(); 2206 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2207 MachineSDNode *Node = 2208 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2209 if (Global) { 2210 MachinePointerInfo MPInfo(Global); 2211 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2212 MachineMemOperand::MODereferenceable; 2213 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2214 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2215 DAG.setNodeMemRefs(Node, {MemRef}); 2216 } 2217 return SDValue(Node, 0); 2218 } 2219 2220 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2221 /// tail spliced into a stack protector check success bb. 2222 /// 2223 /// For a high level explanation of how this fits into the stack protector 2224 /// generation see the comment on the declaration of class 2225 /// StackProtectorDescriptor. 2226 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2227 MachineBasicBlock *ParentBB) { 2228 2229 // First create the loads to the guard/stack slot for the comparison. 2230 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2231 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2232 2233 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2234 int FI = MFI.getStackProtectorIndex(); 2235 2236 SDValue Guard; 2237 SDLoc dl = getCurSDLoc(); 2238 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2239 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2240 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2241 2242 // Generate code to load the content of the guard slot. 2243 SDValue GuardVal = DAG.getLoad( 2244 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2245 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2246 MachineMemOperand::MOVolatile); 2247 2248 if (TLI.useStackGuardXorFP()) 2249 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2250 2251 // Retrieve guard check function, nullptr if instrumentation is inlined. 2252 if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) { 2253 // The target provides a guard check function to validate the guard value. 2254 // Generate a call to that function with the content of the guard slot as 2255 // argument. 2256 auto *Fn = cast<Function>(GuardCheck); 2257 FunctionType *FnTy = Fn->getFunctionType(); 2258 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2259 2260 TargetLowering::ArgListTy Args; 2261 TargetLowering::ArgListEntry Entry; 2262 Entry.Node = GuardVal; 2263 Entry.Ty = FnTy->getParamType(0); 2264 if (Fn->hasAttribute(1, Attribute::AttrKind::InReg)) 2265 Entry.IsInReg = true; 2266 Args.push_back(Entry); 2267 2268 TargetLowering::CallLoweringInfo CLI(DAG); 2269 CLI.setDebugLoc(getCurSDLoc()) 2270 .setChain(DAG.getEntryNode()) 2271 .setCallee(Fn->getCallingConv(), FnTy->getReturnType(), 2272 getValue(GuardCheck), std::move(Args)); 2273 2274 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2275 DAG.setRoot(Result.second); 2276 return; 2277 } 2278 2279 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2280 // Otherwise, emit a volatile load to retrieve the stack guard value. 2281 SDValue Chain = DAG.getEntryNode(); 2282 if (TLI.useLoadStackGuardNode()) { 2283 Guard = getLoadStackGuard(DAG, dl, Chain); 2284 } else { 2285 const Value *IRGuard = TLI.getSDagStackGuard(M); 2286 SDValue GuardPtr = getValue(IRGuard); 2287 2288 Guard = 2289 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2290 Align, MachineMemOperand::MOVolatile); 2291 } 2292 2293 // Perform the comparison via a subtract/getsetcc. 2294 EVT VT = Guard.getValueType(); 2295 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2296 2297 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2298 *DAG.getContext(), 2299 Sub.getValueType()), 2300 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2301 2302 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2303 // branch to failure MBB. 2304 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2305 MVT::Other, GuardVal.getOperand(0), 2306 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2307 // Otherwise branch to success MBB. 2308 SDValue Br = DAG.getNode(ISD::BR, dl, 2309 MVT::Other, BrCond, 2310 DAG.getBasicBlock(SPD.getSuccessMBB())); 2311 2312 DAG.setRoot(Br); 2313 } 2314 2315 /// Codegen the failure basic block for a stack protector check. 2316 /// 2317 /// A failure stack protector machine basic block consists simply of a call to 2318 /// __stack_chk_fail(). 2319 /// 2320 /// For a high level explanation of how this fits into the stack protector 2321 /// generation see the comment on the declaration of class 2322 /// StackProtectorDescriptor. 2323 void 2324 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2325 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2326 SDValue Chain = 2327 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2328 None, false, getCurSDLoc(), false, false).second; 2329 DAG.setRoot(Chain); 2330 } 2331 2332 /// visitBitTestHeader - This function emits necessary code to produce value 2333 /// suitable for "bit tests" 2334 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2335 MachineBasicBlock *SwitchBB) { 2336 SDLoc dl = getCurSDLoc(); 2337 2338 // Subtract the minimum value 2339 SDValue SwitchOp = getValue(B.SValue); 2340 EVT VT = SwitchOp.getValueType(); 2341 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2342 DAG.getConstant(B.First, dl, VT)); 2343 2344 // Check range 2345 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2346 SDValue RangeCmp = DAG.getSetCC( 2347 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2348 Sub.getValueType()), 2349 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2350 2351 // Determine the type of the test operands. 2352 bool UsePtrType = false; 2353 if (!TLI.isTypeLegal(VT)) 2354 UsePtrType = true; 2355 else { 2356 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2357 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2358 // Switch table case range are encoded into series of masks. 2359 // Just use pointer type, it's guaranteed to fit. 2360 UsePtrType = true; 2361 break; 2362 } 2363 } 2364 if (UsePtrType) { 2365 VT = TLI.getPointerTy(DAG.getDataLayout()); 2366 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2367 } 2368 2369 B.RegVT = VT.getSimpleVT(); 2370 B.Reg = FuncInfo.CreateReg(B.RegVT); 2371 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2372 2373 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2374 2375 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2376 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2377 SwitchBB->normalizeSuccProbs(); 2378 2379 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2380 MVT::Other, CopyTo, RangeCmp, 2381 DAG.getBasicBlock(B.Default)); 2382 2383 // Avoid emitting unnecessary branches to the next block. 2384 if (MBB != NextBlock(SwitchBB)) 2385 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2386 DAG.getBasicBlock(MBB)); 2387 2388 DAG.setRoot(BrRange); 2389 } 2390 2391 /// visitBitTestCase - this function produces one "bit test" 2392 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2393 MachineBasicBlock* NextMBB, 2394 BranchProbability BranchProbToNext, 2395 unsigned Reg, 2396 BitTestCase &B, 2397 MachineBasicBlock *SwitchBB) { 2398 SDLoc dl = getCurSDLoc(); 2399 MVT VT = BB.RegVT; 2400 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2401 SDValue Cmp; 2402 unsigned PopCount = countPopulation(B.Mask); 2403 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2404 if (PopCount == 1) { 2405 // Testing for a single bit; just compare the shift count with what it 2406 // would need to be to shift a 1 bit in that position. 2407 Cmp = DAG.getSetCC( 2408 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2409 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2410 ISD::SETEQ); 2411 } else if (PopCount == BB.Range) { 2412 // There is only one zero bit in the range, test for it directly. 2413 Cmp = DAG.getSetCC( 2414 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2415 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2416 ISD::SETNE); 2417 } else { 2418 // Make desired shift 2419 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2420 DAG.getConstant(1, dl, VT), ShiftOp); 2421 2422 // Emit bit tests and jumps 2423 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2424 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2425 Cmp = DAG.getSetCC( 2426 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2427 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2428 } 2429 2430 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2431 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2432 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2433 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2434 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2435 // one as they are relative probabilities (and thus work more like weights), 2436 // and hence we need to normalize them to let the sum of them become one. 2437 SwitchBB->normalizeSuccProbs(); 2438 2439 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2440 MVT::Other, getControlRoot(), 2441 Cmp, DAG.getBasicBlock(B.TargetBB)); 2442 2443 // Avoid emitting unnecessary branches to the next block. 2444 if (NextMBB != NextBlock(SwitchBB)) 2445 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2446 DAG.getBasicBlock(NextMBB)); 2447 2448 DAG.setRoot(BrAnd); 2449 } 2450 2451 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2452 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2453 2454 // Retrieve successors. Look through artificial IR level blocks like 2455 // catchswitch for successors. 2456 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2457 const BasicBlock *EHPadBB = I.getSuccessor(1); 2458 2459 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2460 // have to do anything here to lower funclet bundles. 2461 assert(!I.hasOperandBundlesOtherThan( 2462 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2463 "Cannot lower invokes with arbitrary operand bundles yet!"); 2464 2465 const Value *Callee(I.getCalledValue()); 2466 const Function *Fn = dyn_cast<Function>(Callee); 2467 if (isa<InlineAsm>(Callee)) 2468 visitInlineAsm(&I); 2469 else if (Fn && Fn->isIntrinsic()) { 2470 switch (Fn->getIntrinsicID()) { 2471 default: 2472 llvm_unreachable("Cannot invoke this intrinsic"); 2473 case Intrinsic::donothing: 2474 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2475 break; 2476 case Intrinsic::experimental_patchpoint_void: 2477 case Intrinsic::experimental_patchpoint_i64: 2478 visitPatchpoint(&I, EHPadBB); 2479 break; 2480 case Intrinsic::experimental_gc_statepoint: 2481 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2482 break; 2483 } 2484 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2485 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2486 // Eventually we will support lowering the @llvm.experimental.deoptimize 2487 // intrinsic, and right now there are no plans to support other intrinsics 2488 // with deopt state. 2489 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2490 } else { 2491 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2492 } 2493 2494 // If the value of the invoke is used outside of its defining block, make it 2495 // available as a virtual register. 2496 // We already took care of the exported value for the statepoint instruction 2497 // during call to the LowerStatepoint. 2498 if (!isStatepoint(I)) { 2499 CopyToExportRegsIfNeeded(&I); 2500 } 2501 2502 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2503 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2504 BranchProbability EHPadBBProb = 2505 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2506 : BranchProbability::getZero(); 2507 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2508 2509 // Update successor info. 2510 addSuccessorWithProb(InvokeMBB, Return); 2511 for (auto &UnwindDest : UnwindDests) { 2512 UnwindDest.first->setIsEHPad(); 2513 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2514 } 2515 InvokeMBB->normalizeSuccProbs(); 2516 2517 // Drop into normal successor. 2518 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2519 MVT::Other, getControlRoot(), 2520 DAG.getBasicBlock(Return))); 2521 } 2522 2523 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2524 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2525 } 2526 2527 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2528 assert(FuncInfo.MBB->isEHPad() && 2529 "Call to landingpad not in landing pad!"); 2530 2531 // If there aren't registers to copy the values into (e.g., during SjLj 2532 // exceptions), then don't bother to create these DAG nodes. 2533 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2534 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2535 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2536 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2537 return; 2538 2539 // If landingpad's return type is token type, we don't create DAG nodes 2540 // for its exception pointer and selector value. The extraction of exception 2541 // pointer or selector value from token type landingpads is not currently 2542 // supported. 2543 if (LP.getType()->isTokenTy()) 2544 return; 2545 2546 SmallVector<EVT, 2> ValueVTs; 2547 SDLoc dl = getCurSDLoc(); 2548 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2549 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2550 2551 // Get the two live-in registers as SDValues. The physregs have already been 2552 // copied into virtual registers. 2553 SDValue Ops[2]; 2554 if (FuncInfo.ExceptionPointerVirtReg) { 2555 Ops[0] = DAG.getZExtOrTrunc( 2556 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2557 FuncInfo.ExceptionPointerVirtReg, 2558 TLI.getPointerTy(DAG.getDataLayout())), 2559 dl, ValueVTs[0]); 2560 } else { 2561 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2562 } 2563 Ops[1] = DAG.getZExtOrTrunc( 2564 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2565 FuncInfo.ExceptionSelectorVirtReg, 2566 TLI.getPointerTy(DAG.getDataLayout())), 2567 dl, ValueVTs[1]); 2568 2569 // Merge into one. 2570 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2571 DAG.getVTList(ValueVTs), Ops); 2572 setValue(&LP, Res); 2573 } 2574 2575 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2576 #ifndef NDEBUG 2577 for (const CaseCluster &CC : Clusters) 2578 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2579 #endif 2580 2581 llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) { 2582 return a.Low->getValue().slt(b.Low->getValue()); 2583 }); 2584 2585 // Merge adjacent clusters with the same destination. 2586 const unsigned N = Clusters.size(); 2587 unsigned DstIndex = 0; 2588 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2589 CaseCluster &CC = Clusters[SrcIndex]; 2590 const ConstantInt *CaseVal = CC.Low; 2591 MachineBasicBlock *Succ = CC.MBB; 2592 2593 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2594 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2595 // If this case has the same successor and is a neighbour, merge it into 2596 // the previous cluster. 2597 Clusters[DstIndex - 1].High = CaseVal; 2598 Clusters[DstIndex - 1].Prob += CC.Prob; 2599 } else { 2600 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2601 sizeof(Clusters[SrcIndex])); 2602 } 2603 } 2604 Clusters.resize(DstIndex); 2605 } 2606 2607 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2608 MachineBasicBlock *Last) { 2609 // Update JTCases. 2610 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2611 if (JTCases[i].first.HeaderBB == First) 2612 JTCases[i].first.HeaderBB = Last; 2613 2614 // Update BitTestCases. 2615 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2616 if (BitTestCases[i].Parent == First) 2617 BitTestCases[i].Parent = Last; 2618 } 2619 2620 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2621 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2622 2623 // Update machine-CFG edges with unique successors. 2624 SmallSet<BasicBlock*, 32> Done; 2625 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2626 BasicBlock *BB = I.getSuccessor(i); 2627 bool Inserted = Done.insert(BB).second; 2628 if (!Inserted) 2629 continue; 2630 2631 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2632 addSuccessorWithProb(IndirectBrMBB, Succ); 2633 } 2634 IndirectBrMBB->normalizeSuccProbs(); 2635 2636 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2637 MVT::Other, getControlRoot(), 2638 getValue(I.getAddress()))); 2639 } 2640 2641 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2642 if (!DAG.getTarget().Options.TrapUnreachable) 2643 return; 2644 2645 // We may be able to ignore unreachable behind a noreturn call. 2646 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2647 const BasicBlock &BB = *I.getParent(); 2648 if (&I != &BB.front()) { 2649 BasicBlock::const_iterator PredI = 2650 std::prev(BasicBlock::const_iterator(&I)); 2651 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2652 if (Call->doesNotReturn()) 2653 return; 2654 } 2655 } 2656 } 2657 2658 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2659 } 2660 2661 void SelectionDAGBuilder::visitFSub(const User &I) { 2662 // -0.0 - X --> fneg 2663 Type *Ty = I.getType(); 2664 if (isa<Constant>(I.getOperand(0)) && 2665 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2666 SDValue Op2 = getValue(I.getOperand(1)); 2667 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2668 Op2.getValueType(), Op2)); 2669 return; 2670 } 2671 2672 visitBinary(I, ISD::FSUB); 2673 } 2674 2675 /// Checks if the given instruction performs a vector reduction, in which case 2676 /// we have the freedom to alter the elements in the result as long as the 2677 /// reduction of them stays unchanged. 2678 static bool isVectorReductionOp(const User *I) { 2679 const Instruction *Inst = dyn_cast<Instruction>(I); 2680 if (!Inst || !Inst->getType()->isVectorTy()) 2681 return false; 2682 2683 auto OpCode = Inst->getOpcode(); 2684 switch (OpCode) { 2685 case Instruction::Add: 2686 case Instruction::Mul: 2687 case Instruction::And: 2688 case Instruction::Or: 2689 case Instruction::Xor: 2690 break; 2691 case Instruction::FAdd: 2692 case Instruction::FMul: 2693 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2694 if (FPOp->getFastMathFlags().isFast()) 2695 break; 2696 LLVM_FALLTHROUGH; 2697 default: 2698 return false; 2699 } 2700 2701 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2702 // Ensure the reduction size is a power of 2. 2703 if (!isPowerOf2_32(ElemNum)) 2704 return false; 2705 2706 unsigned ElemNumToReduce = ElemNum; 2707 2708 // Do DFS search on the def-use chain from the given instruction. We only 2709 // allow four kinds of operations during the search until we reach the 2710 // instruction that extracts the first element from the vector: 2711 // 2712 // 1. The reduction operation of the same opcode as the given instruction. 2713 // 2714 // 2. PHI node. 2715 // 2716 // 3. ShuffleVector instruction together with a reduction operation that 2717 // does a partial reduction. 2718 // 2719 // 4. ExtractElement that extracts the first element from the vector, and we 2720 // stop searching the def-use chain here. 2721 // 2722 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2723 // from 1-3 to the stack to continue the DFS. The given instruction is not 2724 // a reduction operation if we meet any other instructions other than those 2725 // listed above. 2726 2727 SmallVector<const User *, 16> UsersToVisit{Inst}; 2728 SmallPtrSet<const User *, 16> Visited; 2729 bool ReduxExtracted = false; 2730 2731 while (!UsersToVisit.empty()) { 2732 auto User = UsersToVisit.back(); 2733 UsersToVisit.pop_back(); 2734 if (!Visited.insert(User).second) 2735 continue; 2736 2737 for (const auto &U : User->users()) { 2738 auto Inst = dyn_cast<Instruction>(U); 2739 if (!Inst) 2740 return false; 2741 2742 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2743 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2744 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 2745 return false; 2746 UsersToVisit.push_back(U); 2747 } else if (const ShuffleVectorInst *ShufInst = 2748 dyn_cast<ShuffleVectorInst>(U)) { 2749 // Detect the following pattern: A ShuffleVector instruction together 2750 // with a reduction that do partial reduction on the first and second 2751 // ElemNumToReduce / 2 elements, and store the result in 2752 // ElemNumToReduce / 2 elements in another vector. 2753 2754 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2755 if (ResultElements < ElemNum) 2756 return false; 2757 2758 if (ElemNumToReduce == 1) 2759 return false; 2760 if (!isa<UndefValue>(U->getOperand(1))) 2761 return false; 2762 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2763 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2764 return false; 2765 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2766 if (ShufInst->getMaskValue(i) != -1) 2767 return false; 2768 2769 // There is only one user of this ShuffleVector instruction, which 2770 // must be a reduction operation. 2771 if (!U->hasOneUse()) 2772 return false; 2773 2774 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2775 if (!U2 || U2->getOpcode() != OpCode) 2776 return false; 2777 2778 // Check operands of the reduction operation. 2779 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2780 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2781 UsersToVisit.push_back(U2); 2782 ElemNumToReduce /= 2; 2783 } else 2784 return false; 2785 } else if (isa<ExtractElementInst>(U)) { 2786 // At this moment we should have reduced all elements in the vector. 2787 if (ElemNumToReduce != 1) 2788 return false; 2789 2790 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2791 if (!Val || !Val->isZero()) 2792 return false; 2793 2794 ReduxExtracted = true; 2795 } else 2796 return false; 2797 } 2798 } 2799 return ReduxExtracted; 2800 } 2801 2802 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 2803 SDNodeFlags Flags; 2804 2805 SDValue Op = getValue(I.getOperand(0)); 2806 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 2807 Op, Flags); 2808 setValue(&I, UnNodeValue); 2809 } 2810 2811 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 2812 SDNodeFlags Flags; 2813 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 2814 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 2815 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 2816 } 2817 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 2818 Flags.setExact(ExactOp->isExact()); 2819 } 2820 if (isVectorReductionOp(&I)) { 2821 Flags.setVectorReduction(true); 2822 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2823 } 2824 2825 SDValue Op1 = getValue(I.getOperand(0)); 2826 SDValue Op2 = getValue(I.getOperand(1)); 2827 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 2828 Op1, Op2, Flags); 2829 setValue(&I, BinNodeValue); 2830 } 2831 2832 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2833 SDValue Op1 = getValue(I.getOperand(0)); 2834 SDValue Op2 = getValue(I.getOperand(1)); 2835 2836 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2837 Op1.getValueType(), DAG.getDataLayout()); 2838 2839 // Coerce the shift amount to the right type if we can. 2840 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2841 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2842 unsigned Op2Size = Op2.getValueSizeInBits(); 2843 SDLoc DL = getCurSDLoc(); 2844 2845 // If the operand is smaller than the shift count type, promote it. 2846 if (ShiftSize > Op2Size) 2847 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2848 2849 // If the operand is larger than the shift count type but the shift 2850 // count type has enough bits to represent any shift value, truncate 2851 // it now. This is a common case and it exposes the truncate to 2852 // optimization early. 2853 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 2854 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2855 // Otherwise we'll need to temporarily settle for some other convenient 2856 // type. Type legalization will make adjustments once the shiftee is split. 2857 else 2858 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2859 } 2860 2861 bool nuw = false; 2862 bool nsw = false; 2863 bool exact = false; 2864 2865 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2866 2867 if (const OverflowingBinaryOperator *OFBinOp = 2868 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2869 nuw = OFBinOp->hasNoUnsignedWrap(); 2870 nsw = OFBinOp->hasNoSignedWrap(); 2871 } 2872 if (const PossiblyExactOperator *ExactOp = 2873 dyn_cast<const PossiblyExactOperator>(&I)) 2874 exact = ExactOp->isExact(); 2875 } 2876 SDNodeFlags Flags; 2877 Flags.setExact(exact); 2878 Flags.setNoSignedWrap(nsw); 2879 Flags.setNoUnsignedWrap(nuw); 2880 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2881 Flags); 2882 setValue(&I, Res); 2883 } 2884 2885 void SelectionDAGBuilder::visitSDiv(const User &I) { 2886 SDValue Op1 = getValue(I.getOperand(0)); 2887 SDValue Op2 = getValue(I.getOperand(1)); 2888 2889 SDNodeFlags Flags; 2890 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2891 cast<PossiblyExactOperator>(&I)->isExact()); 2892 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2893 Op2, Flags)); 2894 } 2895 2896 void SelectionDAGBuilder::visitICmp(const User &I) { 2897 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2898 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2899 predicate = IC->getPredicate(); 2900 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2901 predicate = ICmpInst::Predicate(IC->getPredicate()); 2902 SDValue Op1 = getValue(I.getOperand(0)); 2903 SDValue Op2 = getValue(I.getOperand(1)); 2904 ISD::CondCode Opcode = getICmpCondCode(predicate); 2905 2906 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2907 I.getType()); 2908 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2909 } 2910 2911 void SelectionDAGBuilder::visitFCmp(const User &I) { 2912 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2913 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2914 predicate = FC->getPredicate(); 2915 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2916 predicate = FCmpInst::Predicate(FC->getPredicate()); 2917 SDValue Op1 = getValue(I.getOperand(0)); 2918 SDValue Op2 = getValue(I.getOperand(1)); 2919 2920 ISD::CondCode Condition = getFCmpCondCode(predicate); 2921 auto *FPMO = dyn_cast<FPMathOperator>(&I); 2922 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 2923 Condition = getFCmpCodeWithoutNaN(Condition); 2924 2925 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2926 I.getType()); 2927 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2928 } 2929 2930 // Check if the condition of the select has one use or two users that are both 2931 // selects with the same condition. 2932 static bool hasOnlySelectUsers(const Value *Cond) { 2933 return llvm::all_of(Cond->users(), [](const Value *V) { 2934 return isa<SelectInst>(V); 2935 }); 2936 } 2937 2938 void SelectionDAGBuilder::visitSelect(const User &I) { 2939 SmallVector<EVT, 4> ValueVTs; 2940 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2941 ValueVTs); 2942 unsigned NumValues = ValueVTs.size(); 2943 if (NumValues == 0) return; 2944 2945 SmallVector<SDValue, 4> Values(NumValues); 2946 SDValue Cond = getValue(I.getOperand(0)); 2947 SDValue LHSVal = getValue(I.getOperand(1)); 2948 SDValue RHSVal = getValue(I.getOperand(2)); 2949 auto BaseOps = {Cond}; 2950 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2951 ISD::VSELECT : ISD::SELECT; 2952 2953 // Min/max matching is only viable if all output VTs are the same. 2954 if (is_splat(ValueVTs)) { 2955 EVT VT = ValueVTs[0]; 2956 LLVMContext &Ctx = *DAG.getContext(); 2957 auto &TLI = DAG.getTargetLoweringInfo(); 2958 2959 // We care about the legality of the operation after it has been type 2960 // legalized. 2961 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 2962 VT != TLI.getTypeToTransformTo(Ctx, VT)) 2963 VT = TLI.getTypeToTransformTo(Ctx, VT); 2964 2965 // If the vselect is legal, assume we want to leave this as a vector setcc + 2966 // vselect. Otherwise, if this is going to be scalarized, we want to see if 2967 // min/max is legal on the scalar type. 2968 bool UseScalarMinMax = VT.isVector() && 2969 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 2970 2971 Value *LHS, *RHS; 2972 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2973 ISD::NodeType Opc = ISD::DELETED_NODE; 2974 switch (SPR.Flavor) { 2975 case SPF_UMAX: Opc = ISD::UMAX; break; 2976 case SPF_UMIN: Opc = ISD::UMIN; break; 2977 case SPF_SMAX: Opc = ISD::SMAX; break; 2978 case SPF_SMIN: Opc = ISD::SMIN; break; 2979 case SPF_FMINNUM: 2980 switch (SPR.NaNBehavior) { 2981 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2982 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 2983 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 2984 case SPNB_RETURNS_ANY: { 2985 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 2986 Opc = ISD::FMINNUM; 2987 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 2988 Opc = ISD::FMINIMUM; 2989 else if (UseScalarMinMax) 2990 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 2991 ISD::FMINNUM : ISD::FMINIMUM; 2992 break; 2993 } 2994 } 2995 break; 2996 case SPF_FMAXNUM: 2997 switch (SPR.NaNBehavior) { 2998 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2999 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3000 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3001 case SPNB_RETURNS_ANY: 3002 3003 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3004 Opc = ISD::FMAXNUM; 3005 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3006 Opc = ISD::FMAXIMUM; 3007 else if (UseScalarMinMax) 3008 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3009 ISD::FMAXNUM : ISD::FMAXIMUM; 3010 break; 3011 } 3012 break; 3013 default: break; 3014 } 3015 3016 if (Opc != ISD::DELETED_NODE && 3017 (TLI.isOperationLegalOrCustom(Opc, VT) || 3018 (UseScalarMinMax && 3019 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3020 // If the underlying comparison instruction is used by any other 3021 // instruction, the consumed instructions won't be destroyed, so it is 3022 // not profitable to convert to a min/max. 3023 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3024 OpCode = Opc; 3025 LHSVal = getValue(LHS); 3026 RHSVal = getValue(RHS); 3027 BaseOps = {}; 3028 } 3029 } 3030 3031 for (unsigned i = 0; i != NumValues; ++i) { 3032 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3033 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3034 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3035 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 3036 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 3037 Ops); 3038 } 3039 3040 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3041 DAG.getVTList(ValueVTs), Values)); 3042 } 3043 3044 void SelectionDAGBuilder::visitTrunc(const User &I) { 3045 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3046 SDValue N = getValue(I.getOperand(0)); 3047 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3048 I.getType()); 3049 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3050 } 3051 3052 void SelectionDAGBuilder::visitZExt(const User &I) { 3053 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3054 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3055 SDValue N = getValue(I.getOperand(0)); 3056 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3057 I.getType()); 3058 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3059 } 3060 3061 void SelectionDAGBuilder::visitSExt(const User &I) { 3062 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3063 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3064 SDValue N = getValue(I.getOperand(0)); 3065 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3066 I.getType()); 3067 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3068 } 3069 3070 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3071 // FPTrunc is never a no-op cast, no need to check 3072 SDValue N = getValue(I.getOperand(0)); 3073 SDLoc dl = getCurSDLoc(); 3074 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3075 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3076 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3077 DAG.getTargetConstant( 3078 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3079 } 3080 3081 void SelectionDAGBuilder::visitFPExt(const User &I) { 3082 // FPExt is never a no-op cast, no need to check 3083 SDValue N = getValue(I.getOperand(0)); 3084 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3085 I.getType()); 3086 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3087 } 3088 3089 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3090 // FPToUI is never a no-op cast, no need to check 3091 SDValue N = getValue(I.getOperand(0)); 3092 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3093 I.getType()); 3094 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3095 } 3096 3097 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3098 // FPToSI is never a no-op cast, no need to check 3099 SDValue N = getValue(I.getOperand(0)); 3100 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3101 I.getType()); 3102 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3103 } 3104 3105 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3106 // UIToFP is never a no-op cast, no need to check 3107 SDValue N = getValue(I.getOperand(0)); 3108 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3109 I.getType()); 3110 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3111 } 3112 3113 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3114 // SIToFP is never a no-op cast, no need to check 3115 SDValue N = getValue(I.getOperand(0)); 3116 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3117 I.getType()); 3118 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3119 } 3120 3121 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3122 // What to do depends on the size of the integer and the size of the pointer. 3123 // We can either truncate, zero extend, or no-op, accordingly. 3124 SDValue N = getValue(I.getOperand(0)); 3125 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3126 I.getType()); 3127 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3128 } 3129 3130 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3131 // What to do depends on the size of the integer and the size of the pointer. 3132 // We can either truncate, zero extend, or no-op, accordingly. 3133 SDValue N = getValue(I.getOperand(0)); 3134 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3135 I.getType()); 3136 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3137 } 3138 3139 void SelectionDAGBuilder::visitBitCast(const User &I) { 3140 SDValue N = getValue(I.getOperand(0)); 3141 SDLoc dl = getCurSDLoc(); 3142 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3143 I.getType()); 3144 3145 // BitCast assures us that source and destination are the same size so this is 3146 // either a BITCAST or a no-op. 3147 if (DestVT != N.getValueType()) 3148 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3149 DestVT, N)); // convert types. 3150 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3151 // might fold any kind of constant expression to an integer constant and that 3152 // is not what we are looking for. Only recognize a bitcast of a genuine 3153 // constant integer as an opaque constant. 3154 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3155 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3156 /*isOpaque*/true)); 3157 else 3158 setValue(&I, N); // noop cast. 3159 } 3160 3161 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3162 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3163 const Value *SV = I.getOperand(0); 3164 SDValue N = getValue(SV); 3165 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3166 3167 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3168 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3169 3170 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3171 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3172 3173 setValue(&I, N); 3174 } 3175 3176 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3177 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3178 SDValue InVec = getValue(I.getOperand(0)); 3179 SDValue InVal = getValue(I.getOperand(1)); 3180 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3181 TLI.getVectorIdxTy(DAG.getDataLayout())); 3182 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3183 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3184 InVec, InVal, InIdx)); 3185 } 3186 3187 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3188 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3189 SDValue InVec = getValue(I.getOperand(0)); 3190 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3191 TLI.getVectorIdxTy(DAG.getDataLayout())); 3192 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3193 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3194 InVec, InIdx)); 3195 } 3196 3197 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3198 SDValue Src1 = getValue(I.getOperand(0)); 3199 SDValue Src2 = getValue(I.getOperand(1)); 3200 SDLoc DL = getCurSDLoc(); 3201 3202 SmallVector<int, 8> Mask; 3203 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3204 unsigned MaskNumElts = Mask.size(); 3205 3206 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3207 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3208 EVT SrcVT = Src1.getValueType(); 3209 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3210 3211 if (SrcNumElts == MaskNumElts) { 3212 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3213 return; 3214 } 3215 3216 // Normalize the shuffle vector since mask and vector length don't match. 3217 if (SrcNumElts < MaskNumElts) { 3218 // Mask is longer than the source vectors. We can use concatenate vector to 3219 // make the mask and vectors lengths match. 3220 3221 if (MaskNumElts % SrcNumElts == 0) { 3222 // Mask length is a multiple of the source vector length. 3223 // Check if the shuffle is some kind of concatenation of the input 3224 // vectors. 3225 unsigned NumConcat = MaskNumElts / SrcNumElts; 3226 bool IsConcat = true; 3227 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3228 for (unsigned i = 0; i != MaskNumElts; ++i) { 3229 int Idx = Mask[i]; 3230 if (Idx < 0) 3231 continue; 3232 // Ensure the indices in each SrcVT sized piece are sequential and that 3233 // the same source is used for the whole piece. 3234 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3235 (ConcatSrcs[i / SrcNumElts] >= 0 && 3236 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3237 IsConcat = false; 3238 break; 3239 } 3240 // Remember which source this index came from. 3241 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3242 } 3243 3244 // The shuffle is concatenating multiple vectors together. Just emit 3245 // a CONCAT_VECTORS operation. 3246 if (IsConcat) { 3247 SmallVector<SDValue, 8> ConcatOps; 3248 for (auto Src : ConcatSrcs) { 3249 if (Src < 0) 3250 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3251 else if (Src == 0) 3252 ConcatOps.push_back(Src1); 3253 else 3254 ConcatOps.push_back(Src2); 3255 } 3256 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3257 return; 3258 } 3259 } 3260 3261 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3262 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3263 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3264 PaddedMaskNumElts); 3265 3266 // Pad both vectors with undefs to make them the same length as the mask. 3267 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3268 3269 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3270 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3271 MOps1[0] = Src1; 3272 MOps2[0] = Src2; 3273 3274 Src1 = Src1.isUndef() 3275 ? DAG.getUNDEF(PaddedVT) 3276 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3277 Src2 = Src2.isUndef() 3278 ? DAG.getUNDEF(PaddedVT) 3279 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3280 3281 // Readjust mask for new input vector length. 3282 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3283 for (unsigned i = 0; i != MaskNumElts; ++i) { 3284 int Idx = Mask[i]; 3285 if (Idx >= (int)SrcNumElts) 3286 Idx -= SrcNumElts - PaddedMaskNumElts; 3287 MappedOps[i] = Idx; 3288 } 3289 3290 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3291 3292 // If the concatenated vector was padded, extract a subvector with the 3293 // correct number of elements. 3294 if (MaskNumElts != PaddedMaskNumElts) 3295 Result = DAG.getNode( 3296 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3297 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3298 3299 setValue(&I, Result); 3300 return; 3301 } 3302 3303 if (SrcNumElts > MaskNumElts) { 3304 // Analyze the access pattern of the vector to see if we can extract 3305 // two subvectors and do the shuffle. 3306 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3307 bool CanExtract = true; 3308 for (int Idx : Mask) { 3309 unsigned Input = 0; 3310 if (Idx < 0) 3311 continue; 3312 3313 if (Idx >= (int)SrcNumElts) { 3314 Input = 1; 3315 Idx -= SrcNumElts; 3316 } 3317 3318 // If all the indices come from the same MaskNumElts sized portion of 3319 // the sources we can use extract. Also make sure the extract wouldn't 3320 // extract past the end of the source. 3321 int NewStartIdx = alignDown(Idx, MaskNumElts); 3322 if (NewStartIdx + MaskNumElts > SrcNumElts || 3323 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3324 CanExtract = false; 3325 // Make sure we always update StartIdx as we use it to track if all 3326 // elements are undef. 3327 StartIdx[Input] = NewStartIdx; 3328 } 3329 3330 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3331 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3332 return; 3333 } 3334 if (CanExtract) { 3335 // Extract appropriate subvector and generate a vector shuffle 3336 for (unsigned Input = 0; Input < 2; ++Input) { 3337 SDValue &Src = Input == 0 ? Src1 : Src2; 3338 if (StartIdx[Input] < 0) 3339 Src = DAG.getUNDEF(VT); 3340 else { 3341 Src = DAG.getNode( 3342 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3343 DAG.getConstant(StartIdx[Input], DL, 3344 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3345 } 3346 } 3347 3348 // Calculate new mask. 3349 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3350 for (int &Idx : MappedOps) { 3351 if (Idx >= (int)SrcNumElts) 3352 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3353 else if (Idx >= 0) 3354 Idx -= StartIdx[0]; 3355 } 3356 3357 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3358 return; 3359 } 3360 } 3361 3362 // We can't use either concat vectors or extract subvectors so fall back to 3363 // replacing the shuffle with extract and build vector. 3364 // to insert and build vector. 3365 EVT EltVT = VT.getVectorElementType(); 3366 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3367 SmallVector<SDValue,8> Ops; 3368 for (int Idx : Mask) { 3369 SDValue Res; 3370 3371 if (Idx < 0) { 3372 Res = DAG.getUNDEF(EltVT); 3373 } else { 3374 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3375 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3376 3377 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3378 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3379 } 3380 3381 Ops.push_back(Res); 3382 } 3383 3384 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3385 } 3386 3387 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3388 ArrayRef<unsigned> Indices; 3389 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3390 Indices = IV->getIndices(); 3391 else 3392 Indices = cast<ConstantExpr>(&I)->getIndices(); 3393 3394 const Value *Op0 = I.getOperand(0); 3395 const Value *Op1 = I.getOperand(1); 3396 Type *AggTy = I.getType(); 3397 Type *ValTy = Op1->getType(); 3398 bool IntoUndef = isa<UndefValue>(Op0); 3399 bool FromUndef = isa<UndefValue>(Op1); 3400 3401 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3402 3403 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3404 SmallVector<EVT, 4> AggValueVTs; 3405 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3406 SmallVector<EVT, 4> ValValueVTs; 3407 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3408 3409 unsigned NumAggValues = AggValueVTs.size(); 3410 unsigned NumValValues = ValValueVTs.size(); 3411 SmallVector<SDValue, 4> Values(NumAggValues); 3412 3413 // Ignore an insertvalue that produces an empty object 3414 if (!NumAggValues) { 3415 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3416 return; 3417 } 3418 3419 SDValue Agg = getValue(Op0); 3420 unsigned i = 0; 3421 // Copy the beginning value(s) from the original aggregate. 3422 for (; i != LinearIndex; ++i) 3423 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3424 SDValue(Agg.getNode(), Agg.getResNo() + i); 3425 // Copy values from the inserted value(s). 3426 if (NumValValues) { 3427 SDValue Val = getValue(Op1); 3428 for (; i != LinearIndex + NumValValues; ++i) 3429 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3430 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3431 } 3432 // Copy remaining value(s) from the original aggregate. 3433 for (; i != NumAggValues; ++i) 3434 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3435 SDValue(Agg.getNode(), Agg.getResNo() + i); 3436 3437 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3438 DAG.getVTList(AggValueVTs), Values)); 3439 } 3440 3441 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3442 ArrayRef<unsigned> Indices; 3443 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3444 Indices = EV->getIndices(); 3445 else 3446 Indices = cast<ConstantExpr>(&I)->getIndices(); 3447 3448 const Value *Op0 = I.getOperand(0); 3449 Type *AggTy = Op0->getType(); 3450 Type *ValTy = I.getType(); 3451 bool OutOfUndef = isa<UndefValue>(Op0); 3452 3453 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3454 3455 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3456 SmallVector<EVT, 4> ValValueVTs; 3457 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3458 3459 unsigned NumValValues = ValValueVTs.size(); 3460 3461 // Ignore a extractvalue that produces an empty object 3462 if (!NumValValues) { 3463 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3464 return; 3465 } 3466 3467 SmallVector<SDValue, 4> Values(NumValValues); 3468 3469 SDValue Agg = getValue(Op0); 3470 // Copy out the selected value(s). 3471 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3472 Values[i - LinearIndex] = 3473 OutOfUndef ? 3474 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3475 SDValue(Agg.getNode(), Agg.getResNo() + i); 3476 3477 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3478 DAG.getVTList(ValValueVTs), Values)); 3479 } 3480 3481 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3482 Value *Op0 = I.getOperand(0); 3483 // Note that the pointer operand may be a vector of pointers. Take the scalar 3484 // element which holds a pointer. 3485 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3486 SDValue N = getValue(Op0); 3487 SDLoc dl = getCurSDLoc(); 3488 3489 // Normalize Vector GEP - all scalar operands should be converted to the 3490 // splat vector. 3491 unsigned VectorWidth = I.getType()->isVectorTy() ? 3492 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3493 3494 if (VectorWidth && !N.getValueType().isVector()) { 3495 LLVMContext &Context = *DAG.getContext(); 3496 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3497 N = DAG.getSplatBuildVector(VT, dl, N); 3498 } 3499 3500 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3501 GTI != E; ++GTI) { 3502 const Value *Idx = GTI.getOperand(); 3503 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3504 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3505 if (Field) { 3506 // N = N + Offset 3507 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3508 3509 // In an inbounds GEP with an offset that is nonnegative even when 3510 // interpreted as signed, assume there is no unsigned overflow. 3511 SDNodeFlags Flags; 3512 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3513 Flags.setNoUnsignedWrap(true); 3514 3515 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3516 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3517 } 3518 } else { 3519 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3520 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3521 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3522 3523 // If this is a scalar constant or a splat vector of constants, 3524 // handle it quickly. 3525 const auto *CI = dyn_cast<ConstantInt>(Idx); 3526 if (!CI && isa<ConstantDataVector>(Idx) && 3527 cast<ConstantDataVector>(Idx)->getSplatValue()) 3528 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3529 3530 if (CI) { 3531 if (CI->isZero()) 3532 continue; 3533 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3534 LLVMContext &Context = *DAG.getContext(); 3535 SDValue OffsVal = VectorWidth ? 3536 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3537 DAG.getConstant(Offs, dl, IdxTy); 3538 3539 // In an inbouds GEP with an offset that is nonnegative even when 3540 // interpreted as signed, assume there is no unsigned overflow. 3541 SDNodeFlags Flags; 3542 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3543 Flags.setNoUnsignedWrap(true); 3544 3545 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3546 continue; 3547 } 3548 3549 // N = N + Idx * ElementSize; 3550 SDValue IdxN = getValue(Idx); 3551 3552 if (!IdxN.getValueType().isVector() && VectorWidth) { 3553 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3554 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3555 } 3556 3557 // If the index is smaller or larger than intptr_t, truncate or extend 3558 // it. 3559 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3560 3561 // If this is a multiply by a power of two, turn it into a shl 3562 // immediately. This is a very common case. 3563 if (ElementSize != 1) { 3564 if (ElementSize.isPowerOf2()) { 3565 unsigned Amt = ElementSize.logBase2(); 3566 IdxN = DAG.getNode(ISD::SHL, dl, 3567 N.getValueType(), IdxN, 3568 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3569 } else { 3570 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3571 IdxN = DAG.getNode(ISD::MUL, dl, 3572 N.getValueType(), IdxN, Scale); 3573 } 3574 } 3575 3576 N = DAG.getNode(ISD::ADD, dl, 3577 N.getValueType(), N, IdxN); 3578 } 3579 } 3580 3581 setValue(&I, N); 3582 } 3583 3584 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3585 // If this is a fixed sized alloca in the entry block of the function, 3586 // allocate it statically on the stack. 3587 if (FuncInfo.StaticAllocaMap.count(&I)) 3588 return; // getValue will auto-populate this. 3589 3590 SDLoc dl = getCurSDLoc(); 3591 Type *Ty = I.getAllocatedType(); 3592 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3593 auto &DL = DAG.getDataLayout(); 3594 uint64_t TySize = DL.getTypeAllocSize(Ty); 3595 unsigned Align = 3596 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3597 3598 SDValue AllocSize = getValue(I.getArraySize()); 3599 3600 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3601 if (AllocSize.getValueType() != IntPtr) 3602 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3603 3604 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3605 AllocSize, 3606 DAG.getConstant(TySize, dl, IntPtr)); 3607 3608 // Handle alignment. If the requested alignment is less than or equal to 3609 // the stack alignment, ignore it. If the size is greater than or equal to 3610 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3611 unsigned StackAlign = 3612 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3613 if (Align <= StackAlign) 3614 Align = 0; 3615 3616 // Round the size of the allocation up to the stack alignment size 3617 // by add SA-1 to the size. This doesn't overflow because we're computing 3618 // an address inside an alloca. 3619 SDNodeFlags Flags; 3620 Flags.setNoUnsignedWrap(true); 3621 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3622 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3623 3624 // Mask out the low bits for alignment purposes. 3625 AllocSize = 3626 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3627 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3628 3629 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3630 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3631 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3632 setValue(&I, DSA); 3633 DAG.setRoot(DSA.getValue(1)); 3634 3635 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3636 } 3637 3638 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3639 if (I.isAtomic()) 3640 return visitAtomicLoad(I); 3641 3642 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3643 const Value *SV = I.getOperand(0); 3644 if (TLI.supportSwiftError()) { 3645 // Swifterror values can come from either a function parameter with 3646 // swifterror attribute or an alloca with swifterror attribute. 3647 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3648 if (Arg->hasSwiftErrorAttr()) 3649 return visitLoadFromSwiftError(I); 3650 } 3651 3652 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3653 if (Alloca->isSwiftError()) 3654 return visitLoadFromSwiftError(I); 3655 } 3656 } 3657 3658 SDValue Ptr = getValue(SV); 3659 3660 Type *Ty = I.getType(); 3661 3662 bool isVolatile = I.isVolatile(); 3663 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3664 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3665 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3666 unsigned Alignment = I.getAlignment(); 3667 3668 AAMDNodes AAInfo; 3669 I.getAAMetadata(AAInfo); 3670 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3671 3672 SmallVector<EVT, 4> ValueVTs; 3673 SmallVector<uint64_t, 4> Offsets; 3674 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3675 unsigned NumValues = ValueVTs.size(); 3676 if (NumValues == 0) 3677 return; 3678 3679 SDValue Root; 3680 bool ConstantMemory = false; 3681 if (isVolatile || NumValues > MaxParallelChains) 3682 // Serialize volatile loads with other side effects. 3683 Root = getRoot(); 3684 else if (AA && 3685 AA->pointsToConstantMemory(MemoryLocation( 3686 SV, 3687 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3688 AAInfo))) { 3689 // Do not serialize (non-volatile) loads of constant memory with anything. 3690 Root = DAG.getEntryNode(); 3691 ConstantMemory = true; 3692 } else { 3693 // Do not serialize non-volatile loads against each other. 3694 Root = DAG.getRoot(); 3695 } 3696 3697 SDLoc dl = getCurSDLoc(); 3698 3699 if (isVolatile) 3700 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3701 3702 // An aggregate load cannot wrap around the address space, so offsets to its 3703 // parts don't wrap either. 3704 SDNodeFlags Flags; 3705 Flags.setNoUnsignedWrap(true); 3706 3707 SmallVector<SDValue, 4> Values(NumValues); 3708 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3709 EVT PtrVT = Ptr.getValueType(); 3710 unsigned ChainI = 0; 3711 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3712 // Serializing loads here may result in excessive register pressure, and 3713 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3714 // could recover a bit by hoisting nodes upward in the chain by recognizing 3715 // they are side-effect free or do not alias. The optimizer should really 3716 // avoid this case by converting large object/array copies to llvm.memcpy 3717 // (MaxParallelChains should always remain as failsafe). 3718 if (ChainI == MaxParallelChains) { 3719 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3720 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3721 makeArrayRef(Chains.data(), ChainI)); 3722 Root = Chain; 3723 ChainI = 0; 3724 } 3725 SDValue A = DAG.getNode(ISD::ADD, dl, 3726 PtrVT, Ptr, 3727 DAG.getConstant(Offsets[i], dl, PtrVT), 3728 Flags); 3729 auto MMOFlags = MachineMemOperand::MONone; 3730 if (isVolatile) 3731 MMOFlags |= MachineMemOperand::MOVolatile; 3732 if (isNonTemporal) 3733 MMOFlags |= MachineMemOperand::MONonTemporal; 3734 if (isInvariant) 3735 MMOFlags |= MachineMemOperand::MOInvariant; 3736 if (isDereferenceable) 3737 MMOFlags |= MachineMemOperand::MODereferenceable; 3738 MMOFlags |= TLI.getMMOFlags(I); 3739 3740 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3741 MachinePointerInfo(SV, Offsets[i]), Alignment, 3742 MMOFlags, AAInfo, Ranges); 3743 3744 Values[i] = L; 3745 Chains[ChainI] = L.getValue(1); 3746 } 3747 3748 if (!ConstantMemory) { 3749 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3750 makeArrayRef(Chains.data(), ChainI)); 3751 if (isVolatile) 3752 DAG.setRoot(Chain); 3753 else 3754 PendingLoads.push_back(Chain); 3755 } 3756 3757 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3758 DAG.getVTList(ValueVTs), Values)); 3759 } 3760 3761 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3762 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3763 "call visitStoreToSwiftError when backend supports swifterror"); 3764 3765 SmallVector<EVT, 4> ValueVTs; 3766 SmallVector<uint64_t, 4> Offsets; 3767 const Value *SrcV = I.getOperand(0); 3768 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3769 SrcV->getType(), ValueVTs, &Offsets); 3770 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3771 "expect a single EVT for swifterror"); 3772 3773 SDValue Src = getValue(SrcV); 3774 // Create a virtual register, then update the virtual register. 3775 unsigned VReg; bool CreatedVReg; 3776 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 3777 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3778 // Chain can be getRoot or getControlRoot. 3779 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3780 SDValue(Src.getNode(), Src.getResNo())); 3781 DAG.setRoot(CopyNode); 3782 if (CreatedVReg) 3783 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3784 } 3785 3786 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3787 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3788 "call visitLoadFromSwiftError when backend supports swifterror"); 3789 3790 assert(!I.isVolatile() && 3791 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3792 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3793 "Support volatile, non temporal, invariant for load_from_swift_error"); 3794 3795 const Value *SV = I.getOperand(0); 3796 Type *Ty = I.getType(); 3797 AAMDNodes AAInfo; 3798 I.getAAMetadata(AAInfo); 3799 assert( 3800 (!AA || 3801 !AA->pointsToConstantMemory(MemoryLocation( 3802 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3803 AAInfo))) && 3804 "load_from_swift_error should not be constant memory"); 3805 3806 SmallVector<EVT, 4> ValueVTs; 3807 SmallVector<uint64_t, 4> Offsets; 3808 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3809 ValueVTs, &Offsets); 3810 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3811 "expect a single EVT for swifterror"); 3812 3813 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3814 SDValue L = DAG.getCopyFromReg( 3815 getRoot(), getCurSDLoc(), 3816 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 3817 ValueVTs[0]); 3818 3819 setValue(&I, L); 3820 } 3821 3822 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3823 if (I.isAtomic()) 3824 return visitAtomicStore(I); 3825 3826 const Value *SrcV = I.getOperand(0); 3827 const Value *PtrV = I.getOperand(1); 3828 3829 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3830 if (TLI.supportSwiftError()) { 3831 // Swifterror values can come from either a function parameter with 3832 // swifterror attribute or an alloca with swifterror attribute. 3833 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3834 if (Arg->hasSwiftErrorAttr()) 3835 return visitStoreToSwiftError(I); 3836 } 3837 3838 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3839 if (Alloca->isSwiftError()) 3840 return visitStoreToSwiftError(I); 3841 } 3842 } 3843 3844 SmallVector<EVT, 4> ValueVTs; 3845 SmallVector<uint64_t, 4> Offsets; 3846 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3847 SrcV->getType(), ValueVTs, &Offsets); 3848 unsigned NumValues = ValueVTs.size(); 3849 if (NumValues == 0) 3850 return; 3851 3852 // Get the lowered operands. Note that we do this after 3853 // checking if NumResults is zero, because with zero results 3854 // the operands won't have values in the map. 3855 SDValue Src = getValue(SrcV); 3856 SDValue Ptr = getValue(PtrV); 3857 3858 SDValue Root = getRoot(); 3859 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3860 SDLoc dl = getCurSDLoc(); 3861 EVT PtrVT = Ptr.getValueType(); 3862 unsigned Alignment = I.getAlignment(); 3863 AAMDNodes AAInfo; 3864 I.getAAMetadata(AAInfo); 3865 3866 auto MMOFlags = MachineMemOperand::MONone; 3867 if (I.isVolatile()) 3868 MMOFlags |= MachineMemOperand::MOVolatile; 3869 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3870 MMOFlags |= MachineMemOperand::MONonTemporal; 3871 MMOFlags |= TLI.getMMOFlags(I); 3872 3873 // An aggregate load cannot wrap around the address space, so offsets to its 3874 // parts don't wrap either. 3875 SDNodeFlags Flags; 3876 Flags.setNoUnsignedWrap(true); 3877 3878 unsigned ChainI = 0; 3879 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3880 // See visitLoad comments. 3881 if (ChainI == MaxParallelChains) { 3882 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3883 makeArrayRef(Chains.data(), ChainI)); 3884 Root = Chain; 3885 ChainI = 0; 3886 } 3887 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3888 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 3889 SDValue St = DAG.getStore( 3890 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3891 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3892 Chains[ChainI] = St; 3893 } 3894 3895 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3896 makeArrayRef(Chains.data(), ChainI)); 3897 DAG.setRoot(StoreNode); 3898 } 3899 3900 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 3901 bool IsCompressing) { 3902 SDLoc sdl = getCurSDLoc(); 3903 3904 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3905 unsigned& Alignment) { 3906 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3907 Src0 = I.getArgOperand(0); 3908 Ptr = I.getArgOperand(1); 3909 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3910 Mask = I.getArgOperand(3); 3911 }; 3912 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3913 unsigned& Alignment) { 3914 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 3915 Src0 = I.getArgOperand(0); 3916 Ptr = I.getArgOperand(1); 3917 Mask = I.getArgOperand(2); 3918 Alignment = 0; 3919 }; 3920 3921 Value *PtrOperand, *MaskOperand, *Src0Operand; 3922 unsigned Alignment; 3923 if (IsCompressing) 3924 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3925 else 3926 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3927 3928 SDValue Ptr = getValue(PtrOperand); 3929 SDValue Src0 = getValue(Src0Operand); 3930 SDValue Mask = getValue(MaskOperand); 3931 3932 EVT VT = Src0.getValueType(); 3933 if (!Alignment) 3934 Alignment = DAG.getEVTAlignment(VT); 3935 3936 AAMDNodes AAInfo; 3937 I.getAAMetadata(AAInfo); 3938 3939 MachineMemOperand *MMO = 3940 DAG.getMachineFunction(). 3941 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3942 MachineMemOperand::MOStore, VT.getStoreSize(), 3943 Alignment, AAInfo); 3944 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3945 MMO, false /* Truncating */, 3946 IsCompressing); 3947 DAG.setRoot(StoreNode); 3948 setValue(&I, StoreNode); 3949 } 3950 3951 // Get a uniform base for the Gather/Scatter intrinsic. 3952 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 3953 // We try to represent it as a base pointer + vector of indices. 3954 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 3955 // The first operand of the GEP may be a single pointer or a vector of pointers 3956 // Example: 3957 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 3958 // or 3959 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 3960 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 3961 // 3962 // When the first GEP operand is a single pointer - it is the uniform base we 3963 // are looking for. If first operand of the GEP is a splat vector - we 3964 // extract the splat value and use it as a uniform base. 3965 // In all other cases the function returns 'false'. 3966 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 3967 SDValue &Scale, SelectionDAGBuilder* SDB) { 3968 SelectionDAG& DAG = SDB->DAG; 3969 LLVMContext &Context = *DAG.getContext(); 3970 3971 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 3972 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 3973 if (!GEP) 3974 return false; 3975 3976 const Value *GEPPtr = GEP->getPointerOperand(); 3977 if (!GEPPtr->getType()->isVectorTy()) 3978 Ptr = GEPPtr; 3979 else if (!(Ptr = getSplatValue(GEPPtr))) 3980 return false; 3981 3982 unsigned FinalIndex = GEP->getNumOperands() - 1; 3983 Value *IndexVal = GEP->getOperand(FinalIndex); 3984 3985 // Ensure all the other indices are 0. 3986 for (unsigned i = 1; i < FinalIndex; ++i) { 3987 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 3988 if (!C || !C->isZero()) 3989 return false; 3990 } 3991 3992 // The operands of the GEP may be defined in another basic block. 3993 // In this case we'll not find nodes for the operands. 3994 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 3995 return false; 3996 3997 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3998 const DataLayout &DL = DAG.getDataLayout(); 3999 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4000 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4001 Base = SDB->getValue(Ptr); 4002 Index = SDB->getValue(IndexVal); 4003 4004 if (!Index.getValueType().isVector()) { 4005 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4006 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4007 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4008 } 4009 return true; 4010 } 4011 4012 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4013 SDLoc sdl = getCurSDLoc(); 4014 4015 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4016 const Value *Ptr = I.getArgOperand(1); 4017 SDValue Src0 = getValue(I.getArgOperand(0)); 4018 SDValue Mask = getValue(I.getArgOperand(3)); 4019 EVT VT = Src0.getValueType(); 4020 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4021 if (!Alignment) 4022 Alignment = DAG.getEVTAlignment(VT); 4023 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4024 4025 AAMDNodes AAInfo; 4026 I.getAAMetadata(AAInfo); 4027 4028 SDValue Base; 4029 SDValue Index; 4030 SDValue Scale; 4031 const Value *BasePtr = Ptr; 4032 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4033 4034 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4035 MachineMemOperand *MMO = DAG.getMachineFunction(). 4036 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4037 MachineMemOperand::MOStore, VT.getStoreSize(), 4038 Alignment, AAInfo); 4039 if (!UniformBase) { 4040 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4041 Index = getValue(Ptr); 4042 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4043 } 4044 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4045 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4046 Ops, MMO); 4047 DAG.setRoot(Scatter); 4048 setValue(&I, Scatter); 4049 } 4050 4051 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4052 SDLoc sdl = getCurSDLoc(); 4053 4054 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4055 unsigned& Alignment) { 4056 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4057 Ptr = I.getArgOperand(0); 4058 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4059 Mask = I.getArgOperand(2); 4060 Src0 = I.getArgOperand(3); 4061 }; 4062 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4063 unsigned& Alignment) { 4064 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4065 Ptr = I.getArgOperand(0); 4066 Alignment = 0; 4067 Mask = I.getArgOperand(1); 4068 Src0 = I.getArgOperand(2); 4069 }; 4070 4071 Value *PtrOperand, *MaskOperand, *Src0Operand; 4072 unsigned Alignment; 4073 if (IsExpanding) 4074 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4075 else 4076 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4077 4078 SDValue Ptr = getValue(PtrOperand); 4079 SDValue Src0 = getValue(Src0Operand); 4080 SDValue Mask = getValue(MaskOperand); 4081 4082 EVT VT = Src0.getValueType(); 4083 if (!Alignment) 4084 Alignment = DAG.getEVTAlignment(VT); 4085 4086 AAMDNodes AAInfo; 4087 I.getAAMetadata(AAInfo); 4088 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4089 4090 // Do not serialize masked loads of constant memory with anything. 4091 bool AddToChain = 4092 !AA || !AA->pointsToConstantMemory(MemoryLocation( 4093 PtrOperand, 4094 LocationSize::precise( 4095 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4096 AAInfo)); 4097 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4098 4099 MachineMemOperand *MMO = 4100 DAG.getMachineFunction(). 4101 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4102 MachineMemOperand::MOLoad, VT.getStoreSize(), 4103 Alignment, AAInfo, Ranges); 4104 4105 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4106 ISD::NON_EXTLOAD, IsExpanding); 4107 if (AddToChain) 4108 PendingLoads.push_back(Load.getValue(1)); 4109 setValue(&I, Load); 4110 } 4111 4112 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4113 SDLoc sdl = getCurSDLoc(); 4114 4115 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4116 const Value *Ptr = I.getArgOperand(0); 4117 SDValue Src0 = getValue(I.getArgOperand(3)); 4118 SDValue Mask = getValue(I.getArgOperand(2)); 4119 4120 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4121 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4122 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4123 if (!Alignment) 4124 Alignment = DAG.getEVTAlignment(VT); 4125 4126 AAMDNodes AAInfo; 4127 I.getAAMetadata(AAInfo); 4128 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4129 4130 SDValue Root = DAG.getRoot(); 4131 SDValue Base; 4132 SDValue Index; 4133 SDValue Scale; 4134 const Value *BasePtr = Ptr; 4135 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4136 bool ConstantMemory = false; 4137 if (UniformBase && AA && 4138 AA->pointsToConstantMemory( 4139 MemoryLocation(BasePtr, 4140 LocationSize::precise( 4141 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4142 AAInfo))) { 4143 // Do not serialize (non-volatile) loads of constant memory with anything. 4144 Root = DAG.getEntryNode(); 4145 ConstantMemory = true; 4146 } 4147 4148 MachineMemOperand *MMO = 4149 DAG.getMachineFunction(). 4150 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4151 MachineMemOperand::MOLoad, VT.getStoreSize(), 4152 Alignment, AAInfo, Ranges); 4153 4154 if (!UniformBase) { 4155 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4156 Index = getValue(Ptr); 4157 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4158 } 4159 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4160 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4161 Ops, MMO); 4162 4163 SDValue OutChain = Gather.getValue(1); 4164 if (!ConstantMemory) 4165 PendingLoads.push_back(OutChain); 4166 setValue(&I, Gather); 4167 } 4168 4169 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4170 SDLoc dl = getCurSDLoc(); 4171 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 4172 AtomicOrdering FailureOrder = I.getFailureOrdering(); 4173 SyncScope::ID SSID = I.getSyncScopeID(); 4174 4175 SDValue InChain = getRoot(); 4176 4177 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4178 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4179 SDValue L = DAG.getAtomicCmpSwap( 4180 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 4181 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 4182 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 4183 /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID); 4184 4185 SDValue OutChain = L.getValue(2); 4186 4187 setValue(&I, L); 4188 DAG.setRoot(OutChain); 4189 } 4190 4191 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4192 SDLoc dl = getCurSDLoc(); 4193 ISD::NodeType NT; 4194 switch (I.getOperation()) { 4195 default: llvm_unreachable("Unknown atomicrmw operation"); 4196 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4197 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4198 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4199 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4200 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4201 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4202 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4203 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4204 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4205 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4206 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4207 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4208 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4209 } 4210 AtomicOrdering Order = I.getOrdering(); 4211 SyncScope::ID SSID = I.getSyncScopeID(); 4212 4213 SDValue InChain = getRoot(); 4214 4215 SDValue L = 4216 DAG.getAtomic(NT, dl, 4217 getValue(I.getValOperand()).getSimpleValueType(), 4218 InChain, 4219 getValue(I.getPointerOperand()), 4220 getValue(I.getValOperand()), 4221 I.getPointerOperand(), 4222 /* Alignment=*/ 0, Order, SSID); 4223 4224 SDValue OutChain = L.getValue(1); 4225 4226 setValue(&I, L); 4227 DAG.setRoot(OutChain); 4228 } 4229 4230 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4231 SDLoc dl = getCurSDLoc(); 4232 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4233 SDValue Ops[3]; 4234 Ops[0] = getRoot(); 4235 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4236 TLI.getFenceOperandTy(DAG.getDataLayout())); 4237 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4238 TLI.getFenceOperandTy(DAG.getDataLayout())); 4239 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4240 } 4241 4242 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4243 SDLoc dl = getCurSDLoc(); 4244 AtomicOrdering Order = I.getOrdering(); 4245 SyncScope::ID SSID = I.getSyncScopeID(); 4246 4247 SDValue InChain = getRoot(); 4248 4249 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4250 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4251 4252 if (!TLI.supportsUnalignedAtomics() && 4253 I.getAlignment() < VT.getStoreSize()) 4254 report_fatal_error("Cannot generate unaligned atomic load"); 4255 4256 MachineMemOperand *MMO = 4257 DAG.getMachineFunction(). 4258 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4259 MachineMemOperand::MOVolatile | 4260 MachineMemOperand::MOLoad, 4261 VT.getStoreSize(), 4262 I.getAlignment() ? I.getAlignment() : 4263 DAG.getEVTAlignment(VT), 4264 AAMDNodes(), nullptr, SSID, Order); 4265 4266 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4267 SDValue L = 4268 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4269 getValue(I.getPointerOperand()), MMO); 4270 4271 SDValue OutChain = L.getValue(1); 4272 4273 setValue(&I, L); 4274 DAG.setRoot(OutChain); 4275 } 4276 4277 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4278 SDLoc dl = getCurSDLoc(); 4279 4280 AtomicOrdering Order = I.getOrdering(); 4281 SyncScope::ID SSID = I.getSyncScopeID(); 4282 4283 SDValue InChain = getRoot(); 4284 4285 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4286 EVT VT = 4287 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4288 4289 if (I.getAlignment() < VT.getStoreSize()) 4290 report_fatal_error("Cannot generate unaligned atomic store"); 4291 4292 SDValue OutChain = 4293 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4294 InChain, 4295 getValue(I.getPointerOperand()), 4296 getValue(I.getValueOperand()), 4297 I.getPointerOperand(), I.getAlignment(), 4298 Order, SSID); 4299 4300 DAG.setRoot(OutChain); 4301 } 4302 4303 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4304 /// node. 4305 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4306 unsigned Intrinsic) { 4307 // Ignore the callsite's attributes. A specific call site may be marked with 4308 // readnone, but the lowering code will expect the chain based on the 4309 // definition. 4310 const Function *F = I.getCalledFunction(); 4311 bool HasChain = !F->doesNotAccessMemory(); 4312 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4313 4314 // Build the operand list. 4315 SmallVector<SDValue, 8> Ops; 4316 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4317 if (OnlyLoad) { 4318 // We don't need to serialize loads against other loads. 4319 Ops.push_back(DAG.getRoot()); 4320 } else { 4321 Ops.push_back(getRoot()); 4322 } 4323 } 4324 4325 // Info is set by getTgtMemInstrinsic 4326 TargetLowering::IntrinsicInfo Info; 4327 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4328 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4329 DAG.getMachineFunction(), 4330 Intrinsic); 4331 4332 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4333 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4334 Info.opc == ISD::INTRINSIC_W_CHAIN) 4335 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4336 TLI.getPointerTy(DAG.getDataLayout()))); 4337 4338 // Add all operands of the call to the operand list. 4339 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4340 SDValue Op = getValue(I.getArgOperand(i)); 4341 Ops.push_back(Op); 4342 } 4343 4344 SmallVector<EVT, 4> ValueVTs; 4345 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4346 4347 if (HasChain) 4348 ValueVTs.push_back(MVT::Other); 4349 4350 SDVTList VTs = DAG.getVTList(ValueVTs); 4351 4352 // Create the node. 4353 SDValue Result; 4354 if (IsTgtIntrinsic) { 4355 // This is target intrinsic that touches memory 4356 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4357 Ops, Info.memVT, 4358 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4359 Info.flags, Info.size); 4360 } else if (!HasChain) { 4361 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4362 } else if (!I.getType()->isVoidTy()) { 4363 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4364 } else { 4365 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4366 } 4367 4368 if (HasChain) { 4369 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4370 if (OnlyLoad) 4371 PendingLoads.push_back(Chain); 4372 else 4373 DAG.setRoot(Chain); 4374 } 4375 4376 if (!I.getType()->isVoidTy()) { 4377 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4378 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4379 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4380 } else 4381 Result = lowerRangeToAssertZExt(DAG, I, Result); 4382 4383 setValue(&I, Result); 4384 } 4385 } 4386 4387 /// GetSignificand - Get the significand and build it into a floating-point 4388 /// number with exponent of 1: 4389 /// 4390 /// Op = (Op & 0x007fffff) | 0x3f800000; 4391 /// 4392 /// where Op is the hexadecimal representation of floating point value. 4393 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4394 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4395 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4396 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4397 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4398 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4399 } 4400 4401 /// GetExponent - Get the exponent: 4402 /// 4403 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4404 /// 4405 /// where Op is the hexadecimal representation of floating point value. 4406 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4407 const TargetLowering &TLI, const SDLoc &dl) { 4408 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4409 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4410 SDValue t1 = DAG.getNode( 4411 ISD::SRL, dl, MVT::i32, t0, 4412 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4413 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4414 DAG.getConstant(127, dl, MVT::i32)); 4415 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4416 } 4417 4418 /// getF32Constant - Get 32-bit floating point constant. 4419 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4420 const SDLoc &dl) { 4421 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4422 MVT::f32); 4423 } 4424 4425 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4426 SelectionDAG &DAG) { 4427 // TODO: What fast-math-flags should be set on the floating-point nodes? 4428 4429 // IntegerPartOfX = ((int32_t)(t0); 4430 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4431 4432 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4433 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4434 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4435 4436 // IntegerPartOfX <<= 23; 4437 IntegerPartOfX = DAG.getNode( 4438 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4439 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4440 DAG.getDataLayout()))); 4441 4442 SDValue TwoToFractionalPartOfX; 4443 if (LimitFloatPrecision <= 6) { 4444 // For floating-point precision of 6: 4445 // 4446 // TwoToFractionalPartOfX = 4447 // 0.997535578f + 4448 // (0.735607626f + 0.252464424f * x) * x; 4449 // 4450 // error 0.0144103317, which is 6 bits 4451 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4452 getF32Constant(DAG, 0x3e814304, dl)); 4453 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4454 getF32Constant(DAG, 0x3f3c50c8, dl)); 4455 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4456 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4457 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4458 } else if (LimitFloatPrecision <= 12) { 4459 // For floating-point precision of 12: 4460 // 4461 // TwoToFractionalPartOfX = 4462 // 0.999892986f + 4463 // (0.696457318f + 4464 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4465 // 4466 // error 0.000107046256, which is 13 to 14 bits 4467 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4468 getF32Constant(DAG, 0x3da235e3, dl)); 4469 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4470 getF32Constant(DAG, 0x3e65b8f3, dl)); 4471 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4472 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4473 getF32Constant(DAG, 0x3f324b07, dl)); 4474 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4475 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4476 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4477 } else { // LimitFloatPrecision <= 18 4478 // For floating-point precision of 18: 4479 // 4480 // TwoToFractionalPartOfX = 4481 // 0.999999982f + 4482 // (0.693148872f + 4483 // (0.240227044f + 4484 // (0.554906021e-1f + 4485 // (0.961591928e-2f + 4486 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4487 // error 2.47208000*10^(-7), which is better than 18 bits 4488 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4489 getF32Constant(DAG, 0x3924b03e, dl)); 4490 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4491 getF32Constant(DAG, 0x3ab24b87, dl)); 4492 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4493 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4494 getF32Constant(DAG, 0x3c1d8c17, dl)); 4495 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4496 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4497 getF32Constant(DAG, 0x3d634a1d, dl)); 4498 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4499 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4500 getF32Constant(DAG, 0x3e75fe14, dl)); 4501 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4502 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4503 getF32Constant(DAG, 0x3f317234, dl)); 4504 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4505 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4506 getF32Constant(DAG, 0x3f800000, dl)); 4507 } 4508 4509 // Add the exponent into the result in integer domain. 4510 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4511 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4512 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4513 } 4514 4515 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4516 /// limited-precision mode. 4517 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4518 const TargetLowering &TLI) { 4519 if (Op.getValueType() == MVT::f32 && 4520 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4521 4522 // Put the exponent in the right bit position for later addition to the 4523 // final result: 4524 // 4525 // #define LOG2OFe 1.4426950f 4526 // t0 = Op * LOG2OFe 4527 4528 // TODO: What fast-math-flags should be set here? 4529 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4530 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4531 return getLimitedPrecisionExp2(t0, dl, DAG); 4532 } 4533 4534 // No special expansion. 4535 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4536 } 4537 4538 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4539 /// limited-precision mode. 4540 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4541 const TargetLowering &TLI) { 4542 // TODO: What fast-math-flags should be set on the floating-point nodes? 4543 4544 if (Op.getValueType() == MVT::f32 && 4545 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4546 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4547 4548 // Scale the exponent by log(2) [0.69314718f]. 4549 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4550 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4551 getF32Constant(DAG, 0x3f317218, dl)); 4552 4553 // Get the significand and build it into a floating-point number with 4554 // exponent of 1. 4555 SDValue X = GetSignificand(DAG, Op1, dl); 4556 4557 SDValue LogOfMantissa; 4558 if (LimitFloatPrecision <= 6) { 4559 // For floating-point precision of 6: 4560 // 4561 // LogofMantissa = 4562 // -1.1609546f + 4563 // (1.4034025f - 0.23903021f * x) * x; 4564 // 4565 // error 0.0034276066, which is better than 8 bits 4566 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4567 getF32Constant(DAG, 0xbe74c456, dl)); 4568 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4569 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4570 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4571 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4572 getF32Constant(DAG, 0x3f949a29, dl)); 4573 } else if (LimitFloatPrecision <= 12) { 4574 // For floating-point precision of 12: 4575 // 4576 // LogOfMantissa = 4577 // -1.7417939f + 4578 // (2.8212026f + 4579 // (-1.4699568f + 4580 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4581 // 4582 // error 0.000061011436, which is 14 bits 4583 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4584 getF32Constant(DAG, 0xbd67b6d6, dl)); 4585 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4586 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4587 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4588 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4589 getF32Constant(DAG, 0x3fbc278b, dl)); 4590 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4591 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4592 getF32Constant(DAG, 0x40348e95, dl)); 4593 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4594 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4595 getF32Constant(DAG, 0x3fdef31a, dl)); 4596 } else { // LimitFloatPrecision <= 18 4597 // For floating-point precision of 18: 4598 // 4599 // LogOfMantissa = 4600 // -2.1072184f + 4601 // (4.2372794f + 4602 // (-3.7029485f + 4603 // (2.2781945f + 4604 // (-0.87823314f + 4605 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4606 // 4607 // error 0.0000023660568, which is better than 18 bits 4608 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4609 getF32Constant(DAG, 0xbc91e5ac, dl)); 4610 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4611 getF32Constant(DAG, 0x3e4350aa, dl)); 4612 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4613 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4614 getF32Constant(DAG, 0x3f60d3e3, dl)); 4615 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4616 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4617 getF32Constant(DAG, 0x4011cdf0, dl)); 4618 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4619 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4620 getF32Constant(DAG, 0x406cfd1c, dl)); 4621 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4622 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4623 getF32Constant(DAG, 0x408797cb, dl)); 4624 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4625 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4626 getF32Constant(DAG, 0x4006dcab, dl)); 4627 } 4628 4629 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4630 } 4631 4632 // No special expansion. 4633 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4634 } 4635 4636 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4637 /// limited-precision mode. 4638 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4639 const TargetLowering &TLI) { 4640 // TODO: What fast-math-flags should be set on the floating-point nodes? 4641 4642 if (Op.getValueType() == MVT::f32 && 4643 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4644 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4645 4646 // Get the exponent. 4647 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4648 4649 // Get the significand and build it into a floating-point number with 4650 // exponent of 1. 4651 SDValue X = GetSignificand(DAG, Op1, dl); 4652 4653 // Different possible minimax approximations of significand in 4654 // floating-point for various degrees of accuracy over [1,2]. 4655 SDValue Log2ofMantissa; 4656 if (LimitFloatPrecision <= 6) { 4657 // For floating-point precision of 6: 4658 // 4659 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4660 // 4661 // error 0.0049451742, which is more than 7 bits 4662 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4663 getF32Constant(DAG, 0xbeb08fe0, dl)); 4664 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4665 getF32Constant(DAG, 0x40019463, dl)); 4666 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4667 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4668 getF32Constant(DAG, 0x3fd6633d, dl)); 4669 } else if (LimitFloatPrecision <= 12) { 4670 // For floating-point precision of 12: 4671 // 4672 // Log2ofMantissa = 4673 // -2.51285454f + 4674 // (4.07009056f + 4675 // (-2.12067489f + 4676 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4677 // 4678 // error 0.0000876136000, which is better than 13 bits 4679 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4680 getF32Constant(DAG, 0xbda7262e, dl)); 4681 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4682 getF32Constant(DAG, 0x3f25280b, dl)); 4683 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4684 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4685 getF32Constant(DAG, 0x4007b923, dl)); 4686 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4687 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4688 getF32Constant(DAG, 0x40823e2f, dl)); 4689 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4690 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4691 getF32Constant(DAG, 0x4020d29c, dl)); 4692 } else { // LimitFloatPrecision <= 18 4693 // For floating-point precision of 18: 4694 // 4695 // Log2ofMantissa = 4696 // -3.0400495f + 4697 // (6.1129976f + 4698 // (-5.3420409f + 4699 // (3.2865683f + 4700 // (-1.2669343f + 4701 // (0.27515199f - 4702 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4703 // 4704 // error 0.0000018516, which is better than 18 bits 4705 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4706 getF32Constant(DAG, 0xbcd2769e, dl)); 4707 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4708 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4709 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4710 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4711 getF32Constant(DAG, 0x3fa22ae7, dl)); 4712 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4713 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4714 getF32Constant(DAG, 0x40525723, dl)); 4715 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4716 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4717 getF32Constant(DAG, 0x40aaf200, dl)); 4718 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4719 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4720 getF32Constant(DAG, 0x40c39dad, dl)); 4721 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4722 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4723 getF32Constant(DAG, 0x4042902c, dl)); 4724 } 4725 4726 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4727 } 4728 4729 // No special expansion. 4730 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4731 } 4732 4733 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4734 /// limited-precision mode. 4735 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4736 const TargetLowering &TLI) { 4737 // TODO: What fast-math-flags should be set on the floating-point nodes? 4738 4739 if (Op.getValueType() == MVT::f32 && 4740 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4741 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4742 4743 // Scale the exponent by log10(2) [0.30102999f]. 4744 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4745 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4746 getF32Constant(DAG, 0x3e9a209a, dl)); 4747 4748 // Get the significand and build it into a floating-point number with 4749 // exponent of 1. 4750 SDValue X = GetSignificand(DAG, Op1, dl); 4751 4752 SDValue Log10ofMantissa; 4753 if (LimitFloatPrecision <= 6) { 4754 // For floating-point precision of 6: 4755 // 4756 // Log10ofMantissa = 4757 // -0.50419619f + 4758 // (0.60948995f - 0.10380950f * x) * x; 4759 // 4760 // error 0.0014886165, which is 6 bits 4761 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4762 getF32Constant(DAG, 0xbdd49a13, dl)); 4763 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4764 getF32Constant(DAG, 0x3f1c0789, dl)); 4765 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4766 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4767 getF32Constant(DAG, 0x3f011300, dl)); 4768 } else if (LimitFloatPrecision <= 12) { 4769 // For floating-point precision of 12: 4770 // 4771 // Log10ofMantissa = 4772 // -0.64831180f + 4773 // (0.91751397f + 4774 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4775 // 4776 // error 0.00019228036, which is better than 12 bits 4777 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4778 getF32Constant(DAG, 0x3d431f31, dl)); 4779 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4780 getF32Constant(DAG, 0x3ea21fb2, dl)); 4781 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4782 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4783 getF32Constant(DAG, 0x3f6ae232, dl)); 4784 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4785 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4786 getF32Constant(DAG, 0x3f25f7c3, dl)); 4787 } else { // LimitFloatPrecision <= 18 4788 // For floating-point precision of 18: 4789 // 4790 // Log10ofMantissa = 4791 // -0.84299375f + 4792 // (1.5327582f + 4793 // (-1.0688956f + 4794 // (0.49102474f + 4795 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4796 // 4797 // error 0.0000037995730, which is better than 18 bits 4798 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4799 getF32Constant(DAG, 0x3c5d51ce, dl)); 4800 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4801 getF32Constant(DAG, 0x3e00685a, dl)); 4802 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4803 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4804 getF32Constant(DAG, 0x3efb6798, dl)); 4805 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4806 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4807 getF32Constant(DAG, 0x3f88d192, dl)); 4808 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4809 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4810 getF32Constant(DAG, 0x3fc4316c, dl)); 4811 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4812 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4813 getF32Constant(DAG, 0x3f57ce70, dl)); 4814 } 4815 4816 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4817 } 4818 4819 // No special expansion. 4820 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4821 } 4822 4823 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4824 /// limited-precision mode. 4825 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4826 const TargetLowering &TLI) { 4827 if (Op.getValueType() == MVT::f32 && 4828 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4829 return getLimitedPrecisionExp2(Op, dl, DAG); 4830 4831 // No special expansion. 4832 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4833 } 4834 4835 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4836 /// limited-precision mode with x == 10.0f. 4837 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4838 SelectionDAG &DAG, const TargetLowering &TLI) { 4839 bool IsExp10 = false; 4840 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4841 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4842 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4843 APFloat Ten(10.0f); 4844 IsExp10 = LHSC->isExactlyValue(Ten); 4845 } 4846 } 4847 4848 // TODO: What fast-math-flags should be set on the FMUL node? 4849 if (IsExp10) { 4850 // Put the exponent in the right bit position for later addition to the 4851 // final result: 4852 // 4853 // #define LOG2OF10 3.3219281f 4854 // t0 = Op * LOG2OF10; 4855 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4856 getF32Constant(DAG, 0x40549a78, dl)); 4857 return getLimitedPrecisionExp2(t0, dl, DAG); 4858 } 4859 4860 // No special expansion. 4861 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4862 } 4863 4864 /// ExpandPowI - Expand a llvm.powi intrinsic. 4865 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4866 SelectionDAG &DAG) { 4867 // If RHS is a constant, we can expand this out to a multiplication tree, 4868 // otherwise we end up lowering to a call to __powidf2 (for example). When 4869 // optimizing for size, we only want to do this if the expansion would produce 4870 // a small number of multiplies, otherwise we do the full expansion. 4871 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4872 // Get the exponent as a positive value. 4873 unsigned Val = RHSC->getSExtValue(); 4874 if ((int)Val < 0) Val = -Val; 4875 4876 // powi(x, 0) -> 1.0 4877 if (Val == 0) 4878 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4879 4880 const Function &F = DAG.getMachineFunction().getFunction(); 4881 if (!F.optForSize() || 4882 // If optimizing for size, don't insert too many multiplies. 4883 // This inserts up to 5 multiplies. 4884 countPopulation(Val) + Log2_32(Val) < 7) { 4885 // We use the simple binary decomposition method to generate the multiply 4886 // sequence. There are more optimal ways to do this (for example, 4887 // powi(x,15) generates one more multiply than it should), but this has 4888 // the benefit of being both really simple and much better than a libcall. 4889 SDValue Res; // Logically starts equal to 1.0 4890 SDValue CurSquare = LHS; 4891 // TODO: Intrinsics should have fast-math-flags that propagate to these 4892 // nodes. 4893 while (Val) { 4894 if (Val & 1) { 4895 if (Res.getNode()) 4896 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4897 else 4898 Res = CurSquare; // 1.0*CurSquare. 4899 } 4900 4901 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4902 CurSquare, CurSquare); 4903 Val >>= 1; 4904 } 4905 4906 // If the original was negative, invert the result, producing 1/(x*x*x). 4907 if (RHSC->getSExtValue() < 0) 4908 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4909 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4910 return Res; 4911 } 4912 } 4913 4914 // Otherwise, expand to a libcall. 4915 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4916 } 4917 4918 // getUnderlyingArgReg - Find underlying register used for a truncated or 4919 // bitcasted argument. 4920 static unsigned getUnderlyingArgReg(const SDValue &N) { 4921 switch (N.getOpcode()) { 4922 case ISD::CopyFromReg: 4923 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4924 case ISD::BITCAST: 4925 case ISD::AssertZext: 4926 case ISD::AssertSext: 4927 case ISD::TRUNCATE: 4928 return getUnderlyingArgReg(N.getOperand(0)); 4929 default: 4930 return 0; 4931 } 4932 } 4933 4934 /// If the DbgValueInst is a dbg_value of a function argument, create the 4935 /// corresponding DBG_VALUE machine instruction for it now. At the end of 4936 /// instruction selection, they will be inserted to the entry BB. 4937 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4938 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4939 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 4940 const Argument *Arg = dyn_cast<Argument>(V); 4941 if (!Arg) 4942 return false; 4943 4944 MachineFunction &MF = DAG.getMachineFunction(); 4945 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4946 4947 bool IsIndirect = false; 4948 Optional<MachineOperand> Op; 4949 // Some arguments' frame index is recorded during argument lowering. 4950 int FI = FuncInfo.getArgumentFrameIndex(Arg); 4951 if (FI != std::numeric_limits<int>::max()) 4952 Op = MachineOperand::CreateFI(FI); 4953 4954 if (!Op && N.getNode()) { 4955 unsigned Reg = getUnderlyingArgReg(N); 4956 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4957 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4958 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4959 if (PR) 4960 Reg = PR; 4961 } 4962 if (Reg) { 4963 Op = MachineOperand::CreateReg(Reg, false); 4964 IsIndirect = IsDbgDeclare; 4965 } 4966 } 4967 4968 if (!Op && N.getNode()) 4969 // Check if frame index is available. 4970 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4971 if (FrameIndexSDNode *FINode = 4972 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4973 Op = MachineOperand::CreateFI(FINode->getIndex()); 4974 4975 if (!Op) { 4976 // Check if ValueMap has reg number. 4977 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4978 if (VMI != FuncInfo.ValueMap.end()) { 4979 const auto &TLI = DAG.getTargetLoweringInfo(); 4980 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 4981 V->getType(), getABIRegCopyCC(V)); 4982 if (RFV.occupiesMultipleRegs()) { 4983 unsigned Offset = 0; 4984 for (auto RegAndSize : RFV.getRegsAndSizes()) { 4985 Op = MachineOperand::CreateReg(RegAndSize.first, false); 4986 auto FragmentExpr = DIExpression::createFragmentExpression( 4987 Expr, Offset, RegAndSize.second); 4988 if (!FragmentExpr) 4989 continue; 4990 FuncInfo.ArgDbgValues.push_back( 4991 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 4992 Op->getReg(), Variable, *FragmentExpr)); 4993 Offset += RegAndSize.second; 4994 } 4995 return true; 4996 } 4997 Op = MachineOperand::CreateReg(VMI->second, false); 4998 IsIndirect = IsDbgDeclare; 4999 } 5000 } 5001 5002 if (!Op) 5003 return false; 5004 5005 assert(Variable->isValidLocationForIntrinsic(DL) && 5006 "Expected inlined-at fields to agree"); 5007 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5008 FuncInfo.ArgDbgValues.push_back( 5009 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5010 *Op, Variable, Expr)); 5011 5012 return true; 5013 } 5014 5015 /// Return the appropriate SDDbgValue based on N. 5016 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5017 DILocalVariable *Variable, 5018 DIExpression *Expr, 5019 const DebugLoc &dl, 5020 unsigned DbgSDNodeOrder) { 5021 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5022 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5023 // stack slot locations. 5024 // 5025 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5026 // debug values here after optimization: 5027 // 5028 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5029 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5030 // 5031 // Both describe the direct values of their associated variables. 5032 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5033 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5034 } 5035 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5036 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5037 } 5038 5039 // VisualStudio defines setjmp as _setjmp 5040 #if defined(_MSC_VER) && defined(setjmp) && \ 5041 !defined(setjmp_undefined_for_msvc) 5042 # pragma push_macro("setjmp") 5043 # undef setjmp 5044 # define setjmp_undefined_for_msvc 5045 #endif 5046 5047 /// Lower the call to the specified intrinsic function. If we want to emit this 5048 /// as a call to a named external function, return the name. Otherwise, lower it 5049 /// and return null. 5050 const char * 5051 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5052 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5053 SDLoc sdl = getCurSDLoc(); 5054 DebugLoc dl = getCurDebugLoc(); 5055 SDValue Res; 5056 5057 switch (Intrinsic) { 5058 default: 5059 // By default, turn this into a target intrinsic node. 5060 visitTargetIntrinsic(I, Intrinsic); 5061 return nullptr; 5062 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5063 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5064 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5065 case Intrinsic::returnaddress: 5066 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5067 TLI.getPointerTy(DAG.getDataLayout()), 5068 getValue(I.getArgOperand(0)))); 5069 return nullptr; 5070 case Intrinsic::addressofreturnaddress: 5071 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5072 TLI.getPointerTy(DAG.getDataLayout()))); 5073 return nullptr; 5074 case Intrinsic::sponentry: 5075 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5076 TLI.getPointerTy(DAG.getDataLayout()))); 5077 return nullptr; 5078 case Intrinsic::frameaddress: 5079 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5080 TLI.getPointerTy(DAG.getDataLayout()), 5081 getValue(I.getArgOperand(0)))); 5082 return nullptr; 5083 case Intrinsic::read_register: { 5084 Value *Reg = I.getArgOperand(0); 5085 SDValue Chain = getRoot(); 5086 SDValue RegName = 5087 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5088 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5089 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5090 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5091 setValue(&I, Res); 5092 DAG.setRoot(Res.getValue(1)); 5093 return nullptr; 5094 } 5095 case Intrinsic::write_register: { 5096 Value *Reg = I.getArgOperand(0); 5097 Value *RegValue = I.getArgOperand(1); 5098 SDValue Chain = getRoot(); 5099 SDValue RegName = 5100 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5101 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5102 RegName, getValue(RegValue))); 5103 return nullptr; 5104 } 5105 case Intrinsic::setjmp: 5106 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5107 case Intrinsic::longjmp: 5108 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5109 case Intrinsic::memcpy: { 5110 const auto &MCI = cast<MemCpyInst>(I); 5111 SDValue Op1 = getValue(I.getArgOperand(0)); 5112 SDValue Op2 = getValue(I.getArgOperand(1)); 5113 SDValue Op3 = getValue(I.getArgOperand(2)); 5114 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5115 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5116 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5117 unsigned Align = MinAlign(DstAlign, SrcAlign); 5118 bool isVol = MCI.isVolatile(); 5119 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5120 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5121 // node. 5122 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5123 false, isTC, 5124 MachinePointerInfo(I.getArgOperand(0)), 5125 MachinePointerInfo(I.getArgOperand(1))); 5126 updateDAGForMaybeTailCall(MC); 5127 return nullptr; 5128 } 5129 case Intrinsic::memset: { 5130 const auto &MSI = cast<MemSetInst>(I); 5131 SDValue Op1 = getValue(I.getArgOperand(0)); 5132 SDValue Op2 = getValue(I.getArgOperand(1)); 5133 SDValue Op3 = getValue(I.getArgOperand(2)); 5134 // @llvm.memset defines 0 and 1 to both mean no alignment. 5135 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5136 bool isVol = MSI.isVolatile(); 5137 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5138 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5139 isTC, MachinePointerInfo(I.getArgOperand(0))); 5140 updateDAGForMaybeTailCall(MS); 5141 return nullptr; 5142 } 5143 case Intrinsic::memmove: { 5144 const auto &MMI = cast<MemMoveInst>(I); 5145 SDValue Op1 = getValue(I.getArgOperand(0)); 5146 SDValue Op2 = getValue(I.getArgOperand(1)); 5147 SDValue Op3 = getValue(I.getArgOperand(2)); 5148 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5149 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5150 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5151 unsigned Align = MinAlign(DstAlign, SrcAlign); 5152 bool isVol = MMI.isVolatile(); 5153 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5154 // FIXME: Support passing different dest/src alignments to the memmove DAG 5155 // node. 5156 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5157 isTC, MachinePointerInfo(I.getArgOperand(0)), 5158 MachinePointerInfo(I.getArgOperand(1))); 5159 updateDAGForMaybeTailCall(MM); 5160 return nullptr; 5161 } 5162 case Intrinsic::memcpy_element_unordered_atomic: { 5163 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5164 SDValue Dst = getValue(MI.getRawDest()); 5165 SDValue Src = getValue(MI.getRawSource()); 5166 SDValue Length = getValue(MI.getLength()); 5167 5168 unsigned DstAlign = MI.getDestAlignment(); 5169 unsigned SrcAlign = MI.getSourceAlignment(); 5170 Type *LengthTy = MI.getLength()->getType(); 5171 unsigned ElemSz = MI.getElementSizeInBytes(); 5172 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5173 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5174 SrcAlign, Length, LengthTy, ElemSz, isTC, 5175 MachinePointerInfo(MI.getRawDest()), 5176 MachinePointerInfo(MI.getRawSource())); 5177 updateDAGForMaybeTailCall(MC); 5178 return nullptr; 5179 } 5180 case Intrinsic::memmove_element_unordered_atomic: { 5181 auto &MI = cast<AtomicMemMoveInst>(I); 5182 SDValue Dst = getValue(MI.getRawDest()); 5183 SDValue Src = getValue(MI.getRawSource()); 5184 SDValue Length = getValue(MI.getLength()); 5185 5186 unsigned DstAlign = MI.getDestAlignment(); 5187 unsigned SrcAlign = MI.getSourceAlignment(); 5188 Type *LengthTy = MI.getLength()->getType(); 5189 unsigned ElemSz = MI.getElementSizeInBytes(); 5190 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5191 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5192 SrcAlign, Length, LengthTy, ElemSz, isTC, 5193 MachinePointerInfo(MI.getRawDest()), 5194 MachinePointerInfo(MI.getRawSource())); 5195 updateDAGForMaybeTailCall(MC); 5196 return nullptr; 5197 } 5198 case Intrinsic::memset_element_unordered_atomic: { 5199 auto &MI = cast<AtomicMemSetInst>(I); 5200 SDValue Dst = getValue(MI.getRawDest()); 5201 SDValue Val = getValue(MI.getValue()); 5202 SDValue Length = getValue(MI.getLength()); 5203 5204 unsigned DstAlign = MI.getDestAlignment(); 5205 Type *LengthTy = MI.getLength()->getType(); 5206 unsigned ElemSz = MI.getElementSizeInBytes(); 5207 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5208 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5209 LengthTy, ElemSz, isTC, 5210 MachinePointerInfo(MI.getRawDest())); 5211 updateDAGForMaybeTailCall(MC); 5212 return nullptr; 5213 } 5214 case Intrinsic::dbg_addr: 5215 case Intrinsic::dbg_declare: { 5216 const auto &DI = cast<DbgVariableIntrinsic>(I); 5217 DILocalVariable *Variable = DI.getVariable(); 5218 DIExpression *Expression = DI.getExpression(); 5219 dropDanglingDebugInfo(Variable, Expression); 5220 assert(Variable && "Missing variable"); 5221 5222 // Check if address has undef value. 5223 const Value *Address = DI.getVariableLocation(); 5224 if (!Address || isa<UndefValue>(Address) || 5225 (Address->use_empty() && !isa<Argument>(Address))) { 5226 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5227 return nullptr; 5228 } 5229 5230 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5231 5232 // Check if this variable can be described by a frame index, typically 5233 // either as a static alloca or a byval parameter. 5234 int FI = std::numeric_limits<int>::max(); 5235 if (const auto *AI = 5236 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5237 if (AI->isStaticAlloca()) { 5238 auto I = FuncInfo.StaticAllocaMap.find(AI); 5239 if (I != FuncInfo.StaticAllocaMap.end()) 5240 FI = I->second; 5241 } 5242 } else if (const auto *Arg = dyn_cast<Argument>( 5243 Address->stripInBoundsConstantOffsets())) { 5244 FI = FuncInfo.getArgumentFrameIndex(Arg); 5245 } 5246 5247 // llvm.dbg.addr is control dependent and always generates indirect 5248 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5249 // the MachineFunction variable table. 5250 if (FI != std::numeric_limits<int>::max()) { 5251 if (Intrinsic == Intrinsic::dbg_addr) { 5252 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5253 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5254 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5255 } 5256 return nullptr; 5257 } 5258 5259 SDValue &N = NodeMap[Address]; 5260 if (!N.getNode() && isa<Argument>(Address)) 5261 // Check unused arguments map. 5262 N = UnusedArgNodeMap[Address]; 5263 SDDbgValue *SDV; 5264 if (N.getNode()) { 5265 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5266 Address = BCI->getOperand(0); 5267 // Parameters are handled specially. 5268 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5269 if (isParameter && FINode) { 5270 // Byval parameter. We have a frame index at this point. 5271 SDV = 5272 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5273 /*IsIndirect*/ true, dl, SDNodeOrder); 5274 } else if (isa<Argument>(Address)) { 5275 // Address is an argument, so try to emit its dbg value using 5276 // virtual register info from the FuncInfo.ValueMap. 5277 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5278 return nullptr; 5279 } else { 5280 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5281 true, dl, SDNodeOrder); 5282 } 5283 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5284 } else { 5285 // If Address is an argument then try to emit its dbg value using 5286 // virtual register info from the FuncInfo.ValueMap. 5287 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5288 N)) { 5289 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5290 } 5291 } 5292 return nullptr; 5293 } 5294 case Intrinsic::dbg_label: { 5295 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5296 DILabel *Label = DI.getLabel(); 5297 assert(Label && "Missing label"); 5298 5299 SDDbgLabel *SDV; 5300 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5301 DAG.AddDbgLabel(SDV); 5302 return nullptr; 5303 } 5304 case Intrinsic::dbg_value: { 5305 const DbgValueInst &DI = cast<DbgValueInst>(I); 5306 assert(DI.getVariable() && "Missing variable"); 5307 5308 DILocalVariable *Variable = DI.getVariable(); 5309 DIExpression *Expression = DI.getExpression(); 5310 dropDanglingDebugInfo(Variable, Expression); 5311 const Value *V = DI.getValue(); 5312 if (!V) 5313 return nullptr; 5314 5315 SDDbgValue *SDV; 5316 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 5317 isa<ConstantPointerNull>(V)) { 5318 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5319 DAG.AddDbgValue(SDV, nullptr, false); 5320 return nullptr; 5321 } 5322 5323 // Do not use getValue() in here; we don't want to generate code at 5324 // this point if it hasn't been done yet. 5325 SDValue N = NodeMap[V]; 5326 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5327 N = UnusedArgNodeMap[V]; 5328 if (N.getNode()) { 5329 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5330 return nullptr; 5331 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5332 DAG.AddDbgValue(SDV, N.getNode(), false); 5333 return nullptr; 5334 } 5335 5336 // The value is not used in this block yet (or it would have an SDNode). 5337 // We still want the value to appear for the user if possible -- if it has 5338 // an associated VReg, we can refer to that instead. 5339 if (!isa<Argument>(V)) { 5340 auto VMI = FuncInfo.ValueMap.find(V); 5341 if (VMI != FuncInfo.ValueMap.end()) { 5342 unsigned Reg = VMI->second; 5343 // If this is a PHI node, it may be split up into several MI PHI nodes 5344 // (in FunctionLoweringInfo::set). 5345 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 5346 V->getType(), None); 5347 if (RFV.occupiesMultipleRegs()) { 5348 unsigned Offset = 0; 5349 unsigned BitsToDescribe = 0; 5350 if (auto VarSize = Variable->getSizeInBits()) 5351 BitsToDescribe = *VarSize; 5352 if (auto Fragment = Expression->getFragmentInfo()) 5353 BitsToDescribe = Fragment->SizeInBits; 5354 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5355 unsigned RegisterSize = RegAndSize.second; 5356 // Bail out if all bits are described already. 5357 if (Offset >= BitsToDescribe) 5358 break; 5359 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 5360 ? BitsToDescribe - Offset 5361 : RegisterSize; 5362 auto FragmentExpr = DIExpression::createFragmentExpression( 5363 Expression, Offset, FragmentSize); 5364 if (!FragmentExpr) 5365 continue; 5366 SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first, 5367 false, dl, SDNodeOrder); 5368 DAG.AddDbgValue(SDV, nullptr, false); 5369 Offset += RegisterSize; 5370 } 5371 } else { 5372 SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl, 5373 SDNodeOrder); 5374 DAG.AddDbgValue(SDV, nullptr, false); 5375 } 5376 return nullptr; 5377 } 5378 } 5379 5380 // TODO: When we get here we will either drop the dbg.value completely, or 5381 // we try to move it forward by letting it dangle for awhile. So we should 5382 // probably add an extra DbgValue to the DAG here, with a reference to 5383 // "noreg", to indicate that we have lost the debug location for the 5384 // variable. 5385 5386 if (!V->use_empty() ) { 5387 // Do not call getValue(V) yet, as we don't want to generate code. 5388 // Remember it for later. 5389 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5390 return nullptr; 5391 } 5392 5393 LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5394 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5395 return nullptr; 5396 } 5397 5398 case Intrinsic::eh_typeid_for: { 5399 // Find the type id for the given typeinfo. 5400 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5401 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5402 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5403 setValue(&I, Res); 5404 return nullptr; 5405 } 5406 5407 case Intrinsic::eh_return_i32: 5408 case Intrinsic::eh_return_i64: 5409 DAG.getMachineFunction().setCallsEHReturn(true); 5410 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5411 MVT::Other, 5412 getControlRoot(), 5413 getValue(I.getArgOperand(0)), 5414 getValue(I.getArgOperand(1)))); 5415 return nullptr; 5416 case Intrinsic::eh_unwind_init: 5417 DAG.getMachineFunction().setCallsUnwindInit(true); 5418 return nullptr; 5419 case Intrinsic::eh_dwarf_cfa: 5420 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5421 TLI.getPointerTy(DAG.getDataLayout()), 5422 getValue(I.getArgOperand(0)))); 5423 return nullptr; 5424 case Intrinsic::eh_sjlj_callsite: { 5425 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5426 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5427 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5428 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5429 5430 MMI.setCurrentCallSite(CI->getZExtValue()); 5431 return nullptr; 5432 } 5433 case Intrinsic::eh_sjlj_functioncontext: { 5434 // Get and store the index of the function context. 5435 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5436 AllocaInst *FnCtx = 5437 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5438 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5439 MFI.setFunctionContextIndex(FI); 5440 return nullptr; 5441 } 5442 case Intrinsic::eh_sjlj_setjmp: { 5443 SDValue Ops[2]; 5444 Ops[0] = getRoot(); 5445 Ops[1] = getValue(I.getArgOperand(0)); 5446 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5447 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5448 setValue(&I, Op.getValue(0)); 5449 DAG.setRoot(Op.getValue(1)); 5450 return nullptr; 5451 } 5452 case Intrinsic::eh_sjlj_longjmp: 5453 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5454 getRoot(), getValue(I.getArgOperand(0)))); 5455 return nullptr; 5456 case Intrinsic::eh_sjlj_setup_dispatch: 5457 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5458 getRoot())); 5459 return nullptr; 5460 case Intrinsic::masked_gather: 5461 visitMaskedGather(I); 5462 return nullptr; 5463 case Intrinsic::masked_load: 5464 visitMaskedLoad(I); 5465 return nullptr; 5466 case Intrinsic::masked_scatter: 5467 visitMaskedScatter(I); 5468 return nullptr; 5469 case Intrinsic::masked_store: 5470 visitMaskedStore(I); 5471 return nullptr; 5472 case Intrinsic::masked_expandload: 5473 visitMaskedLoad(I, true /* IsExpanding */); 5474 return nullptr; 5475 case Intrinsic::masked_compressstore: 5476 visitMaskedStore(I, true /* IsCompressing */); 5477 return nullptr; 5478 case Intrinsic::x86_mmx_pslli_w: 5479 case Intrinsic::x86_mmx_pslli_d: 5480 case Intrinsic::x86_mmx_pslli_q: 5481 case Intrinsic::x86_mmx_psrli_w: 5482 case Intrinsic::x86_mmx_psrli_d: 5483 case Intrinsic::x86_mmx_psrli_q: 5484 case Intrinsic::x86_mmx_psrai_w: 5485 case Intrinsic::x86_mmx_psrai_d: { 5486 SDValue ShAmt = getValue(I.getArgOperand(1)); 5487 if (isa<ConstantSDNode>(ShAmt)) { 5488 visitTargetIntrinsic(I, Intrinsic); 5489 return nullptr; 5490 } 5491 unsigned NewIntrinsic = 0; 5492 EVT ShAmtVT = MVT::v2i32; 5493 switch (Intrinsic) { 5494 case Intrinsic::x86_mmx_pslli_w: 5495 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5496 break; 5497 case Intrinsic::x86_mmx_pslli_d: 5498 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5499 break; 5500 case Intrinsic::x86_mmx_pslli_q: 5501 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5502 break; 5503 case Intrinsic::x86_mmx_psrli_w: 5504 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5505 break; 5506 case Intrinsic::x86_mmx_psrli_d: 5507 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5508 break; 5509 case Intrinsic::x86_mmx_psrli_q: 5510 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5511 break; 5512 case Intrinsic::x86_mmx_psrai_w: 5513 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5514 break; 5515 case Intrinsic::x86_mmx_psrai_d: 5516 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5517 break; 5518 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5519 } 5520 5521 // The vector shift intrinsics with scalars uses 32b shift amounts but 5522 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5523 // to be zero. 5524 // We must do this early because v2i32 is not a legal type. 5525 SDValue ShOps[2]; 5526 ShOps[0] = ShAmt; 5527 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5528 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5529 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5530 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5531 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5532 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5533 getValue(I.getArgOperand(0)), ShAmt); 5534 setValue(&I, Res); 5535 return nullptr; 5536 } 5537 case Intrinsic::powi: 5538 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5539 getValue(I.getArgOperand(1)), DAG)); 5540 return nullptr; 5541 case Intrinsic::log: 5542 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5543 return nullptr; 5544 case Intrinsic::log2: 5545 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5546 return nullptr; 5547 case Intrinsic::log10: 5548 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5549 return nullptr; 5550 case Intrinsic::exp: 5551 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5552 return nullptr; 5553 case Intrinsic::exp2: 5554 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5555 return nullptr; 5556 case Intrinsic::pow: 5557 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5558 getValue(I.getArgOperand(1)), DAG, TLI)); 5559 return nullptr; 5560 case Intrinsic::sqrt: 5561 case Intrinsic::fabs: 5562 case Intrinsic::sin: 5563 case Intrinsic::cos: 5564 case Intrinsic::floor: 5565 case Intrinsic::ceil: 5566 case Intrinsic::trunc: 5567 case Intrinsic::rint: 5568 case Intrinsic::nearbyint: 5569 case Intrinsic::round: 5570 case Intrinsic::canonicalize: { 5571 unsigned Opcode; 5572 switch (Intrinsic) { 5573 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5574 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5575 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5576 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5577 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5578 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5579 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5580 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5581 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5582 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5583 case Intrinsic::round: Opcode = ISD::FROUND; break; 5584 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5585 } 5586 5587 setValue(&I, DAG.getNode(Opcode, sdl, 5588 getValue(I.getArgOperand(0)).getValueType(), 5589 getValue(I.getArgOperand(0)))); 5590 return nullptr; 5591 } 5592 case Intrinsic::minnum: { 5593 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5594 unsigned Opc = 5595 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT) 5596 ? ISD::FMINIMUM 5597 : ISD::FMINNUM; 5598 setValue(&I, DAG.getNode(Opc, sdl, VT, 5599 getValue(I.getArgOperand(0)), 5600 getValue(I.getArgOperand(1)))); 5601 return nullptr; 5602 } 5603 case Intrinsic::maxnum: { 5604 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5605 unsigned Opc = 5606 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT) 5607 ? ISD::FMAXIMUM 5608 : ISD::FMAXNUM; 5609 setValue(&I, DAG.getNode(Opc, sdl, VT, 5610 getValue(I.getArgOperand(0)), 5611 getValue(I.getArgOperand(1)))); 5612 return nullptr; 5613 } 5614 case Intrinsic::minimum: 5615 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 5616 getValue(I.getArgOperand(0)).getValueType(), 5617 getValue(I.getArgOperand(0)), 5618 getValue(I.getArgOperand(1)))); 5619 return nullptr; 5620 case Intrinsic::maximum: 5621 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 5622 getValue(I.getArgOperand(0)).getValueType(), 5623 getValue(I.getArgOperand(0)), 5624 getValue(I.getArgOperand(1)))); 5625 return nullptr; 5626 case Intrinsic::copysign: 5627 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5628 getValue(I.getArgOperand(0)).getValueType(), 5629 getValue(I.getArgOperand(0)), 5630 getValue(I.getArgOperand(1)))); 5631 return nullptr; 5632 case Intrinsic::fma: 5633 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5634 getValue(I.getArgOperand(0)).getValueType(), 5635 getValue(I.getArgOperand(0)), 5636 getValue(I.getArgOperand(1)), 5637 getValue(I.getArgOperand(2)))); 5638 return nullptr; 5639 case Intrinsic::experimental_constrained_fadd: 5640 case Intrinsic::experimental_constrained_fsub: 5641 case Intrinsic::experimental_constrained_fmul: 5642 case Intrinsic::experimental_constrained_fdiv: 5643 case Intrinsic::experimental_constrained_frem: 5644 case Intrinsic::experimental_constrained_fma: 5645 case Intrinsic::experimental_constrained_sqrt: 5646 case Intrinsic::experimental_constrained_pow: 5647 case Intrinsic::experimental_constrained_powi: 5648 case Intrinsic::experimental_constrained_sin: 5649 case Intrinsic::experimental_constrained_cos: 5650 case Intrinsic::experimental_constrained_exp: 5651 case Intrinsic::experimental_constrained_exp2: 5652 case Intrinsic::experimental_constrained_log: 5653 case Intrinsic::experimental_constrained_log10: 5654 case Intrinsic::experimental_constrained_log2: 5655 case Intrinsic::experimental_constrained_rint: 5656 case Intrinsic::experimental_constrained_nearbyint: 5657 case Intrinsic::experimental_constrained_maxnum: 5658 case Intrinsic::experimental_constrained_minnum: 5659 case Intrinsic::experimental_constrained_ceil: 5660 case Intrinsic::experimental_constrained_floor: 5661 case Intrinsic::experimental_constrained_round: 5662 case Intrinsic::experimental_constrained_trunc: 5663 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5664 return nullptr; 5665 case Intrinsic::fmuladd: { 5666 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5667 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5668 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5669 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5670 getValue(I.getArgOperand(0)).getValueType(), 5671 getValue(I.getArgOperand(0)), 5672 getValue(I.getArgOperand(1)), 5673 getValue(I.getArgOperand(2)))); 5674 } else { 5675 // TODO: Intrinsic calls should have fast-math-flags. 5676 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5677 getValue(I.getArgOperand(0)).getValueType(), 5678 getValue(I.getArgOperand(0)), 5679 getValue(I.getArgOperand(1))); 5680 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5681 getValue(I.getArgOperand(0)).getValueType(), 5682 Mul, 5683 getValue(I.getArgOperand(2))); 5684 setValue(&I, Add); 5685 } 5686 return nullptr; 5687 } 5688 case Intrinsic::convert_to_fp16: 5689 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5690 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5691 getValue(I.getArgOperand(0)), 5692 DAG.getTargetConstant(0, sdl, 5693 MVT::i32)))); 5694 return nullptr; 5695 case Intrinsic::convert_from_fp16: 5696 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5697 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5698 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5699 getValue(I.getArgOperand(0))))); 5700 return nullptr; 5701 case Intrinsic::pcmarker: { 5702 SDValue Tmp = getValue(I.getArgOperand(0)); 5703 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5704 return nullptr; 5705 } 5706 case Intrinsic::readcyclecounter: { 5707 SDValue Op = getRoot(); 5708 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5709 DAG.getVTList(MVT::i64, MVT::Other), Op); 5710 setValue(&I, Res); 5711 DAG.setRoot(Res.getValue(1)); 5712 return nullptr; 5713 } 5714 case Intrinsic::bitreverse: 5715 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5716 getValue(I.getArgOperand(0)).getValueType(), 5717 getValue(I.getArgOperand(0)))); 5718 return nullptr; 5719 case Intrinsic::bswap: 5720 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5721 getValue(I.getArgOperand(0)).getValueType(), 5722 getValue(I.getArgOperand(0)))); 5723 return nullptr; 5724 case Intrinsic::cttz: { 5725 SDValue Arg = getValue(I.getArgOperand(0)); 5726 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5727 EVT Ty = Arg.getValueType(); 5728 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5729 sdl, Ty, Arg)); 5730 return nullptr; 5731 } 5732 case Intrinsic::ctlz: { 5733 SDValue Arg = getValue(I.getArgOperand(0)); 5734 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5735 EVT Ty = Arg.getValueType(); 5736 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5737 sdl, Ty, Arg)); 5738 return nullptr; 5739 } 5740 case Intrinsic::ctpop: { 5741 SDValue Arg = getValue(I.getArgOperand(0)); 5742 EVT Ty = Arg.getValueType(); 5743 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5744 return nullptr; 5745 } 5746 case Intrinsic::fshl: 5747 case Intrinsic::fshr: { 5748 bool IsFSHL = Intrinsic == Intrinsic::fshl; 5749 SDValue X = getValue(I.getArgOperand(0)); 5750 SDValue Y = getValue(I.getArgOperand(1)); 5751 SDValue Z = getValue(I.getArgOperand(2)); 5752 EVT VT = X.getValueType(); 5753 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 5754 SDValue Zero = DAG.getConstant(0, sdl, VT); 5755 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 5756 5757 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 5758 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 5759 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 5760 return nullptr; 5761 } 5762 5763 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 5764 // avoid the select that is necessary in the general case to filter out 5765 // the 0-shift possibility that leads to UB. 5766 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 5767 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 5768 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5769 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 5770 return nullptr; 5771 } 5772 5773 // Some targets only rotate one way. Try the opposite direction. 5774 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 5775 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5776 // Negate the shift amount because it is safe to ignore the high bits. 5777 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5778 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 5779 return nullptr; 5780 } 5781 5782 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 5783 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 5784 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5785 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 5786 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 5787 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 5788 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 5789 return nullptr; 5790 } 5791 5792 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 5793 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 5794 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 5795 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 5796 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 5797 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 5798 5799 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 5800 // and that is undefined. We must compare and select to avoid UB. 5801 EVT CCVT = MVT::i1; 5802 if (VT.isVector()) 5803 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 5804 5805 // For fshl, 0-shift returns the 1st arg (X). 5806 // For fshr, 0-shift returns the 2nd arg (Y). 5807 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 5808 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 5809 return nullptr; 5810 } 5811 case Intrinsic::sadd_sat: { 5812 SDValue Op1 = getValue(I.getArgOperand(0)); 5813 SDValue Op2 = getValue(I.getArgOperand(1)); 5814 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5815 return nullptr; 5816 } 5817 case Intrinsic::uadd_sat: { 5818 SDValue Op1 = getValue(I.getArgOperand(0)); 5819 SDValue Op2 = getValue(I.getArgOperand(1)); 5820 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5821 return nullptr; 5822 } 5823 case Intrinsic::ssub_sat: { 5824 SDValue Op1 = getValue(I.getArgOperand(0)); 5825 SDValue Op2 = getValue(I.getArgOperand(1)); 5826 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5827 return nullptr; 5828 } 5829 case Intrinsic::usub_sat: { 5830 SDValue Op1 = getValue(I.getArgOperand(0)); 5831 SDValue Op2 = getValue(I.getArgOperand(1)); 5832 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5833 return nullptr; 5834 } 5835 case Intrinsic::smul_fix: { 5836 SDValue Op1 = getValue(I.getArgOperand(0)); 5837 SDValue Op2 = getValue(I.getArgOperand(1)); 5838 SDValue Op3 = getValue(I.getArgOperand(2)); 5839 setValue(&I, 5840 DAG.getNode(ISD::SMULFIX, sdl, Op1.getValueType(), Op1, Op2, Op3)); 5841 return nullptr; 5842 } 5843 case Intrinsic::stacksave: { 5844 SDValue Op = getRoot(); 5845 Res = DAG.getNode( 5846 ISD::STACKSAVE, sdl, 5847 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5848 setValue(&I, Res); 5849 DAG.setRoot(Res.getValue(1)); 5850 return nullptr; 5851 } 5852 case Intrinsic::stackrestore: 5853 Res = getValue(I.getArgOperand(0)); 5854 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5855 return nullptr; 5856 case Intrinsic::get_dynamic_area_offset: { 5857 SDValue Op = getRoot(); 5858 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5859 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5860 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5861 // target. 5862 if (PtrTy != ResTy) 5863 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5864 " intrinsic!"); 5865 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5866 Op); 5867 DAG.setRoot(Op); 5868 setValue(&I, Res); 5869 return nullptr; 5870 } 5871 case Intrinsic::stackguard: { 5872 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5873 MachineFunction &MF = DAG.getMachineFunction(); 5874 const Module &M = *MF.getFunction().getParent(); 5875 SDValue Chain = getRoot(); 5876 if (TLI.useLoadStackGuardNode()) { 5877 Res = getLoadStackGuard(DAG, sdl, Chain); 5878 } else { 5879 const Value *Global = TLI.getSDagStackGuard(M); 5880 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5881 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5882 MachinePointerInfo(Global, 0), Align, 5883 MachineMemOperand::MOVolatile); 5884 } 5885 if (TLI.useStackGuardXorFP()) 5886 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 5887 DAG.setRoot(Chain); 5888 setValue(&I, Res); 5889 return nullptr; 5890 } 5891 case Intrinsic::stackprotector: { 5892 // Emit code into the DAG to store the stack guard onto the stack. 5893 MachineFunction &MF = DAG.getMachineFunction(); 5894 MachineFrameInfo &MFI = MF.getFrameInfo(); 5895 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5896 SDValue Src, Chain = getRoot(); 5897 5898 if (TLI.useLoadStackGuardNode()) 5899 Src = getLoadStackGuard(DAG, sdl, Chain); 5900 else 5901 Src = getValue(I.getArgOperand(0)); // The guard's value. 5902 5903 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5904 5905 int FI = FuncInfo.StaticAllocaMap[Slot]; 5906 MFI.setStackProtectorIndex(FI); 5907 5908 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5909 5910 // Store the stack protector onto the stack. 5911 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5912 DAG.getMachineFunction(), FI), 5913 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5914 setValue(&I, Res); 5915 DAG.setRoot(Res); 5916 return nullptr; 5917 } 5918 case Intrinsic::objectsize: { 5919 // If we don't know by now, we're never going to know. 5920 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5921 5922 assert(CI && "Non-constant type in __builtin_object_size?"); 5923 5924 SDValue Arg = getValue(I.getCalledValue()); 5925 EVT Ty = Arg.getValueType(); 5926 5927 if (CI->isZero()) 5928 Res = DAG.getConstant(-1ULL, sdl, Ty); 5929 else 5930 Res = DAG.getConstant(0, sdl, Ty); 5931 5932 setValue(&I, Res); 5933 return nullptr; 5934 } 5935 5936 case Intrinsic::is_constant: 5937 // If this wasn't constant-folded away by now, then it's not a 5938 // constant. 5939 setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); 5940 return nullptr; 5941 5942 case Intrinsic::annotation: 5943 case Intrinsic::ptr_annotation: 5944 case Intrinsic::launder_invariant_group: 5945 case Intrinsic::strip_invariant_group: 5946 // Drop the intrinsic, but forward the value 5947 setValue(&I, getValue(I.getOperand(0))); 5948 return nullptr; 5949 case Intrinsic::assume: 5950 case Intrinsic::var_annotation: 5951 case Intrinsic::sideeffect: 5952 // Discard annotate attributes, assumptions, and artificial side-effects. 5953 return nullptr; 5954 5955 case Intrinsic::codeview_annotation: { 5956 // Emit a label associated with this metadata. 5957 MachineFunction &MF = DAG.getMachineFunction(); 5958 MCSymbol *Label = 5959 MF.getMMI().getContext().createTempSymbol("annotation", true); 5960 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 5961 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 5962 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 5963 DAG.setRoot(Res); 5964 return nullptr; 5965 } 5966 5967 case Intrinsic::init_trampoline: { 5968 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5969 5970 SDValue Ops[6]; 5971 Ops[0] = getRoot(); 5972 Ops[1] = getValue(I.getArgOperand(0)); 5973 Ops[2] = getValue(I.getArgOperand(1)); 5974 Ops[3] = getValue(I.getArgOperand(2)); 5975 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5976 Ops[5] = DAG.getSrcValue(F); 5977 5978 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 5979 5980 DAG.setRoot(Res); 5981 return nullptr; 5982 } 5983 case Intrinsic::adjust_trampoline: 5984 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 5985 TLI.getPointerTy(DAG.getDataLayout()), 5986 getValue(I.getArgOperand(0)))); 5987 return nullptr; 5988 case Intrinsic::gcroot: { 5989 assert(DAG.getMachineFunction().getFunction().hasGC() && 5990 "only valid in functions with gc specified, enforced by Verifier"); 5991 assert(GFI && "implied by previous"); 5992 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 5993 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 5994 5995 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 5996 GFI->addStackRoot(FI->getIndex(), TypeMap); 5997 return nullptr; 5998 } 5999 case Intrinsic::gcread: 6000 case Intrinsic::gcwrite: 6001 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6002 case Intrinsic::flt_rounds: 6003 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6004 return nullptr; 6005 6006 case Intrinsic::expect: 6007 // Just replace __builtin_expect(exp, c) with EXP. 6008 setValue(&I, getValue(I.getArgOperand(0))); 6009 return nullptr; 6010 6011 case Intrinsic::debugtrap: 6012 case Intrinsic::trap: { 6013 StringRef TrapFuncName = 6014 I.getAttributes() 6015 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6016 .getValueAsString(); 6017 if (TrapFuncName.empty()) { 6018 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6019 ISD::TRAP : ISD::DEBUGTRAP; 6020 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6021 return nullptr; 6022 } 6023 TargetLowering::ArgListTy Args; 6024 6025 TargetLowering::CallLoweringInfo CLI(DAG); 6026 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6027 CallingConv::C, I.getType(), 6028 DAG.getExternalSymbol(TrapFuncName.data(), 6029 TLI.getPointerTy(DAG.getDataLayout())), 6030 std::move(Args)); 6031 6032 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6033 DAG.setRoot(Result.second); 6034 return nullptr; 6035 } 6036 6037 case Intrinsic::uadd_with_overflow: 6038 case Intrinsic::sadd_with_overflow: 6039 case Intrinsic::usub_with_overflow: 6040 case Intrinsic::ssub_with_overflow: 6041 case Intrinsic::umul_with_overflow: 6042 case Intrinsic::smul_with_overflow: { 6043 ISD::NodeType Op; 6044 switch (Intrinsic) { 6045 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6046 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6047 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6048 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6049 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6050 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6051 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6052 } 6053 SDValue Op1 = getValue(I.getArgOperand(0)); 6054 SDValue Op2 = getValue(I.getArgOperand(1)); 6055 6056 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 6057 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6058 return nullptr; 6059 } 6060 case Intrinsic::prefetch: { 6061 SDValue Ops[5]; 6062 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6063 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6064 Ops[0] = DAG.getRoot(); 6065 Ops[1] = getValue(I.getArgOperand(0)); 6066 Ops[2] = getValue(I.getArgOperand(1)); 6067 Ops[3] = getValue(I.getArgOperand(2)); 6068 Ops[4] = getValue(I.getArgOperand(3)); 6069 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6070 DAG.getVTList(MVT::Other), Ops, 6071 EVT::getIntegerVT(*Context, 8), 6072 MachinePointerInfo(I.getArgOperand(0)), 6073 0, /* align */ 6074 Flags); 6075 6076 // Chain the prefetch in parallell with any pending loads, to stay out of 6077 // the way of later optimizations. 6078 PendingLoads.push_back(Result); 6079 Result = getRoot(); 6080 DAG.setRoot(Result); 6081 return nullptr; 6082 } 6083 case Intrinsic::lifetime_start: 6084 case Intrinsic::lifetime_end: { 6085 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6086 // Stack coloring is not enabled in O0, discard region information. 6087 if (TM.getOptLevel() == CodeGenOpt::None) 6088 return nullptr; 6089 6090 SmallVector<Value *, 4> Allocas; 6091 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 6092 6093 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 6094 E = Allocas.end(); Object != E; ++Object) { 6095 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6096 6097 // Could not find an Alloca. 6098 if (!LifetimeObject) 6099 continue; 6100 6101 // First check that the Alloca is static, otherwise it won't have a 6102 // valid frame index. 6103 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6104 if (SI == FuncInfo.StaticAllocaMap.end()) 6105 return nullptr; 6106 6107 int FI = SI->second; 6108 6109 SDValue Ops[2]; 6110 Ops[0] = getRoot(); 6111 Ops[1] = 6112 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 6113 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 6114 6115 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 6116 DAG.setRoot(Res); 6117 } 6118 return nullptr; 6119 } 6120 case Intrinsic::invariant_start: 6121 // Discard region information. 6122 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6123 return nullptr; 6124 case Intrinsic::invariant_end: 6125 // Discard region information. 6126 return nullptr; 6127 case Intrinsic::clear_cache: 6128 return TLI.getClearCacheBuiltinName(); 6129 case Intrinsic::donothing: 6130 // ignore 6131 return nullptr; 6132 case Intrinsic::experimental_stackmap: 6133 visitStackmap(I); 6134 return nullptr; 6135 case Intrinsic::experimental_patchpoint_void: 6136 case Intrinsic::experimental_patchpoint_i64: 6137 visitPatchpoint(&I); 6138 return nullptr; 6139 case Intrinsic::experimental_gc_statepoint: 6140 LowerStatepoint(ImmutableStatepoint(&I)); 6141 return nullptr; 6142 case Intrinsic::experimental_gc_result: 6143 visitGCResult(cast<GCResultInst>(I)); 6144 return nullptr; 6145 case Intrinsic::experimental_gc_relocate: 6146 visitGCRelocate(cast<GCRelocateInst>(I)); 6147 return nullptr; 6148 case Intrinsic::instrprof_increment: 6149 llvm_unreachable("instrprof failed to lower an increment"); 6150 case Intrinsic::instrprof_value_profile: 6151 llvm_unreachable("instrprof failed to lower a value profiling call"); 6152 case Intrinsic::localescape: { 6153 MachineFunction &MF = DAG.getMachineFunction(); 6154 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6155 6156 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6157 // is the same on all targets. 6158 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6159 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6160 if (isa<ConstantPointerNull>(Arg)) 6161 continue; // Skip null pointers. They represent a hole in index space. 6162 AllocaInst *Slot = cast<AllocaInst>(Arg); 6163 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6164 "can only escape static allocas"); 6165 int FI = FuncInfo.StaticAllocaMap[Slot]; 6166 MCSymbol *FrameAllocSym = 6167 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6168 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6169 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6170 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6171 .addSym(FrameAllocSym) 6172 .addFrameIndex(FI); 6173 } 6174 6175 MF.setHasLocalEscape(true); 6176 6177 return nullptr; 6178 } 6179 6180 case Intrinsic::localrecover: { 6181 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6182 MachineFunction &MF = DAG.getMachineFunction(); 6183 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6184 6185 // Get the symbol that defines the frame offset. 6186 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6187 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6188 unsigned IdxVal = 6189 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6190 MCSymbol *FrameAllocSym = 6191 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6192 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6193 6194 // Create a MCSymbol for the label to avoid any target lowering 6195 // that would make this PC relative. 6196 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6197 SDValue OffsetVal = 6198 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6199 6200 // Add the offset to the FP. 6201 Value *FP = I.getArgOperand(1); 6202 SDValue FPVal = getValue(FP); 6203 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6204 setValue(&I, Add); 6205 6206 return nullptr; 6207 } 6208 6209 case Intrinsic::eh_exceptionpointer: 6210 case Intrinsic::eh_exceptioncode: { 6211 // Get the exception pointer vreg, copy from it, and resize it to fit. 6212 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6213 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6214 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6215 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6216 SDValue N = 6217 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6218 if (Intrinsic == Intrinsic::eh_exceptioncode) 6219 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6220 setValue(&I, N); 6221 return nullptr; 6222 } 6223 case Intrinsic::xray_customevent: { 6224 // Here we want to make sure that the intrinsic behaves as if it has a 6225 // specific calling convention, and only for x86_64. 6226 // FIXME: Support other platforms later. 6227 const auto &Triple = DAG.getTarget().getTargetTriple(); 6228 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6229 return nullptr; 6230 6231 SDLoc DL = getCurSDLoc(); 6232 SmallVector<SDValue, 8> Ops; 6233 6234 // We want to say that we always want the arguments in registers. 6235 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6236 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6237 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6238 SDValue Chain = getRoot(); 6239 Ops.push_back(LogEntryVal); 6240 Ops.push_back(StrSizeVal); 6241 Ops.push_back(Chain); 6242 6243 // We need to enforce the calling convention for the callsite, so that 6244 // argument ordering is enforced correctly, and that register allocation can 6245 // see that some registers may be assumed clobbered and have to preserve 6246 // them across calls to the intrinsic. 6247 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6248 DL, NodeTys, Ops); 6249 SDValue patchableNode = SDValue(MN, 0); 6250 DAG.setRoot(patchableNode); 6251 setValue(&I, patchableNode); 6252 return nullptr; 6253 } 6254 case Intrinsic::xray_typedevent: { 6255 // Here we want to make sure that the intrinsic behaves as if it has a 6256 // specific calling convention, and only for x86_64. 6257 // FIXME: Support other platforms later. 6258 const auto &Triple = DAG.getTarget().getTargetTriple(); 6259 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6260 return nullptr; 6261 6262 SDLoc DL = getCurSDLoc(); 6263 SmallVector<SDValue, 8> Ops; 6264 6265 // We want to say that we always want the arguments in registers. 6266 // It's unclear to me how manipulating the selection DAG here forces callers 6267 // to provide arguments in registers instead of on the stack. 6268 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6269 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6270 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6271 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6272 SDValue Chain = getRoot(); 6273 Ops.push_back(LogTypeId); 6274 Ops.push_back(LogEntryVal); 6275 Ops.push_back(StrSizeVal); 6276 Ops.push_back(Chain); 6277 6278 // We need to enforce the calling convention for the callsite, so that 6279 // argument ordering is enforced correctly, and that register allocation can 6280 // see that some registers may be assumed clobbered and have to preserve 6281 // them across calls to the intrinsic. 6282 MachineSDNode *MN = DAG.getMachineNode( 6283 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6284 SDValue patchableNode = SDValue(MN, 0); 6285 DAG.setRoot(patchableNode); 6286 setValue(&I, patchableNode); 6287 return nullptr; 6288 } 6289 case Intrinsic::experimental_deoptimize: 6290 LowerDeoptimizeCall(&I); 6291 return nullptr; 6292 6293 case Intrinsic::experimental_vector_reduce_fadd: 6294 case Intrinsic::experimental_vector_reduce_fmul: 6295 case Intrinsic::experimental_vector_reduce_add: 6296 case Intrinsic::experimental_vector_reduce_mul: 6297 case Intrinsic::experimental_vector_reduce_and: 6298 case Intrinsic::experimental_vector_reduce_or: 6299 case Intrinsic::experimental_vector_reduce_xor: 6300 case Intrinsic::experimental_vector_reduce_smax: 6301 case Intrinsic::experimental_vector_reduce_smin: 6302 case Intrinsic::experimental_vector_reduce_umax: 6303 case Intrinsic::experimental_vector_reduce_umin: 6304 case Intrinsic::experimental_vector_reduce_fmax: 6305 case Intrinsic::experimental_vector_reduce_fmin: 6306 visitVectorReduce(I, Intrinsic); 6307 return nullptr; 6308 6309 case Intrinsic::icall_branch_funnel: { 6310 SmallVector<SDValue, 16> Ops; 6311 Ops.push_back(DAG.getRoot()); 6312 Ops.push_back(getValue(I.getArgOperand(0))); 6313 6314 int64_t Offset; 6315 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6316 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6317 if (!Base) 6318 report_fatal_error( 6319 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6320 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6321 6322 struct BranchFunnelTarget { 6323 int64_t Offset; 6324 SDValue Target; 6325 }; 6326 SmallVector<BranchFunnelTarget, 8> Targets; 6327 6328 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6329 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6330 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6331 if (ElemBase != Base) 6332 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6333 "to the same GlobalValue"); 6334 6335 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6336 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6337 if (!GA) 6338 report_fatal_error( 6339 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6340 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6341 GA->getGlobal(), getCurSDLoc(), 6342 Val.getValueType(), GA->getOffset())}); 6343 } 6344 llvm::sort(Targets, 6345 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6346 return T1.Offset < T2.Offset; 6347 }); 6348 6349 for (auto &T : Targets) { 6350 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6351 Ops.push_back(T.Target); 6352 } 6353 6354 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6355 getCurSDLoc(), MVT::Other, Ops), 6356 0); 6357 DAG.setRoot(N); 6358 setValue(&I, N); 6359 HasTailCall = true; 6360 return nullptr; 6361 } 6362 6363 case Intrinsic::wasm_landingpad_index: 6364 // Information this intrinsic contained has been transferred to 6365 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6366 // delete it now. 6367 return nullptr; 6368 } 6369 } 6370 6371 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6372 const ConstrainedFPIntrinsic &FPI) { 6373 SDLoc sdl = getCurSDLoc(); 6374 unsigned Opcode; 6375 switch (FPI.getIntrinsicID()) { 6376 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6377 case Intrinsic::experimental_constrained_fadd: 6378 Opcode = ISD::STRICT_FADD; 6379 break; 6380 case Intrinsic::experimental_constrained_fsub: 6381 Opcode = ISD::STRICT_FSUB; 6382 break; 6383 case Intrinsic::experimental_constrained_fmul: 6384 Opcode = ISD::STRICT_FMUL; 6385 break; 6386 case Intrinsic::experimental_constrained_fdiv: 6387 Opcode = ISD::STRICT_FDIV; 6388 break; 6389 case Intrinsic::experimental_constrained_frem: 6390 Opcode = ISD::STRICT_FREM; 6391 break; 6392 case Intrinsic::experimental_constrained_fma: 6393 Opcode = ISD::STRICT_FMA; 6394 break; 6395 case Intrinsic::experimental_constrained_sqrt: 6396 Opcode = ISD::STRICT_FSQRT; 6397 break; 6398 case Intrinsic::experimental_constrained_pow: 6399 Opcode = ISD::STRICT_FPOW; 6400 break; 6401 case Intrinsic::experimental_constrained_powi: 6402 Opcode = ISD::STRICT_FPOWI; 6403 break; 6404 case Intrinsic::experimental_constrained_sin: 6405 Opcode = ISD::STRICT_FSIN; 6406 break; 6407 case Intrinsic::experimental_constrained_cos: 6408 Opcode = ISD::STRICT_FCOS; 6409 break; 6410 case Intrinsic::experimental_constrained_exp: 6411 Opcode = ISD::STRICT_FEXP; 6412 break; 6413 case Intrinsic::experimental_constrained_exp2: 6414 Opcode = ISD::STRICT_FEXP2; 6415 break; 6416 case Intrinsic::experimental_constrained_log: 6417 Opcode = ISD::STRICT_FLOG; 6418 break; 6419 case Intrinsic::experimental_constrained_log10: 6420 Opcode = ISD::STRICT_FLOG10; 6421 break; 6422 case Intrinsic::experimental_constrained_log2: 6423 Opcode = ISD::STRICT_FLOG2; 6424 break; 6425 case Intrinsic::experimental_constrained_rint: 6426 Opcode = ISD::STRICT_FRINT; 6427 break; 6428 case Intrinsic::experimental_constrained_nearbyint: 6429 Opcode = ISD::STRICT_FNEARBYINT; 6430 break; 6431 case Intrinsic::experimental_constrained_maxnum: 6432 Opcode = ISD::STRICT_FMAXNUM; 6433 break; 6434 case Intrinsic::experimental_constrained_minnum: 6435 Opcode = ISD::STRICT_FMINNUM; 6436 break; 6437 case Intrinsic::experimental_constrained_ceil: 6438 Opcode = ISD::STRICT_FCEIL; 6439 break; 6440 case Intrinsic::experimental_constrained_floor: 6441 Opcode = ISD::STRICT_FFLOOR; 6442 break; 6443 case Intrinsic::experimental_constrained_round: 6444 Opcode = ISD::STRICT_FROUND; 6445 break; 6446 case Intrinsic::experimental_constrained_trunc: 6447 Opcode = ISD::STRICT_FTRUNC; 6448 break; 6449 } 6450 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6451 SDValue Chain = getRoot(); 6452 SmallVector<EVT, 4> ValueVTs; 6453 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6454 ValueVTs.push_back(MVT::Other); // Out chain 6455 6456 SDVTList VTs = DAG.getVTList(ValueVTs); 6457 SDValue Result; 6458 if (FPI.isUnaryOp()) 6459 Result = DAG.getNode(Opcode, sdl, VTs, 6460 { Chain, getValue(FPI.getArgOperand(0)) }); 6461 else if (FPI.isTernaryOp()) 6462 Result = DAG.getNode(Opcode, sdl, VTs, 6463 { Chain, getValue(FPI.getArgOperand(0)), 6464 getValue(FPI.getArgOperand(1)), 6465 getValue(FPI.getArgOperand(2)) }); 6466 else 6467 Result = DAG.getNode(Opcode, sdl, VTs, 6468 { Chain, getValue(FPI.getArgOperand(0)), 6469 getValue(FPI.getArgOperand(1)) }); 6470 6471 assert(Result.getNode()->getNumValues() == 2); 6472 SDValue OutChain = Result.getValue(1); 6473 DAG.setRoot(OutChain); 6474 SDValue FPResult = Result.getValue(0); 6475 setValue(&FPI, FPResult); 6476 } 6477 6478 std::pair<SDValue, SDValue> 6479 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6480 const BasicBlock *EHPadBB) { 6481 MachineFunction &MF = DAG.getMachineFunction(); 6482 MachineModuleInfo &MMI = MF.getMMI(); 6483 MCSymbol *BeginLabel = nullptr; 6484 6485 if (EHPadBB) { 6486 // Insert a label before the invoke call to mark the try range. This can be 6487 // used to detect deletion of the invoke via the MachineModuleInfo. 6488 BeginLabel = MMI.getContext().createTempSymbol(); 6489 6490 // For SjLj, keep track of which landing pads go with which invokes 6491 // so as to maintain the ordering of pads in the LSDA. 6492 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6493 if (CallSiteIndex) { 6494 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6495 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6496 6497 // Now that the call site is handled, stop tracking it. 6498 MMI.setCurrentCallSite(0); 6499 } 6500 6501 // Both PendingLoads and PendingExports must be flushed here; 6502 // this call might not return. 6503 (void)getRoot(); 6504 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6505 6506 CLI.setChain(getRoot()); 6507 } 6508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6509 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6510 6511 assert((CLI.IsTailCall || Result.second.getNode()) && 6512 "Non-null chain expected with non-tail call!"); 6513 assert((Result.second.getNode() || !Result.first.getNode()) && 6514 "Null value expected with tail call!"); 6515 6516 if (!Result.second.getNode()) { 6517 // As a special case, a null chain means that a tail call has been emitted 6518 // and the DAG root is already updated. 6519 HasTailCall = true; 6520 6521 // Since there's no actual continuation from this block, nothing can be 6522 // relying on us setting vregs for them. 6523 PendingExports.clear(); 6524 } else { 6525 DAG.setRoot(Result.second); 6526 } 6527 6528 if (EHPadBB) { 6529 // Insert a label at the end of the invoke call to mark the try range. This 6530 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6531 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6532 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6533 6534 // Inform MachineModuleInfo of range. 6535 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6536 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6537 // actually use outlined funclets and their LSDA info style. 6538 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6539 assert(CLI.CS); 6540 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6541 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6542 BeginLabel, EndLabel); 6543 } else if (!isScopedEHPersonality(Pers)) { 6544 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6545 } 6546 } 6547 6548 return Result; 6549 } 6550 6551 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6552 bool isTailCall, 6553 const BasicBlock *EHPadBB) { 6554 auto &DL = DAG.getDataLayout(); 6555 FunctionType *FTy = CS.getFunctionType(); 6556 Type *RetTy = CS.getType(); 6557 6558 TargetLowering::ArgListTy Args; 6559 Args.reserve(CS.arg_size()); 6560 6561 const Value *SwiftErrorVal = nullptr; 6562 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6563 6564 // We can't tail call inside a function with a swifterror argument. Lowering 6565 // does not support this yet. It would have to move into the swifterror 6566 // register before the call. 6567 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6568 if (TLI.supportSwiftError() && 6569 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6570 isTailCall = false; 6571 6572 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6573 i != e; ++i) { 6574 TargetLowering::ArgListEntry Entry; 6575 const Value *V = *i; 6576 6577 // Skip empty types 6578 if (V->getType()->isEmptyTy()) 6579 continue; 6580 6581 SDValue ArgNode = getValue(V); 6582 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6583 6584 Entry.setAttributes(&CS, i - CS.arg_begin()); 6585 6586 // Use swifterror virtual register as input to the call. 6587 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6588 SwiftErrorVal = V; 6589 // We find the virtual register for the actual swifterror argument. 6590 // Instead of using the Value, we use the virtual register instead. 6591 Entry.Node = DAG.getRegister(FuncInfo 6592 .getOrCreateSwiftErrorVRegUseAt( 6593 CS.getInstruction(), FuncInfo.MBB, V) 6594 .first, 6595 EVT(TLI.getPointerTy(DL))); 6596 } 6597 6598 Args.push_back(Entry); 6599 6600 // If we have an explicit sret argument that is an Instruction, (i.e., it 6601 // might point to function-local memory), we can't meaningfully tail-call. 6602 if (Entry.IsSRet && isa<Instruction>(V)) 6603 isTailCall = false; 6604 } 6605 6606 // Check if target-independent constraints permit a tail call here. 6607 // Target-dependent constraints are checked within TLI->LowerCallTo. 6608 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6609 isTailCall = false; 6610 6611 // Disable tail calls if there is an swifterror argument. Targets have not 6612 // been updated to support tail calls. 6613 if (TLI.supportSwiftError() && SwiftErrorVal) 6614 isTailCall = false; 6615 6616 TargetLowering::CallLoweringInfo CLI(DAG); 6617 CLI.setDebugLoc(getCurSDLoc()) 6618 .setChain(getRoot()) 6619 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6620 .setTailCall(isTailCall) 6621 .setConvergent(CS.isConvergent()); 6622 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6623 6624 if (Result.first.getNode()) { 6625 const Instruction *Inst = CS.getInstruction(); 6626 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6627 setValue(Inst, Result.first); 6628 } 6629 6630 // The last element of CLI.InVals has the SDValue for swifterror return. 6631 // Here we copy it to a virtual register and update SwiftErrorMap for 6632 // book-keeping. 6633 if (SwiftErrorVal && TLI.supportSwiftError()) { 6634 // Get the last element of InVals. 6635 SDValue Src = CLI.InVals.back(); 6636 unsigned VReg; bool CreatedVReg; 6637 std::tie(VReg, CreatedVReg) = 6638 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6639 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6640 // We update the virtual register for the actual swifterror argument. 6641 if (CreatedVReg) 6642 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6643 DAG.setRoot(CopyNode); 6644 } 6645 } 6646 6647 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6648 SelectionDAGBuilder &Builder) { 6649 // Check to see if this load can be trivially constant folded, e.g. if the 6650 // input is from a string literal. 6651 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6652 // Cast pointer to the type we really want to load. 6653 Type *LoadTy = 6654 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6655 if (LoadVT.isVector()) 6656 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6657 6658 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6659 PointerType::getUnqual(LoadTy)); 6660 6661 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6662 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6663 return Builder.getValue(LoadCst); 6664 } 6665 6666 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6667 // still constant memory, the input chain can be the entry node. 6668 SDValue Root; 6669 bool ConstantMemory = false; 6670 6671 // Do not serialize (non-volatile) loads of constant memory with anything. 6672 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6673 Root = Builder.DAG.getEntryNode(); 6674 ConstantMemory = true; 6675 } else { 6676 // Do not serialize non-volatile loads against each other. 6677 Root = Builder.DAG.getRoot(); 6678 } 6679 6680 SDValue Ptr = Builder.getValue(PtrVal); 6681 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6682 Ptr, MachinePointerInfo(PtrVal), 6683 /* Alignment = */ 1); 6684 6685 if (!ConstantMemory) 6686 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6687 return LoadVal; 6688 } 6689 6690 /// Record the value for an instruction that produces an integer result, 6691 /// converting the type where necessary. 6692 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6693 SDValue Value, 6694 bool IsSigned) { 6695 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6696 I.getType(), true); 6697 if (IsSigned) 6698 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6699 else 6700 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6701 setValue(&I, Value); 6702 } 6703 6704 /// See if we can lower a memcmp call into an optimized form. If so, return 6705 /// true and lower it. Otherwise return false, and it will be lowered like a 6706 /// normal call. 6707 /// The caller already checked that \p I calls the appropriate LibFunc with a 6708 /// correct prototype. 6709 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6710 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6711 const Value *Size = I.getArgOperand(2); 6712 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6713 if (CSize && CSize->getZExtValue() == 0) { 6714 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6715 I.getType(), true); 6716 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6717 return true; 6718 } 6719 6720 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6721 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6722 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6723 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6724 if (Res.first.getNode()) { 6725 processIntegerCallValue(I, Res.first, true); 6726 PendingLoads.push_back(Res.second); 6727 return true; 6728 } 6729 6730 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6731 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6732 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6733 return false; 6734 6735 // If the target has a fast compare for the given size, it will return a 6736 // preferred load type for that size. Require that the load VT is legal and 6737 // that the target supports unaligned loads of that type. Otherwise, return 6738 // INVALID. 6739 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6740 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6741 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6742 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6743 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6744 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6745 // TODO: Check alignment of src and dest ptrs. 6746 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6747 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6748 if (!TLI.isTypeLegal(LVT) || 6749 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6750 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6751 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6752 } 6753 6754 return LVT; 6755 }; 6756 6757 // This turns into unaligned loads. We only do this if the target natively 6758 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6759 // we'll only produce a small number of byte loads. 6760 MVT LoadVT; 6761 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6762 switch (NumBitsToCompare) { 6763 default: 6764 return false; 6765 case 16: 6766 LoadVT = MVT::i16; 6767 break; 6768 case 32: 6769 LoadVT = MVT::i32; 6770 break; 6771 case 64: 6772 case 128: 6773 case 256: 6774 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6775 break; 6776 } 6777 6778 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6779 return false; 6780 6781 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6782 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6783 6784 // Bitcast to a wide integer type if the loads are vectors. 6785 if (LoadVT.isVector()) { 6786 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6787 LoadL = DAG.getBitcast(CmpVT, LoadL); 6788 LoadR = DAG.getBitcast(CmpVT, LoadR); 6789 } 6790 6791 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6792 processIntegerCallValue(I, Cmp, false); 6793 return true; 6794 } 6795 6796 /// See if we can lower a memchr call into an optimized form. If so, return 6797 /// true and lower it. Otherwise return false, and it will be lowered like a 6798 /// normal call. 6799 /// The caller already checked that \p I calls the appropriate LibFunc with a 6800 /// correct prototype. 6801 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6802 const Value *Src = I.getArgOperand(0); 6803 const Value *Char = I.getArgOperand(1); 6804 const Value *Length = I.getArgOperand(2); 6805 6806 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6807 std::pair<SDValue, SDValue> Res = 6808 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6809 getValue(Src), getValue(Char), getValue(Length), 6810 MachinePointerInfo(Src)); 6811 if (Res.first.getNode()) { 6812 setValue(&I, Res.first); 6813 PendingLoads.push_back(Res.second); 6814 return true; 6815 } 6816 6817 return false; 6818 } 6819 6820 /// See if we can lower a mempcpy call into an optimized form. If so, return 6821 /// true and lower it. Otherwise return false, and it will be lowered like a 6822 /// normal call. 6823 /// The caller already checked that \p I calls the appropriate LibFunc with a 6824 /// correct prototype. 6825 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6826 SDValue Dst = getValue(I.getArgOperand(0)); 6827 SDValue Src = getValue(I.getArgOperand(1)); 6828 SDValue Size = getValue(I.getArgOperand(2)); 6829 6830 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6831 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6832 unsigned Align = std::min(DstAlign, SrcAlign); 6833 if (Align == 0) // Alignment of one or both could not be inferred. 6834 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6835 6836 bool isVol = false; 6837 SDLoc sdl = getCurSDLoc(); 6838 6839 // In the mempcpy context we need to pass in a false value for isTailCall 6840 // because the return pointer needs to be adjusted by the size of 6841 // the copied memory. 6842 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6843 false, /*isTailCall=*/false, 6844 MachinePointerInfo(I.getArgOperand(0)), 6845 MachinePointerInfo(I.getArgOperand(1))); 6846 assert(MC.getNode() != nullptr && 6847 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6848 DAG.setRoot(MC); 6849 6850 // Check if Size needs to be truncated or extended. 6851 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6852 6853 // Adjust return pointer to point just past the last dst byte. 6854 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6855 Dst, Size); 6856 setValue(&I, DstPlusSize); 6857 return true; 6858 } 6859 6860 /// See if we can lower a strcpy call into an optimized form. If so, return 6861 /// true and lower it, otherwise return false and it will be lowered like a 6862 /// normal call. 6863 /// The caller already checked that \p I calls the appropriate LibFunc with a 6864 /// correct prototype. 6865 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6866 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6867 6868 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6869 std::pair<SDValue, SDValue> Res = 6870 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6871 getValue(Arg0), getValue(Arg1), 6872 MachinePointerInfo(Arg0), 6873 MachinePointerInfo(Arg1), isStpcpy); 6874 if (Res.first.getNode()) { 6875 setValue(&I, Res.first); 6876 DAG.setRoot(Res.second); 6877 return true; 6878 } 6879 6880 return false; 6881 } 6882 6883 /// See if we can lower a strcmp call into an optimized form. If so, return 6884 /// true and lower it, otherwise return false and it will be lowered like a 6885 /// normal call. 6886 /// The caller already checked that \p I calls the appropriate LibFunc with a 6887 /// correct prototype. 6888 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6889 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6890 6891 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6892 std::pair<SDValue, SDValue> Res = 6893 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6894 getValue(Arg0), getValue(Arg1), 6895 MachinePointerInfo(Arg0), 6896 MachinePointerInfo(Arg1)); 6897 if (Res.first.getNode()) { 6898 processIntegerCallValue(I, Res.first, true); 6899 PendingLoads.push_back(Res.second); 6900 return true; 6901 } 6902 6903 return false; 6904 } 6905 6906 /// See if we can lower a strlen call into an optimized form. If so, return 6907 /// true and lower it, otherwise return false and it will be lowered like a 6908 /// normal call. 6909 /// The caller already checked that \p I calls the appropriate LibFunc with a 6910 /// correct prototype. 6911 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6912 const Value *Arg0 = I.getArgOperand(0); 6913 6914 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6915 std::pair<SDValue, SDValue> Res = 6916 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6917 getValue(Arg0), MachinePointerInfo(Arg0)); 6918 if (Res.first.getNode()) { 6919 processIntegerCallValue(I, Res.first, false); 6920 PendingLoads.push_back(Res.second); 6921 return true; 6922 } 6923 6924 return false; 6925 } 6926 6927 /// See if we can lower a strnlen call into an optimized form. If so, return 6928 /// true and lower it, otherwise return false and it will be lowered like a 6929 /// normal call. 6930 /// The caller already checked that \p I calls the appropriate LibFunc with a 6931 /// correct prototype. 6932 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6933 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6934 6935 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6936 std::pair<SDValue, SDValue> Res = 6937 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6938 getValue(Arg0), getValue(Arg1), 6939 MachinePointerInfo(Arg0)); 6940 if (Res.first.getNode()) { 6941 processIntegerCallValue(I, Res.first, false); 6942 PendingLoads.push_back(Res.second); 6943 return true; 6944 } 6945 6946 return false; 6947 } 6948 6949 /// See if we can lower a unary floating-point operation into an SDNode with 6950 /// the specified Opcode. If so, return true and lower it, otherwise return 6951 /// false and it will be lowered like a normal call. 6952 /// The caller already checked that \p I calls the appropriate LibFunc with a 6953 /// correct prototype. 6954 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6955 unsigned Opcode) { 6956 // We already checked this call's prototype; verify it doesn't modify errno. 6957 if (!I.onlyReadsMemory()) 6958 return false; 6959 6960 SDValue Tmp = getValue(I.getArgOperand(0)); 6961 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6962 return true; 6963 } 6964 6965 /// See if we can lower a binary floating-point operation into an SDNode with 6966 /// the specified Opcode. If so, return true and lower it. Otherwise return 6967 /// false, and it will be lowered like a normal call. 6968 /// The caller already checked that \p I calls the appropriate LibFunc with a 6969 /// correct prototype. 6970 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6971 unsigned Opcode) { 6972 // We already checked this call's prototype; verify it doesn't modify errno. 6973 if (!I.onlyReadsMemory()) 6974 return false; 6975 6976 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6977 SDValue Tmp1 = getValue(I.getArgOperand(1)); 6978 EVT VT = Tmp0.getValueType(); 6979 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 6980 return true; 6981 } 6982 6983 void SelectionDAGBuilder::visitCall(const CallInst &I) { 6984 // Handle inline assembly differently. 6985 if (isa<InlineAsm>(I.getCalledValue())) { 6986 visitInlineAsm(&I); 6987 return; 6988 } 6989 6990 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6991 computeUsesVAFloatArgument(I, MMI); 6992 6993 const char *RenameFn = nullptr; 6994 if (Function *F = I.getCalledFunction()) { 6995 if (F->isDeclaration()) { 6996 // Is this an LLVM intrinsic or a target-specific intrinsic? 6997 unsigned IID = F->getIntrinsicID(); 6998 if (!IID) 6999 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7000 IID = II->getIntrinsicID(F); 7001 7002 if (IID) { 7003 RenameFn = visitIntrinsicCall(I, IID); 7004 if (!RenameFn) 7005 return; 7006 } 7007 } 7008 7009 // Check for well-known libc/libm calls. If the function is internal, it 7010 // can't be a library call. Don't do the check if marked as nobuiltin for 7011 // some reason or the call site requires strict floating point semantics. 7012 LibFunc Func; 7013 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7014 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7015 LibInfo->hasOptimizedCodeGen(Func)) { 7016 switch (Func) { 7017 default: break; 7018 case LibFunc_copysign: 7019 case LibFunc_copysignf: 7020 case LibFunc_copysignl: 7021 // We already checked this call's prototype; verify it doesn't modify 7022 // errno. 7023 if (I.onlyReadsMemory()) { 7024 SDValue LHS = getValue(I.getArgOperand(0)); 7025 SDValue RHS = getValue(I.getArgOperand(1)); 7026 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7027 LHS.getValueType(), LHS, RHS)); 7028 return; 7029 } 7030 break; 7031 case LibFunc_fabs: 7032 case LibFunc_fabsf: 7033 case LibFunc_fabsl: 7034 if (visitUnaryFloatCall(I, ISD::FABS)) 7035 return; 7036 break; 7037 case LibFunc_fmin: 7038 case LibFunc_fminf: 7039 case LibFunc_fminl: 7040 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7041 return; 7042 break; 7043 case LibFunc_fmax: 7044 case LibFunc_fmaxf: 7045 case LibFunc_fmaxl: 7046 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7047 return; 7048 break; 7049 case LibFunc_sin: 7050 case LibFunc_sinf: 7051 case LibFunc_sinl: 7052 if (visitUnaryFloatCall(I, ISD::FSIN)) 7053 return; 7054 break; 7055 case LibFunc_cos: 7056 case LibFunc_cosf: 7057 case LibFunc_cosl: 7058 if (visitUnaryFloatCall(I, ISD::FCOS)) 7059 return; 7060 break; 7061 case LibFunc_sqrt: 7062 case LibFunc_sqrtf: 7063 case LibFunc_sqrtl: 7064 case LibFunc_sqrt_finite: 7065 case LibFunc_sqrtf_finite: 7066 case LibFunc_sqrtl_finite: 7067 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7068 return; 7069 break; 7070 case LibFunc_floor: 7071 case LibFunc_floorf: 7072 case LibFunc_floorl: 7073 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7074 return; 7075 break; 7076 case LibFunc_nearbyint: 7077 case LibFunc_nearbyintf: 7078 case LibFunc_nearbyintl: 7079 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7080 return; 7081 break; 7082 case LibFunc_ceil: 7083 case LibFunc_ceilf: 7084 case LibFunc_ceill: 7085 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7086 return; 7087 break; 7088 case LibFunc_rint: 7089 case LibFunc_rintf: 7090 case LibFunc_rintl: 7091 if (visitUnaryFloatCall(I, ISD::FRINT)) 7092 return; 7093 break; 7094 case LibFunc_round: 7095 case LibFunc_roundf: 7096 case LibFunc_roundl: 7097 if (visitUnaryFloatCall(I, ISD::FROUND)) 7098 return; 7099 break; 7100 case LibFunc_trunc: 7101 case LibFunc_truncf: 7102 case LibFunc_truncl: 7103 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7104 return; 7105 break; 7106 case LibFunc_log2: 7107 case LibFunc_log2f: 7108 case LibFunc_log2l: 7109 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7110 return; 7111 break; 7112 case LibFunc_exp2: 7113 case LibFunc_exp2f: 7114 case LibFunc_exp2l: 7115 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7116 return; 7117 break; 7118 case LibFunc_memcmp: 7119 if (visitMemCmpCall(I)) 7120 return; 7121 break; 7122 case LibFunc_mempcpy: 7123 if (visitMemPCpyCall(I)) 7124 return; 7125 break; 7126 case LibFunc_memchr: 7127 if (visitMemChrCall(I)) 7128 return; 7129 break; 7130 case LibFunc_strcpy: 7131 if (visitStrCpyCall(I, false)) 7132 return; 7133 break; 7134 case LibFunc_stpcpy: 7135 if (visitStrCpyCall(I, true)) 7136 return; 7137 break; 7138 case LibFunc_strcmp: 7139 if (visitStrCmpCall(I)) 7140 return; 7141 break; 7142 case LibFunc_strlen: 7143 if (visitStrLenCall(I)) 7144 return; 7145 break; 7146 case LibFunc_strnlen: 7147 if (visitStrNLenCall(I)) 7148 return; 7149 break; 7150 } 7151 } 7152 } 7153 7154 SDValue Callee; 7155 if (!RenameFn) 7156 Callee = getValue(I.getCalledValue()); 7157 else 7158 Callee = DAG.getExternalSymbol( 7159 RenameFn, 7160 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7161 7162 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7163 // have to do anything here to lower funclet bundles. 7164 assert(!I.hasOperandBundlesOtherThan( 7165 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7166 "Cannot lower calls with arbitrary operand bundles!"); 7167 7168 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7169 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7170 else 7171 // Check if we can potentially perform a tail call. More detailed checking 7172 // is be done within LowerCallTo, after more information about the call is 7173 // known. 7174 LowerCallTo(&I, Callee, I.isTailCall()); 7175 } 7176 7177 namespace { 7178 7179 /// AsmOperandInfo - This contains information for each constraint that we are 7180 /// lowering. 7181 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7182 public: 7183 /// CallOperand - If this is the result output operand or a clobber 7184 /// this is null, otherwise it is the incoming operand to the CallInst. 7185 /// This gets modified as the asm is processed. 7186 SDValue CallOperand; 7187 7188 /// AssignedRegs - If this is a register or register class operand, this 7189 /// contains the set of register corresponding to the operand. 7190 RegsForValue AssignedRegs; 7191 7192 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7193 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7194 } 7195 7196 /// Whether or not this operand accesses memory 7197 bool hasMemory(const TargetLowering &TLI) const { 7198 // Indirect operand accesses access memory. 7199 if (isIndirect) 7200 return true; 7201 7202 for (const auto &Code : Codes) 7203 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7204 return true; 7205 7206 return false; 7207 } 7208 7209 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7210 /// corresponds to. If there is no Value* for this operand, it returns 7211 /// MVT::Other. 7212 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7213 const DataLayout &DL) const { 7214 if (!CallOperandVal) return MVT::Other; 7215 7216 if (isa<BasicBlock>(CallOperandVal)) 7217 return TLI.getPointerTy(DL); 7218 7219 llvm::Type *OpTy = CallOperandVal->getType(); 7220 7221 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7222 // If this is an indirect operand, the operand is a pointer to the 7223 // accessed type. 7224 if (isIndirect) { 7225 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7226 if (!PtrTy) 7227 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7228 OpTy = PtrTy->getElementType(); 7229 } 7230 7231 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7232 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7233 if (STy->getNumElements() == 1) 7234 OpTy = STy->getElementType(0); 7235 7236 // If OpTy is not a single value, it may be a struct/union that we 7237 // can tile with integers. 7238 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7239 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7240 switch (BitSize) { 7241 default: break; 7242 case 1: 7243 case 8: 7244 case 16: 7245 case 32: 7246 case 64: 7247 case 128: 7248 OpTy = IntegerType::get(Context, BitSize); 7249 break; 7250 } 7251 } 7252 7253 return TLI.getValueType(DL, OpTy, true); 7254 } 7255 }; 7256 7257 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7258 7259 } // end anonymous namespace 7260 7261 /// Make sure that the output operand \p OpInfo and its corresponding input 7262 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7263 /// out). 7264 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7265 SDISelAsmOperandInfo &MatchingOpInfo, 7266 SelectionDAG &DAG) { 7267 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7268 return; 7269 7270 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7271 const auto &TLI = DAG.getTargetLoweringInfo(); 7272 7273 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7274 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7275 OpInfo.ConstraintVT); 7276 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7277 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7278 MatchingOpInfo.ConstraintVT); 7279 if ((OpInfo.ConstraintVT.isInteger() != 7280 MatchingOpInfo.ConstraintVT.isInteger()) || 7281 (MatchRC.second != InputRC.second)) { 7282 // FIXME: error out in a more elegant fashion 7283 report_fatal_error("Unsupported asm: input constraint" 7284 " with a matching output constraint of" 7285 " incompatible type!"); 7286 } 7287 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7288 } 7289 7290 /// Get a direct memory input to behave well as an indirect operand. 7291 /// This may introduce stores, hence the need for a \p Chain. 7292 /// \return The (possibly updated) chain. 7293 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7294 SDISelAsmOperandInfo &OpInfo, 7295 SelectionDAG &DAG) { 7296 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7297 7298 // If we don't have an indirect input, put it in the constpool if we can, 7299 // otherwise spill it to a stack slot. 7300 // TODO: This isn't quite right. We need to handle these according to 7301 // the addressing mode that the constraint wants. Also, this may take 7302 // an additional register for the computation and we don't want that 7303 // either. 7304 7305 // If the operand is a float, integer, or vector constant, spill to a 7306 // constant pool entry to get its address. 7307 const Value *OpVal = OpInfo.CallOperandVal; 7308 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7309 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7310 OpInfo.CallOperand = DAG.getConstantPool( 7311 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7312 return Chain; 7313 } 7314 7315 // Otherwise, create a stack slot and emit a store to it before the asm. 7316 Type *Ty = OpVal->getType(); 7317 auto &DL = DAG.getDataLayout(); 7318 uint64_t TySize = DL.getTypeAllocSize(Ty); 7319 unsigned Align = DL.getPrefTypeAlignment(Ty); 7320 MachineFunction &MF = DAG.getMachineFunction(); 7321 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7322 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7323 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7324 MachinePointerInfo::getFixedStack(MF, SSFI)); 7325 OpInfo.CallOperand = StackSlot; 7326 7327 return Chain; 7328 } 7329 7330 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7331 /// specified operand. We prefer to assign virtual registers, to allow the 7332 /// register allocator to handle the assignment process. However, if the asm 7333 /// uses features that we can't model on machineinstrs, we have SDISel do the 7334 /// allocation. This produces generally horrible, but correct, code. 7335 /// 7336 /// OpInfo describes the operand 7337 /// RefOpInfo describes the matching operand if any, the operand otherwise 7338 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7339 SDISelAsmOperandInfo &OpInfo, 7340 SDISelAsmOperandInfo &RefOpInfo) { 7341 LLVMContext &Context = *DAG.getContext(); 7342 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7343 7344 MachineFunction &MF = DAG.getMachineFunction(); 7345 SmallVector<unsigned, 4> Regs; 7346 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7347 7348 // No work to do for memory operations. 7349 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7350 return; 7351 7352 // If this is a constraint for a single physreg, or a constraint for a 7353 // register class, find it. 7354 unsigned AssignedReg; 7355 const TargetRegisterClass *RC; 7356 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7357 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7358 // RC is unset only on failure. Return immediately. 7359 if (!RC) 7360 return; 7361 7362 // Get the actual register value type. This is important, because the user 7363 // may have asked for (e.g.) the AX register in i32 type. We need to 7364 // remember that AX is actually i16 to get the right extension. 7365 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7366 7367 if (OpInfo.ConstraintVT != MVT::Other) { 7368 // If this is an FP operand in an integer register (or visa versa), or more 7369 // generally if the operand value disagrees with the register class we plan 7370 // to stick it in, fix the operand type. 7371 // 7372 // If this is an input value, the bitcast to the new type is done now. 7373 // Bitcast for output value is done at the end of visitInlineAsm(). 7374 if ((OpInfo.Type == InlineAsm::isOutput || 7375 OpInfo.Type == InlineAsm::isInput) && 7376 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7377 // Try to convert to the first EVT that the reg class contains. If the 7378 // types are identical size, use a bitcast to convert (e.g. two differing 7379 // vector types). Note: output bitcast is done at the end of 7380 // visitInlineAsm(). 7381 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7382 // Exclude indirect inputs while they are unsupported because the code 7383 // to perform the load is missing and thus OpInfo.CallOperand still 7384 // refers to the input address rather than the pointed-to value. 7385 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7386 OpInfo.CallOperand = 7387 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7388 OpInfo.ConstraintVT = RegVT; 7389 // If the operand is an FP value and we want it in integer registers, 7390 // use the corresponding integer type. This turns an f64 value into 7391 // i64, which can be passed with two i32 values on a 32-bit machine. 7392 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7393 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7394 if (OpInfo.Type == InlineAsm::isInput) 7395 OpInfo.CallOperand = 7396 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7397 OpInfo.ConstraintVT = VT; 7398 } 7399 } 7400 } 7401 7402 // No need to allocate a matching input constraint since the constraint it's 7403 // matching to has already been allocated. 7404 if (OpInfo.isMatchingInputConstraint()) 7405 return; 7406 7407 EVT ValueVT = OpInfo.ConstraintVT; 7408 if (OpInfo.ConstraintVT == MVT::Other) 7409 ValueVT = RegVT; 7410 7411 // Initialize NumRegs. 7412 unsigned NumRegs = 1; 7413 if (OpInfo.ConstraintVT != MVT::Other) 7414 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7415 7416 // If this is a constraint for a specific physical register, like {r17}, 7417 // assign it now. 7418 7419 // If this associated to a specific register, initialize iterator to correct 7420 // place. If virtual, make sure we have enough registers 7421 7422 // Initialize iterator if necessary 7423 TargetRegisterClass::iterator I = RC->begin(); 7424 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7425 7426 // Do not check for single registers. 7427 if (AssignedReg) { 7428 for (; *I != AssignedReg; ++I) 7429 assert(I != RC->end() && "AssignedReg should be member of RC"); 7430 } 7431 7432 for (; NumRegs; --NumRegs, ++I) { 7433 assert(I != RC->end() && "Ran out of registers to allocate!"); 7434 auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC); 7435 Regs.push_back(R); 7436 } 7437 7438 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7439 } 7440 7441 static unsigned 7442 findMatchingInlineAsmOperand(unsigned OperandNo, 7443 const std::vector<SDValue> &AsmNodeOperands) { 7444 // Scan until we find the definition we already emitted of this operand. 7445 unsigned CurOp = InlineAsm::Op_FirstOperand; 7446 for (; OperandNo; --OperandNo) { 7447 // Advance to the next operand. 7448 unsigned OpFlag = 7449 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7450 assert((InlineAsm::isRegDefKind(OpFlag) || 7451 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7452 InlineAsm::isMemKind(OpFlag)) && 7453 "Skipped past definitions?"); 7454 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7455 } 7456 return CurOp; 7457 } 7458 7459 namespace { 7460 7461 class ExtraFlags { 7462 unsigned Flags = 0; 7463 7464 public: 7465 explicit ExtraFlags(ImmutableCallSite CS) { 7466 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7467 if (IA->hasSideEffects()) 7468 Flags |= InlineAsm::Extra_HasSideEffects; 7469 if (IA->isAlignStack()) 7470 Flags |= InlineAsm::Extra_IsAlignStack; 7471 if (CS.isConvergent()) 7472 Flags |= InlineAsm::Extra_IsConvergent; 7473 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7474 } 7475 7476 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7477 // Ideally, we would only check against memory constraints. However, the 7478 // meaning of an Other constraint can be target-specific and we can't easily 7479 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7480 // for Other constraints as well. 7481 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7482 OpInfo.ConstraintType == TargetLowering::C_Other) { 7483 if (OpInfo.Type == InlineAsm::isInput) 7484 Flags |= InlineAsm::Extra_MayLoad; 7485 else if (OpInfo.Type == InlineAsm::isOutput) 7486 Flags |= InlineAsm::Extra_MayStore; 7487 else if (OpInfo.Type == InlineAsm::isClobber) 7488 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7489 } 7490 } 7491 7492 unsigned get() const { return Flags; } 7493 }; 7494 7495 } // end anonymous namespace 7496 7497 /// visitInlineAsm - Handle a call to an InlineAsm object. 7498 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7499 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7500 7501 /// ConstraintOperands - Information about all of the constraints. 7502 SDISelAsmOperandInfoVector ConstraintOperands; 7503 7504 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7505 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7506 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7507 7508 bool hasMemory = false; 7509 7510 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7511 ExtraFlags ExtraInfo(CS); 7512 7513 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7514 unsigned ResNo = 0; // ResNo - The result number of the next output. 7515 for (auto &T : TargetConstraints) { 7516 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7517 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7518 7519 // Compute the value type for each operand. 7520 if (OpInfo.Type == InlineAsm::isInput || 7521 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7522 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7523 7524 // Process the call argument. BasicBlocks are labels, currently appearing 7525 // only in asm's. 7526 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7527 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7528 } else { 7529 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7530 } 7531 7532 OpInfo.ConstraintVT = 7533 OpInfo 7534 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7535 .getSimpleVT(); 7536 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7537 // The return value of the call is this value. As such, there is no 7538 // corresponding argument. 7539 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7540 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7541 OpInfo.ConstraintVT = TLI.getSimpleValueType( 7542 DAG.getDataLayout(), STy->getElementType(ResNo)); 7543 } else { 7544 assert(ResNo == 0 && "Asm only has one result!"); 7545 OpInfo.ConstraintVT = 7546 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7547 } 7548 ++ResNo; 7549 } else { 7550 OpInfo.ConstraintVT = MVT::Other; 7551 } 7552 7553 if (!hasMemory) 7554 hasMemory = OpInfo.hasMemory(TLI); 7555 7556 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7557 // FIXME: Could we compute this on OpInfo rather than T? 7558 7559 // Compute the constraint code and ConstraintType to use. 7560 TLI.ComputeConstraintToUse(T, SDValue()); 7561 7562 ExtraInfo.update(T); 7563 } 7564 7565 SDValue Chain, Flag; 7566 7567 // We won't need to flush pending loads if this asm doesn't touch 7568 // memory and is nonvolatile. 7569 if (hasMemory || IA->hasSideEffects()) 7570 Chain = getRoot(); 7571 else 7572 Chain = DAG.getRoot(); 7573 7574 // Second pass over the constraints: compute which constraint option to use. 7575 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7576 // If this is an output operand with a matching input operand, look up the 7577 // matching input. If their types mismatch, e.g. one is an integer, the 7578 // other is floating point, or their sizes are different, flag it as an 7579 // error. 7580 if (OpInfo.hasMatchingInput()) { 7581 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7582 patchMatchingInput(OpInfo, Input, DAG); 7583 } 7584 7585 // Compute the constraint code and ConstraintType to use. 7586 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7587 7588 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7589 OpInfo.Type == InlineAsm::isClobber) 7590 continue; 7591 7592 // If this is a memory input, and if the operand is not indirect, do what we 7593 // need to provide an address for the memory input. 7594 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7595 !OpInfo.isIndirect) { 7596 assert((OpInfo.isMultipleAlternative || 7597 (OpInfo.Type == InlineAsm::isInput)) && 7598 "Can only indirectify direct input operands!"); 7599 7600 // Memory operands really want the address of the value. 7601 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7602 7603 // There is no longer a Value* corresponding to this operand. 7604 OpInfo.CallOperandVal = nullptr; 7605 7606 // It is now an indirect operand. 7607 OpInfo.isIndirect = true; 7608 } 7609 7610 } 7611 7612 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7613 std::vector<SDValue> AsmNodeOperands; 7614 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7615 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7616 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7617 7618 // If we have a !srcloc metadata node associated with it, we want to attach 7619 // this to the ultimately generated inline asm machineinstr. To do this, we 7620 // pass in the third operand as this (potentially null) inline asm MDNode. 7621 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7622 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7623 7624 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7625 // bits as operand 3. 7626 AsmNodeOperands.push_back(DAG.getTargetConstant( 7627 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7628 7629 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 7630 // this, assign virtual and physical registers for inputs and otput. 7631 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7632 // Assign Registers. 7633 SDISelAsmOperandInfo &RefOpInfo = 7634 OpInfo.isMatchingInputConstraint() 7635 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7636 : OpInfo; 7637 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 7638 7639 switch (OpInfo.Type) { 7640 case InlineAsm::isOutput: 7641 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 7642 OpInfo.ConstraintType != TargetLowering::C_Register) { 7643 // Memory output, or 'other' output (e.g. 'X' constraint). 7644 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 7645 7646 unsigned ConstraintID = 7647 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7648 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7649 "Failed to convert memory constraint code to constraint id."); 7650 7651 // Add information to the INLINEASM node to know about this output. 7652 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7653 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7654 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7655 MVT::i32)); 7656 AsmNodeOperands.push_back(OpInfo.CallOperand); 7657 break; 7658 } else if (OpInfo.ConstraintType == TargetLowering::C_Register || 7659 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 7660 // Otherwise, this is a register or register class output. 7661 7662 // Copy the output from the appropriate register. Find a register that 7663 // we can use. 7664 if (OpInfo.AssignedRegs.Regs.empty()) { 7665 emitInlineAsmError( 7666 CS, "couldn't allocate output register for constraint '" + 7667 Twine(OpInfo.ConstraintCode) + "'"); 7668 return; 7669 } 7670 7671 // Add information to the INLINEASM node to know that this register is 7672 // set. 7673 OpInfo.AssignedRegs.AddInlineAsmOperands( 7674 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 7675 : InlineAsm::Kind_RegDef, 7676 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7677 } 7678 break; 7679 7680 case InlineAsm::isInput: { 7681 SDValue InOperandVal = OpInfo.CallOperand; 7682 7683 if (OpInfo.isMatchingInputConstraint()) { 7684 // If this is required to match an output register we have already set, 7685 // just use its register. 7686 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7687 AsmNodeOperands); 7688 unsigned OpFlag = 7689 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7690 if (InlineAsm::isRegDefKind(OpFlag) || 7691 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7692 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7693 if (OpInfo.isIndirect) { 7694 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7695 emitInlineAsmError(CS, "inline asm not supported yet:" 7696 " don't know how to handle tied " 7697 "indirect register inputs"); 7698 return; 7699 } 7700 7701 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7702 SmallVector<unsigned, 4> Regs; 7703 7704 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 7705 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 7706 MachineRegisterInfo &RegInfo = 7707 DAG.getMachineFunction().getRegInfo(); 7708 for (unsigned i = 0; i != NumRegs; ++i) 7709 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7710 } else { 7711 emitInlineAsmError(CS, "inline asm error: This value type register " 7712 "class is not natively supported!"); 7713 return; 7714 } 7715 7716 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7717 7718 SDLoc dl = getCurSDLoc(); 7719 // Use the produced MatchedRegs object to 7720 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7721 CS.getInstruction()); 7722 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7723 true, OpInfo.getMatchedOperand(), dl, 7724 DAG, AsmNodeOperands); 7725 break; 7726 } 7727 7728 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7729 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7730 "Unexpected number of operands"); 7731 // Add information to the INLINEASM node to know about this input. 7732 // See InlineAsm.h isUseOperandTiedToDef. 7733 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7734 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7735 OpInfo.getMatchedOperand()); 7736 AsmNodeOperands.push_back(DAG.getTargetConstant( 7737 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7738 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7739 break; 7740 } 7741 7742 // Treat indirect 'X' constraint as memory. 7743 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7744 OpInfo.isIndirect) 7745 OpInfo.ConstraintType = TargetLowering::C_Memory; 7746 7747 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7748 std::vector<SDValue> Ops; 7749 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7750 Ops, DAG); 7751 if (Ops.empty()) { 7752 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7753 Twine(OpInfo.ConstraintCode) + "'"); 7754 return; 7755 } 7756 7757 // Add information to the INLINEASM node to know about this input. 7758 unsigned ResOpType = 7759 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7760 AsmNodeOperands.push_back(DAG.getTargetConstant( 7761 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7762 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7763 break; 7764 } 7765 7766 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7767 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7768 assert(InOperandVal.getValueType() == 7769 TLI.getPointerTy(DAG.getDataLayout()) && 7770 "Memory operands expect pointer values"); 7771 7772 unsigned ConstraintID = 7773 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7774 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7775 "Failed to convert memory constraint code to constraint id."); 7776 7777 // Add information to the INLINEASM node to know about this input. 7778 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7779 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7780 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7781 getCurSDLoc(), 7782 MVT::i32)); 7783 AsmNodeOperands.push_back(InOperandVal); 7784 break; 7785 } 7786 7787 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7788 OpInfo.ConstraintType == TargetLowering::C_Register) && 7789 "Unknown constraint type!"); 7790 7791 // TODO: Support this. 7792 if (OpInfo.isIndirect) { 7793 emitInlineAsmError( 7794 CS, "Don't know how to handle indirect register inputs yet " 7795 "for constraint '" + 7796 Twine(OpInfo.ConstraintCode) + "'"); 7797 return; 7798 } 7799 7800 // Copy the input into the appropriate registers. 7801 if (OpInfo.AssignedRegs.Regs.empty()) { 7802 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7803 Twine(OpInfo.ConstraintCode) + "'"); 7804 return; 7805 } 7806 7807 SDLoc dl = getCurSDLoc(); 7808 7809 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7810 Chain, &Flag, CS.getInstruction()); 7811 7812 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7813 dl, DAG, AsmNodeOperands); 7814 break; 7815 } 7816 case InlineAsm::isClobber: 7817 // Add the clobbered value to the operand list, so that the register 7818 // allocator is aware that the physreg got clobbered. 7819 if (!OpInfo.AssignedRegs.Regs.empty()) 7820 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7821 false, 0, getCurSDLoc(), DAG, 7822 AsmNodeOperands); 7823 break; 7824 } 7825 } 7826 7827 // Finish up input operands. Set the input chain and add the flag last. 7828 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7829 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7830 7831 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7832 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7833 Flag = Chain.getValue(1); 7834 7835 // Do additional work to generate outputs. 7836 7837 SmallVector<EVT, 1> ResultVTs; 7838 SmallVector<SDValue, 1> ResultValues; 7839 SmallVector<SDValue, 8> OutChains; 7840 7841 llvm::Type *CSResultType = CS.getType(); 7842 unsigned NumReturns = 0; 7843 ArrayRef<Type *> ResultTypes; 7844 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) { 7845 NumReturns = StructResult->getNumElements(); 7846 ResultTypes = StructResult->elements(); 7847 } else if (!CSResultType->isVoidTy()) { 7848 NumReturns = 1; 7849 ResultTypes = makeArrayRef(CSResultType); 7850 } 7851 7852 auto CurResultType = ResultTypes.begin(); 7853 auto handleRegAssign = [&](SDValue V) { 7854 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 7855 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 7856 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 7857 ++CurResultType; 7858 // If the type of the inline asm call site return value is different but has 7859 // same size as the type of the asm output bitcast it. One example of this 7860 // is for vectors with different width / number of elements. This can 7861 // happen for register classes that can contain multiple different value 7862 // types. The preg or vreg allocated may not have the same VT as was 7863 // expected. 7864 // 7865 // This can also happen for a return value that disagrees with the register 7866 // class it is put in, eg. a double in a general-purpose register on a 7867 // 32-bit machine. 7868 if (ResultVT != V.getValueType() && 7869 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 7870 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 7871 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 7872 V.getValueType().isInteger()) { 7873 // If a result value was tied to an input value, the computed result 7874 // may have a wider width than the expected result. Extract the 7875 // relevant portion. 7876 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 7877 } 7878 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 7879 ResultVTs.push_back(ResultVT); 7880 ResultValues.push_back(V); 7881 }; 7882 7883 // Deal with assembly output fixups. 7884 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7885 if (OpInfo.Type == InlineAsm::isOutput && 7886 (OpInfo.ConstraintType == TargetLowering::C_Register || 7887 OpInfo.ConstraintType == TargetLowering::C_RegisterClass)) { 7888 if (OpInfo.isIndirect) { 7889 // Register indirect are manifest as stores. 7890 const RegsForValue &OutRegs = OpInfo.AssignedRegs; 7891 const Value *Ptr = OpInfo.CallOperandVal; 7892 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7893 Chain, &Flag, IA); 7894 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), OutVal, getValue(Ptr), 7895 MachinePointerInfo(Ptr)); 7896 OutChains.push_back(Val); 7897 } else { 7898 // generate CopyFromRegs to associated registers. 7899 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7900 SDValue Val = OpInfo.AssignedRegs.getCopyFromRegs( 7901 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 7902 if (Val.getOpcode() == ISD::MERGE_VALUES) { 7903 for (const SDValue &V : Val->op_values()) 7904 handleRegAssign(V); 7905 } else 7906 handleRegAssign(Val); 7907 } 7908 } 7909 } 7910 7911 // Set results. 7912 if (!ResultValues.empty()) { 7913 assert(CurResultType == ResultTypes.end() && 7914 "Mismatch in number of ResultTypes"); 7915 assert(ResultValues.size() == NumReturns && 7916 "Mismatch in number of output operands in asm result"); 7917 7918 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 7919 DAG.getVTList(ResultVTs), ResultValues); 7920 setValue(CS.getInstruction(), V); 7921 } 7922 7923 // Collect store chains. 7924 if (!OutChains.empty()) 7925 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7926 7927 // Only Update Root if inline assembly has a memory effect. 7928 if (ResultValues.empty() || IA->hasSideEffects() || hasMemory || 7929 !OutChains.empty()) 7930 DAG.setRoot(Chain); 7931 } 7932 7933 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 7934 const Twine &Message) { 7935 LLVMContext &Ctx = *DAG.getContext(); 7936 Ctx.emitError(CS.getInstruction(), Message); 7937 7938 // Make sure we leave the DAG in a valid state 7939 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7940 SmallVector<EVT, 1> ValueVTs; 7941 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 7942 7943 if (ValueVTs.empty()) 7944 return; 7945 7946 SmallVector<SDValue, 1> Ops; 7947 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 7948 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 7949 7950 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 7951 } 7952 7953 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 7954 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 7955 MVT::Other, getRoot(), 7956 getValue(I.getArgOperand(0)), 7957 DAG.getSrcValue(I.getArgOperand(0)))); 7958 } 7959 7960 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 7961 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7962 const DataLayout &DL = DAG.getDataLayout(); 7963 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7964 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 7965 DAG.getSrcValue(I.getOperand(0)), 7966 DL.getABITypeAlignment(I.getType())); 7967 setValue(&I, V); 7968 DAG.setRoot(V.getValue(1)); 7969 } 7970 7971 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 7972 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 7973 MVT::Other, getRoot(), 7974 getValue(I.getArgOperand(0)), 7975 DAG.getSrcValue(I.getArgOperand(0)))); 7976 } 7977 7978 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 7979 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 7980 MVT::Other, getRoot(), 7981 getValue(I.getArgOperand(0)), 7982 getValue(I.getArgOperand(1)), 7983 DAG.getSrcValue(I.getArgOperand(0)), 7984 DAG.getSrcValue(I.getArgOperand(1)))); 7985 } 7986 7987 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 7988 const Instruction &I, 7989 SDValue Op) { 7990 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 7991 if (!Range) 7992 return Op; 7993 7994 ConstantRange CR = getConstantRangeFromMetadata(*Range); 7995 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 7996 return Op; 7997 7998 APInt Lo = CR.getUnsignedMin(); 7999 if (!Lo.isMinValue()) 8000 return Op; 8001 8002 APInt Hi = CR.getUnsignedMax(); 8003 unsigned Bits = std::max(Hi.getActiveBits(), 8004 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8005 8006 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8007 8008 SDLoc SL = getCurSDLoc(); 8009 8010 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8011 DAG.getValueType(SmallVT)); 8012 unsigned NumVals = Op.getNode()->getNumValues(); 8013 if (NumVals == 1) 8014 return ZExt; 8015 8016 SmallVector<SDValue, 4> Ops; 8017 8018 Ops.push_back(ZExt); 8019 for (unsigned I = 1; I != NumVals; ++I) 8020 Ops.push_back(Op.getValue(I)); 8021 8022 return DAG.getMergeValues(Ops, SL); 8023 } 8024 8025 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8026 /// the call being lowered. 8027 /// 8028 /// This is a helper for lowering intrinsics that follow a target calling 8029 /// convention or require stack pointer adjustment. Only a subset of the 8030 /// intrinsic's operands need to participate in the calling convention. 8031 void SelectionDAGBuilder::populateCallLoweringInfo( 8032 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 8033 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8034 bool IsPatchPoint) { 8035 TargetLowering::ArgListTy Args; 8036 Args.reserve(NumArgs); 8037 8038 // Populate the argument list. 8039 // Attributes for args start at offset 1, after the return attribute. 8040 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8041 ArgI != ArgE; ++ArgI) { 8042 const Value *V = CS->getOperand(ArgI); 8043 8044 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8045 8046 TargetLowering::ArgListEntry Entry; 8047 Entry.Node = getValue(V); 8048 Entry.Ty = V->getType(); 8049 Entry.setAttributes(&CS, ArgI); 8050 Args.push_back(Entry); 8051 } 8052 8053 CLI.setDebugLoc(getCurSDLoc()) 8054 .setChain(getRoot()) 8055 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 8056 .setDiscardResult(CS->use_empty()) 8057 .setIsPatchPoint(IsPatchPoint); 8058 } 8059 8060 /// Add a stack map intrinsic call's live variable operands to a stackmap 8061 /// or patchpoint target node's operand list. 8062 /// 8063 /// Constants are converted to TargetConstants purely as an optimization to 8064 /// avoid constant materialization and register allocation. 8065 /// 8066 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8067 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 8068 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8069 /// address materialization and register allocation, but may also be required 8070 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8071 /// alloca in the entry block, then the runtime may assume that the alloca's 8072 /// StackMap location can be read immediately after compilation and that the 8073 /// location is valid at any point during execution (this is similar to the 8074 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8075 /// only available in a register, then the runtime would need to trap when 8076 /// execution reaches the StackMap in order to read the alloca's location. 8077 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8078 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8079 SelectionDAGBuilder &Builder) { 8080 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8081 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8082 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8083 Ops.push_back( 8084 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8085 Ops.push_back( 8086 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8087 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8088 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8089 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8090 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8091 } else 8092 Ops.push_back(OpVal); 8093 } 8094 } 8095 8096 /// Lower llvm.experimental.stackmap directly to its target opcode. 8097 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8098 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8099 // [live variables...]) 8100 8101 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8102 8103 SDValue Chain, InFlag, Callee, NullPtr; 8104 SmallVector<SDValue, 32> Ops; 8105 8106 SDLoc DL = getCurSDLoc(); 8107 Callee = getValue(CI.getCalledValue()); 8108 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8109 8110 // The stackmap intrinsic only records the live variables (the arguemnts 8111 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8112 // intrinsic, this won't be lowered to a function call. This means we don't 8113 // have to worry about calling conventions and target specific lowering code. 8114 // Instead we perform the call lowering right here. 8115 // 8116 // chain, flag = CALLSEQ_START(chain, 0, 0) 8117 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8118 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8119 // 8120 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8121 InFlag = Chain.getValue(1); 8122 8123 // Add the <id> and <numBytes> constants. 8124 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8125 Ops.push_back(DAG.getTargetConstant( 8126 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8127 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8128 Ops.push_back(DAG.getTargetConstant( 8129 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8130 MVT::i32)); 8131 8132 // Push live variables for the stack map. 8133 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8134 8135 // We are not pushing any register mask info here on the operands list, 8136 // because the stackmap doesn't clobber anything. 8137 8138 // Push the chain and the glue flag. 8139 Ops.push_back(Chain); 8140 Ops.push_back(InFlag); 8141 8142 // Create the STACKMAP node. 8143 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8144 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8145 Chain = SDValue(SM, 0); 8146 InFlag = Chain.getValue(1); 8147 8148 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8149 8150 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8151 8152 // Set the root to the target-lowered call chain. 8153 DAG.setRoot(Chain); 8154 8155 // Inform the Frame Information that we have a stackmap in this function. 8156 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8157 } 8158 8159 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8160 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8161 const BasicBlock *EHPadBB) { 8162 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8163 // i32 <numBytes>, 8164 // i8* <target>, 8165 // i32 <numArgs>, 8166 // [Args...], 8167 // [live variables...]) 8168 8169 CallingConv::ID CC = CS.getCallingConv(); 8170 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8171 bool HasDef = !CS->getType()->isVoidTy(); 8172 SDLoc dl = getCurSDLoc(); 8173 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8174 8175 // Handle immediate and symbolic callees. 8176 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8177 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8178 /*isTarget=*/true); 8179 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8180 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8181 SDLoc(SymbolicCallee), 8182 SymbolicCallee->getValueType(0)); 8183 8184 // Get the real number of arguments participating in the call <numArgs> 8185 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8186 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8187 8188 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8189 // Intrinsics include all meta-operands up to but not including CC. 8190 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8191 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8192 "Not enough arguments provided to the patchpoint intrinsic"); 8193 8194 // For AnyRegCC the arguments are lowered later on manually. 8195 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8196 Type *ReturnTy = 8197 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8198 8199 TargetLowering::CallLoweringInfo CLI(DAG); 8200 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 8201 true); 8202 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8203 8204 SDNode *CallEnd = Result.second.getNode(); 8205 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8206 CallEnd = CallEnd->getOperand(0).getNode(); 8207 8208 /// Get a call instruction from the call sequence chain. 8209 /// Tail calls are not allowed. 8210 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8211 "Expected a callseq node."); 8212 SDNode *Call = CallEnd->getOperand(0).getNode(); 8213 bool HasGlue = Call->getGluedNode(); 8214 8215 // Replace the target specific call node with the patchable intrinsic. 8216 SmallVector<SDValue, 8> Ops; 8217 8218 // Add the <id> and <numBytes> constants. 8219 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8220 Ops.push_back(DAG.getTargetConstant( 8221 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8222 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8223 Ops.push_back(DAG.getTargetConstant( 8224 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8225 MVT::i32)); 8226 8227 // Add the callee. 8228 Ops.push_back(Callee); 8229 8230 // Adjust <numArgs> to account for any arguments that have been passed on the 8231 // stack instead. 8232 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8233 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8234 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8235 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8236 8237 // Add the calling convention 8238 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8239 8240 // Add the arguments we omitted previously. The register allocator should 8241 // place these in any free register. 8242 if (IsAnyRegCC) 8243 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8244 Ops.push_back(getValue(CS.getArgument(i))); 8245 8246 // Push the arguments from the call instruction up to the register mask. 8247 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8248 Ops.append(Call->op_begin() + 2, e); 8249 8250 // Push live variables for the stack map. 8251 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8252 8253 // Push the register mask info. 8254 if (HasGlue) 8255 Ops.push_back(*(Call->op_end()-2)); 8256 else 8257 Ops.push_back(*(Call->op_end()-1)); 8258 8259 // Push the chain (this is originally the first operand of the call, but 8260 // becomes now the last or second to last operand). 8261 Ops.push_back(*(Call->op_begin())); 8262 8263 // Push the glue flag (last operand). 8264 if (HasGlue) 8265 Ops.push_back(*(Call->op_end()-1)); 8266 8267 SDVTList NodeTys; 8268 if (IsAnyRegCC && HasDef) { 8269 // Create the return types based on the intrinsic definition 8270 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8271 SmallVector<EVT, 3> ValueVTs; 8272 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8273 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8274 8275 // There is always a chain and a glue type at the end 8276 ValueVTs.push_back(MVT::Other); 8277 ValueVTs.push_back(MVT::Glue); 8278 NodeTys = DAG.getVTList(ValueVTs); 8279 } else 8280 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8281 8282 // Replace the target specific call node with a PATCHPOINT node. 8283 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8284 dl, NodeTys, Ops); 8285 8286 // Update the NodeMap. 8287 if (HasDef) { 8288 if (IsAnyRegCC) 8289 setValue(CS.getInstruction(), SDValue(MN, 0)); 8290 else 8291 setValue(CS.getInstruction(), Result.first); 8292 } 8293 8294 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8295 // call sequence. Furthermore the location of the chain and glue can change 8296 // when the AnyReg calling convention is used and the intrinsic returns a 8297 // value. 8298 if (IsAnyRegCC && HasDef) { 8299 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8300 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8301 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8302 } else 8303 DAG.ReplaceAllUsesWith(Call, MN); 8304 DAG.DeleteNode(Call); 8305 8306 // Inform the Frame Information that we have a patchpoint in this function. 8307 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8308 } 8309 8310 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8311 unsigned Intrinsic) { 8312 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8313 SDValue Op1 = getValue(I.getArgOperand(0)); 8314 SDValue Op2; 8315 if (I.getNumArgOperands() > 1) 8316 Op2 = getValue(I.getArgOperand(1)); 8317 SDLoc dl = getCurSDLoc(); 8318 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8319 SDValue Res; 8320 FastMathFlags FMF; 8321 if (isa<FPMathOperator>(I)) 8322 FMF = I.getFastMathFlags(); 8323 8324 switch (Intrinsic) { 8325 case Intrinsic::experimental_vector_reduce_fadd: 8326 if (FMF.isFast()) 8327 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8328 else 8329 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8330 break; 8331 case Intrinsic::experimental_vector_reduce_fmul: 8332 if (FMF.isFast()) 8333 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8334 else 8335 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8336 break; 8337 case Intrinsic::experimental_vector_reduce_add: 8338 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8339 break; 8340 case Intrinsic::experimental_vector_reduce_mul: 8341 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8342 break; 8343 case Intrinsic::experimental_vector_reduce_and: 8344 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8345 break; 8346 case Intrinsic::experimental_vector_reduce_or: 8347 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8348 break; 8349 case Intrinsic::experimental_vector_reduce_xor: 8350 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8351 break; 8352 case Intrinsic::experimental_vector_reduce_smax: 8353 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8354 break; 8355 case Intrinsic::experimental_vector_reduce_smin: 8356 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8357 break; 8358 case Intrinsic::experimental_vector_reduce_umax: 8359 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8360 break; 8361 case Intrinsic::experimental_vector_reduce_umin: 8362 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8363 break; 8364 case Intrinsic::experimental_vector_reduce_fmax: 8365 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8366 break; 8367 case Intrinsic::experimental_vector_reduce_fmin: 8368 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8369 break; 8370 default: 8371 llvm_unreachable("Unhandled vector reduce intrinsic"); 8372 } 8373 setValue(&I, Res); 8374 } 8375 8376 /// Returns an AttributeList representing the attributes applied to the return 8377 /// value of the given call. 8378 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8379 SmallVector<Attribute::AttrKind, 2> Attrs; 8380 if (CLI.RetSExt) 8381 Attrs.push_back(Attribute::SExt); 8382 if (CLI.RetZExt) 8383 Attrs.push_back(Attribute::ZExt); 8384 if (CLI.IsInReg) 8385 Attrs.push_back(Attribute::InReg); 8386 8387 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8388 Attrs); 8389 } 8390 8391 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8392 /// implementation, which just calls LowerCall. 8393 /// FIXME: When all targets are 8394 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8395 std::pair<SDValue, SDValue> 8396 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8397 // Handle the incoming return values from the call. 8398 CLI.Ins.clear(); 8399 Type *OrigRetTy = CLI.RetTy; 8400 SmallVector<EVT, 4> RetTys; 8401 SmallVector<uint64_t, 4> Offsets; 8402 auto &DL = CLI.DAG.getDataLayout(); 8403 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8404 8405 if (CLI.IsPostTypeLegalization) { 8406 // If we are lowering a libcall after legalization, split the return type. 8407 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8408 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8409 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8410 EVT RetVT = OldRetTys[i]; 8411 uint64_t Offset = OldOffsets[i]; 8412 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8413 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8414 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8415 RetTys.append(NumRegs, RegisterVT); 8416 for (unsigned j = 0; j != NumRegs; ++j) 8417 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8418 } 8419 } 8420 8421 SmallVector<ISD::OutputArg, 4> Outs; 8422 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8423 8424 bool CanLowerReturn = 8425 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8426 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8427 8428 SDValue DemoteStackSlot; 8429 int DemoteStackIdx = -100; 8430 if (!CanLowerReturn) { 8431 // FIXME: equivalent assert? 8432 // assert(!CS.hasInAllocaArgument() && 8433 // "sret demotion is incompatible with inalloca"); 8434 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8435 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8436 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8437 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8438 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8439 DL.getAllocaAddrSpace()); 8440 8441 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8442 ArgListEntry Entry; 8443 Entry.Node = DemoteStackSlot; 8444 Entry.Ty = StackSlotPtrType; 8445 Entry.IsSExt = false; 8446 Entry.IsZExt = false; 8447 Entry.IsInReg = false; 8448 Entry.IsSRet = true; 8449 Entry.IsNest = false; 8450 Entry.IsByVal = false; 8451 Entry.IsReturned = false; 8452 Entry.IsSwiftSelf = false; 8453 Entry.IsSwiftError = false; 8454 Entry.Alignment = Align; 8455 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8456 CLI.NumFixedArgs += 1; 8457 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8458 8459 // sret demotion isn't compatible with tail-calls, since the sret argument 8460 // points into the callers stack frame. 8461 CLI.IsTailCall = false; 8462 } else { 8463 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8464 EVT VT = RetTys[I]; 8465 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8466 CLI.CallConv, VT); 8467 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8468 CLI.CallConv, VT); 8469 for (unsigned i = 0; i != NumRegs; ++i) { 8470 ISD::InputArg MyFlags; 8471 MyFlags.VT = RegisterVT; 8472 MyFlags.ArgVT = VT; 8473 MyFlags.Used = CLI.IsReturnValueUsed; 8474 if (CLI.RetSExt) 8475 MyFlags.Flags.setSExt(); 8476 if (CLI.RetZExt) 8477 MyFlags.Flags.setZExt(); 8478 if (CLI.IsInReg) 8479 MyFlags.Flags.setInReg(); 8480 CLI.Ins.push_back(MyFlags); 8481 } 8482 } 8483 } 8484 8485 // We push in swifterror return as the last element of CLI.Ins. 8486 ArgListTy &Args = CLI.getArgs(); 8487 if (supportSwiftError()) { 8488 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8489 if (Args[i].IsSwiftError) { 8490 ISD::InputArg MyFlags; 8491 MyFlags.VT = getPointerTy(DL); 8492 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8493 MyFlags.Flags.setSwiftError(); 8494 CLI.Ins.push_back(MyFlags); 8495 } 8496 } 8497 } 8498 8499 // Handle all of the outgoing arguments. 8500 CLI.Outs.clear(); 8501 CLI.OutVals.clear(); 8502 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8503 SmallVector<EVT, 4> ValueVTs; 8504 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8505 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8506 Type *FinalType = Args[i].Ty; 8507 if (Args[i].IsByVal) 8508 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8509 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8510 FinalType, CLI.CallConv, CLI.IsVarArg); 8511 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8512 ++Value) { 8513 EVT VT = ValueVTs[Value]; 8514 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8515 SDValue Op = SDValue(Args[i].Node.getNode(), 8516 Args[i].Node.getResNo() + Value); 8517 ISD::ArgFlagsTy Flags; 8518 8519 // Certain targets (such as MIPS), may have a different ABI alignment 8520 // for a type depending on the context. Give the target a chance to 8521 // specify the alignment it wants. 8522 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8523 8524 if (Args[i].IsZExt) 8525 Flags.setZExt(); 8526 if (Args[i].IsSExt) 8527 Flags.setSExt(); 8528 if (Args[i].IsInReg) { 8529 // If we are using vectorcall calling convention, a structure that is 8530 // passed InReg - is surely an HVA 8531 if (CLI.CallConv == CallingConv::X86_VectorCall && 8532 isa<StructType>(FinalType)) { 8533 // The first value of a structure is marked 8534 if (0 == Value) 8535 Flags.setHvaStart(); 8536 Flags.setHva(); 8537 } 8538 // Set InReg Flag 8539 Flags.setInReg(); 8540 } 8541 if (Args[i].IsSRet) 8542 Flags.setSRet(); 8543 if (Args[i].IsSwiftSelf) 8544 Flags.setSwiftSelf(); 8545 if (Args[i].IsSwiftError) 8546 Flags.setSwiftError(); 8547 if (Args[i].IsByVal) 8548 Flags.setByVal(); 8549 if (Args[i].IsInAlloca) { 8550 Flags.setInAlloca(); 8551 // Set the byval flag for CCAssignFn callbacks that don't know about 8552 // inalloca. This way we can know how many bytes we should've allocated 8553 // and how many bytes a callee cleanup function will pop. If we port 8554 // inalloca to more targets, we'll have to add custom inalloca handling 8555 // in the various CC lowering callbacks. 8556 Flags.setByVal(); 8557 } 8558 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8559 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8560 Type *ElementTy = Ty->getElementType(); 8561 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8562 // For ByVal, alignment should come from FE. BE will guess if this 8563 // info is not there but there are cases it cannot get right. 8564 unsigned FrameAlign; 8565 if (Args[i].Alignment) 8566 FrameAlign = Args[i].Alignment; 8567 else 8568 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8569 Flags.setByValAlign(FrameAlign); 8570 } 8571 if (Args[i].IsNest) 8572 Flags.setNest(); 8573 if (NeedsRegBlock) 8574 Flags.setInConsecutiveRegs(); 8575 Flags.setOrigAlign(OriginalAlignment); 8576 8577 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8578 CLI.CallConv, VT); 8579 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8580 CLI.CallConv, VT); 8581 SmallVector<SDValue, 4> Parts(NumParts); 8582 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8583 8584 if (Args[i].IsSExt) 8585 ExtendKind = ISD::SIGN_EXTEND; 8586 else if (Args[i].IsZExt) 8587 ExtendKind = ISD::ZERO_EXTEND; 8588 8589 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8590 // for now. 8591 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8592 CanLowerReturn) { 8593 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8594 "unexpected use of 'returned'"); 8595 // Before passing 'returned' to the target lowering code, ensure that 8596 // either the register MVT and the actual EVT are the same size or that 8597 // the return value and argument are extended in the same way; in these 8598 // cases it's safe to pass the argument register value unchanged as the 8599 // return register value (although it's at the target's option whether 8600 // to do so) 8601 // TODO: allow code generation to take advantage of partially preserved 8602 // registers rather than clobbering the entire register when the 8603 // parameter extension method is not compatible with the return 8604 // extension method 8605 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8606 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8607 CLI.RetZExt == Args[i].IsZExt)) 8608 Flags.setReturned(); 8609 } 8610 8611 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8612 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 8613 8614 for (unsigned j = 0; j != NumParts; ++j) { 8615 // if it isn't first piece, alignment must be 1 8616 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8617 i < CLI.NumFixedArgs, 8618 i, j*Parts[j].getValueType().getStoreSize()); 8619 if (NumParts > 1 && j == 0) 8620 MyFlags.Flags.setSplit(); 8621 else if (j != 0) { 8622 MyFlags.Flags.setOrigAlign(1); 8623 if (j == NumParts - 1) 8624 MyFlags.Flags.setSplitEnd(); 8625 } 8626 8627 CLI.Outs.push_back(MyFlags); 8628 CLI.OutVals.push_back(Parts[j]); 8629 } 8630 8631 if (NeedsRegBlock && Value == NumValues - 1) 8632 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8633 } 8634 } 8635 8636 SmallVector<SDValue, 4> InVals; 8637 CLI.Chain = LowerCall(CLI, InVals); 8638 8639 // Update CLI.InVals to use outside of this function. 8640 CLI.InVals = InVals; 8641 8642 // Verify that the target's LowerCall behaved as expected. 8643 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8644 "LowerCall didn't return a valid chain!"); 8645 assert((!CLI.IsTailCall || InVals.empty()) && 8646 "LowerCall emitted a return value for a tail call!"); 8647 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8648 "LowerCall didn't emit the correct number of values!"); 8649 8650 // For a tail call, the return value is merely live-out and there aren't 8651 // any nodes in the DAG representing it. Return a special value to 8652 // indicate that a tail call has been emitted and no more Instructions 8653 // should be processed in the current block. 8654 if (CLI.IsTailCall) { 8655 CLI.DAG.setRoot(CLI.Chain); 8656 return std::make_pair(SDValue(), SDValue()); 8657 } 8658 8659 #ifndef NDEBUG 8660 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8661 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8662 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8663 "LowerCall emitted a value with the wrong type!"); 8664 } 8665 #endif 8666 8667 SmallVector<SDValue, 4> ReturnValues; 8668 if (!CanLowerReturn) { 8669 // The instruction result is the result of loading from the 8670 // hidden sret parameter. 8671 SmallVector<EVT, 1> PVTs; 8672 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8673 8674 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8675 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8676 EVT PtrVT = PVTs[0]; 8677 8678 unsigned NumValues = RetTys.size(); 8679 ReturnValues.resize(NumValues); 8680 SmallVector<SDValue, 4> Chains(NumValues); 8681 8682 // An aggregate return value cannot wrap around the address space, so 8683 // offsets to its parts don't wrap either. 8684 SDNodeFlags Flags; 8685 Flags.setNoUnsignedWrap(true); 8686 8687 for (unsigned i = 0; i < NumValues; ++i) { 8688 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8689 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8690 PtrVT), Flags); 8691 SDValue L = CLI.DAG.getLoad( 8692 RetTys[i], CLI.DL, CLI.Chain, Add, 8693 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8694 DemoteStackIdx, Offsets[i]), 8695 /* Alignment = */ 1); 8696 ReturnValues[i] = L; 8697 Chains[i] = L.getValue(1); 8698 } 8699 8700 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8701 } else { 8702 // Collect the legal value parts into potentially illegal values 8703 // that correspond to the original function's return values. 8704 Optional<ISD::NodeType> AssertOp; 8705 if (CLI.RetSExt) 8706 AssertOp = ISD::AssertSext; 8707 else if (CLI.RetZExt) 8708 AssertOp = ISD::AssertZext; 8709 unsigned CurReg = 0; 8710 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8711 EVT VT = RetTys[I]; 8712 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8713 CLI.CallConv, VT); 8714 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8715 CLI.CallConv, VT); 8716 8717 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8718 NumRegs, RegisterVT, VT, nullptr, 8719 CLI.CallConv, AssertOp)); 8720 CurReg += NumRegs; 8721 } 8722 8723 // For a function returning void, there is no return value. We can't create 8724 // such a node, so we just return a null return value in that case. In 8725 // that case, nothing will actually look at the value. 8726 if (ReturnValues.empty()) 8727 return std::make_pair(SDValue(), CLI.Chain); 8728 } 8729 8730 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8731 CLI.DAG.getVTList(RetTys), ReturnValues); 8732 return std::make_pair(Res, CLI.Chain); 8733 } 8734 8735 void TargetLowering::LowerOperationWrapper(SDNode *N, 8736 SmallVectorImpl<SDValue> &Results, 8737 SelectionDAG &DAG) const { 8738 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8739 Results.push_back(Res); 8740 } 8741 8742 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8743 llvm_unreachable("LowerOperation not implemented for this target!"); 8744 } 8745 8746 void 8747 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8748 SDValue Op = getNonRegisterValue(V); 8749 assert((Op.getOpcode() != ISD::CopyFromReg || 8750 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8751 "Copy from a reg to the same reg!"); 8752 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8753 8754 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8755 // If this is an InlineAsm we have to match the registers required, not the 8756 // notional registers required by the type. 8757 8758 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 8759 None); // This is not an ABI copy. 8760 SDValue Chain = DAG.getEntryNode(); 8761 8762 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8763 FuncInfo.PreferredExtendType.end()) 8764 ? ISD::ANY_EXTEND 8765 : FuncInfo.PreferredExtendType[V]; 8766 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8767 PendingExports.push_back(Chain); 8768 } 8769 8770 #include "llvm/CodeGen/SelectionDAGISel.h" 8771 8772 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8773 /// entry block, return true. This includes arguments used by switches, since 8774 /// the switch may expand into multiple basic blocks. 8775 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8776 // With FastISel active, we may be splitting blocks, so force creation 8777 // of virtual registers for all non-dead arguments. 8778 if (FastISel) 8779 return A->use_empty(); 8780 8781 const BasicBlock &Entry = A->getParent()->front(); 8782 for (const User *U : A->users()) 8783 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8784 return false; // Use not in entry block. 8785 8786 return true; 8787 } 8788 8789 using ArgCopyElisionMapTy = 8790 DenseMap<const Argument *, 8791 std::pair<const AllocaInst *, const StoreInst *>>; 8792 8793 /// Scan the entry block of the function in FuncInfo for arguments that look 8794 /// like copies into a local alloca. Record any copied arguments in 8795 /// ArgCopyElisionCandidates. 8796 static void 8797 findArgumentCopyElisionCandidates(const DataLayout &DL, 8798 FunctionLoweringInfo *FuncInfo, 8799 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8800 // Record the state of every static alloca used in the entry block. Argument 8801 // allocas are all used in the entry block, so we need approximately as many 8802 // entries as we have arguments. 8803 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8804 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8805 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8806 StaticAllocas.reserve(NumArgs * 2); 8807 8808 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8809 if (!V) 8810 return nullptr; 8811 V = V->stripPointerCasts(); 8812 const auto *AI = dyn_cast<AllocaInst>(V); 8813 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8814 return nullptr; 8815 auto Iter = StaticAllocas.insert({AI, Unknown}); 8816 return &Iter.first->second; 8817 }; 8818 8819 // Look for stores of arguments to static allocas. Look through bitcasts and 8820 // GEPs to handle type coercions, as long as the alloca is fully initialized 8821 // by the store. Any non-store use of an alloca escapes it and any subsequent 8822 // unanalyzed store might write it. 8823 // FIXME: Handle structs initialized with multiple stores. 8824 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8825 // Look for stores, and handle non-store uses conservatively. 8826 const auto *SI = dyn_cast<StoreInst>(&I); 8827 if (!SI) { 8828 // We will look through cast uses, so ignore them completely. 8829 if (I.isCast()) 8830 continue; 8831 // Ignore debug info intrinsics, they don't escape or store to allocas. 8832 if (isa<DbgInfoIntrinsic>(I)) 8833 continue; 8834 // This is an unknown instruction. Assume it escapes or writes to all 8835 // static alloca operands. 8836 for (const Use &U : I.operands()) { 8837 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8838 *Info = StaticAllocaInfo::Clobbered; 8839 } 8840 continue; 8841 } 8842 8843 // If the stored value is a static alloca, mark it as escaped. 8844 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8845 *Info = StaticAllocaInfo::Clobbered; 8846 8847 // Check if the destination is a static alloca. 8848 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8849 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8850 if (!Info) 8851 continue; 8852 const AllocaInst *AI = cast<AllocaInst>(Dst); 8853 8854 // Skip allocas that have been initialized or clobbered. 8855 if (*Info != StaticAllocaInfo::Unknown) 8856 continue; 8857 8858 // Check if the stored value is an argument, and that this store fully 8859 // initializes the alloca. Don't elide copies from the same argument twice. 8860 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8861 const auto *Arg = dyn_cast<Argument>(Val); 8862 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8863 Arg->getType()->isEmptyTy() || 8864 DL.getTypeStoreSize(Arg->getType()) != 8865 DL.getTypeAllocSize(AI->getAllocatedType()) || 8866 ArgCopyElisionCandidates.count(Arg)) { 8867 *Info = StaticAllocaInfo::Clobbered; 8868 continue; 8869 } 8870 8871 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 8872 << '\n'); 8873 8874 // Mark this alloca and store for argument copy elision. 8875 *Info = StaticAllocaInfo::Elidable; 8876 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8877 8878 // Stop scanning if we've seen all arguments. This will happen early in -O0 8879 // builds, which is useful, because -O0 builds have large entry blocks and 8880 // many allocas. 8881 if (ArgCopyElisionCandidates.size() == NumArgs) 8882 break; 8883 } 8884 } 8885 8886 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8887 /// ArgVal is a load from a suitable fixed stack object. 8888 static void tryToElideArgumentCopy( 8889 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8890 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8891 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8892 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8893 SDValue ArgVal, bool &ArgHasUses) { 8894 // Check if this is a load from a fixed stack object. 8895 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8896 if (!LNode) 8897 return; 8898 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 8899 if (!FINode) 8900 return; 8901 8902 // Check that the fixed stack object is the right size and alignment. 8903 // Look at the alignment that the user wrote on the alloca instead of looking 8904 // at the stack object. 8905 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 8906 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 8907 const AllocaInst *AI = ArgCopyIter->second.first; 8908 int FixedIndex = FINode->getIndex(); 8909 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 8910 int OldIndex = AllocaIndex; 8911 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 8912 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 8913 LLVM_DEBUG( 8914 dbgs() << " argument copy elision failed due to bad fixed stack " 8915 "object size\n"); 8916 return; 8917 } 8918 unsigned RequiredAlignment = AI->getAlignment(); 8919 if (!RequiredAlignment) { 8920 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 8921 AI->getAllocatedType()); 8922 } 8923 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 8924 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 8925 "greater than stack argument alignment (" 8926 << RequiredAlignment << " vs " 8927 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 8928 return; 8929 } 8930 8931 // Perform the elision. Delete the old stack object and replace its only use 8932 // in the variable info map. Mark the stack object as mutable. 8933 LLVM_DEBUG({ 8934 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 8935 << " Replacing frame index " << OldIndex << " with " << FixedIndex 8936 << '\n'; 8937 }); 8938 MFI.RemoveStackObject(OldIndex); 8939 MFI.setIsImmutableObjectIndex(FixedIndex, false); 8940 AllocaIndex = FixedIndex; 8941 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 8942 Chains.push_back(ArgVal.getValue(1)); 8943 8944 // Avoid emitting code for the store implementing the copy. 8945 const StoreInst *SI = ArgCopyIter->second.second; 8946 ElidedArgCopyInstrs.insert(SI); 8947 8948 // Check for uses of the argument again so that we can avoid exporting ArgVal 8949 // if it is't used by anything other than the store. 8950 for (const Value *U : Arg.users()) { 8951 if (U != SI) { 8952 ArgHasUses = true; 8953 break; 8954 } 8955 } 8956 } 8957 8958 void SelectionDAGISel::LowerArguments(const Function &F) { 8959 SelectionDAG &DAG = SDB->DAG; 8960 SDLoc dl = SDB->getCurSDLoc(); 8961 const DataLayout &DL = DAG.getDataLayout(); 8962 SmallVector<ISD::InputArg, 16> Ins; 8963 8964 if (!FuncInfo->CanLowerReturn) { 8965 // Put in an sret pointer parameter before all the other parameters. 8966 SmallVector<EVT, 1> ValueVTs; 8967 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8968 F.getReturnType()->getPointerTo( 8969 DAG.getDataLayout().getAllocaAddrSpace()), 8970 ValueVTs); 8971 8972 // NOTE: Assuming that a pointer will never break down to more than one VT 8973 // or one register. 8974 ISD::ArgFlagsTy Flags; 8975 Flags.setSRet(); 8976 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 8977 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 8978 ISD::InputArg::NoArgIndex, 0); 8979 Ins.push_back(RetArg); 8980 } 8981 8982 // Look for stores of arguments to static allocas. Mark such arguments with a 8983 // flag to ask the target to give us the memory location of that argument if 8984 // available. 8985 ArgCopyElisionMapTy ArgCopyElisionCandidates; 8986 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 8987 8988 // Set up the incoming argument description vector. 8989 for (const Argument &Arg : F.args()) { 8990 unsigned ArgNo = Arg.getArgNo(); 8991 SmallVector<EVT, 4> ValueVTs; 8992 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 8993 bool isArgValueUsed = !Arg.use_empty(); 8994 unsigned PartBase = 0; 8995 Type *FinalType = Arg.getType(); 8996 if (Arg.hasAttribute(Attribute::ByVal)) 8997 FinalType = cast<PointerType>(FinalType)->getElementType(); 8998 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 8999 FinalType, F.getCallingConv(), F.isVarArg()); 9000 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9001 Value != NumValues; ++Value) { 9002 EVT VT = ValueVTs[Value]; 9003 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9004 ISD::ArgFlagsTy Flags; 9005 9006 // Certain targets (such as MIPS), may have a different ABI alignment 9007 // for a type depending on the context. Give the target a chance to 9008 // specify the alignment it wants. 9009 unsigned OriginalAlignment = 9010 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 9011 9012 if (Arg.hasAttribute(Attribute::ZExt)) 9013 Flags.setZExt(); 9014 if (Arg.hasAttribute(Attribute::SExt)) 9015 Flags.setSExt(); 9016 if (Arg.hasAttribute(Attribute::InReg)) { 9017 // If we are using vectorcall calling convention, a structure that is 9018 // passed InReg - is surely an HVA 9019 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9020 isa<StructType>(Arg.getType())) { 9021 // The first value of a structure is marked 9022 if (0 == Value) 9023 Flags.setHvaStart(); 9024 Flags.setHva(); 9025 } 9026 // Set InReg Flag 9027 Flags.setInReg(); 9028 } 9029 if (Arg.hasAttribute(Attribute::StructRet)) 9030 Flags.setSRet(); 9031 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9032 Flags.setSwiftSelf(); 9033 if (Arg.hasAttribute(Attribute::SwiftError)) 9034 Flags.setSwiftError(); 9035 if (Arg.hasAttribute(Attribute::ByVal)) 9036 Flags.setByVal(); 9037 if (Arg.hasAttribute(Attribute::InAlloca)) { 9038 Flags.setInAlloca(); 9039 // Set the byval flag for CCAssignFn callbacks that don't know about 9040 // inalloca. This way we can know how many bytes we should've allocated 9041 // and how many bytes a callee cleanup function will pop. If we port 9042 // inalloca to more targets, we'll have to add custom inalloca handling 9043 // in the various CC lowering callbacks. 9044 Flags.setByVal(); 9045 } 9046 if (F.getCallingConv() == CallingConv::X86_INTR) { 9047 // IA Interrupt passes frame (1st parameter) by value in the stack. 9048 if (ArgNo == 0) 9049 Flags.setByVal(); 9050 } 9051 if (Flags.isByVal() || Flags.isInAlloca()) { 9052 PointerType *Ty = cast<PointerType>(Arg.getType()); 9053 Type *ElementTy = Ty->getElementType(); 9054 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9055 // For ByVal, alignment should be passed from FE. BE will guess if 9056 // this info is not there but there are cases it cannot get right. 9057 unsigned FrameAlign; 9058 if (Arg.getParamAlignment()) 9059 FrameAlign = Arg.getParamAlignment(); 9060 else 9061 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9062 Flags.setByValAlign(FrameAlign); 9063 } 9064 if (Arg.hasAttribute(Attribute::Nest)) 9065 Flags.setNest(); 9066 if (NeedsRegBlock) 9067 Flags.setInConsecutiveRegs(); 9068 Flags.setOrigAlign(OriginalAlignment); 9069 if (ArgCopyElisionCandidates.count(&Arg)) 9070 Flags.setCopyElisionCandidate(); 9071 9072 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9073 *CurDAG->getContext(), F.getCallingConv(), VT); 9074 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9075 *CurDAG->getContext(), F.getCallingConv(), VT); 9076 for (unsigned i = 0; i != NumRegs; ++i) { 9077 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9078 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9079 if (NumRegs > 1 && i == 0) 9080 MyFlags.Flags.setSplit(); 9081 // if it isn't first piece, alignment must be 1 9082 else if (i > 0) { 9083 MyFlags.Flags.setOrigAlign(1); 9084 if (i == NumRegs - 1) 9085 MyFlags.Flags.setSplitEnd(); 9086 } 9087 Ins.push_back(MyFlags); 9088 } 9089 if (NeedsRegBlock && Value == NumValues - 1) 9090 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9091 PartBase += VT.getStoreSize(); 9092 } 9093 } 9094 9095 // Call the target to set up the argument values. 9096 SmallVector<SDValue, 8> InVals; 9097 SDValue NewRoot = TLI->LowerFormalArguments( 9098 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9099 9100 // Verify that the target's LowerFormalArguments behaved as expected. 9101 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9102 "LowerFormalArguments didn't return a valid chain!"); 9103 assert(InVals.size() == Ins.size() && 9104 "LowerFormalArguments didn't emit the correct number of values!"); 9105 LLVM_DEBUG({ 9106 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9107 assert(InVals[i].getNode() && 9108 "LowerFormalArguments emitted a null value!"); 9109 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9110 "LowerFormalArguments emitted a value with the wrong type!"); 9111 } 9112 }); 9113 9114 // Update the DAG with the new chain value resulting from argument lowering. 9115 DAG.setRoot(NewRoot); 9116 9117 // Set up the argument values. 9118 unsigned i = 0; 9119 if (!FuncInfo->CanLowerReturn) { 9120 // Create a virtual register for the sret pointer, and put in a copy 9121 // from the sret argument into it. 9122 SmallVector<EVT, 1> ValueVTs; 9123 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9124 F.getReturnType()->getPointerTo( 9125 DAG.getDataLayout().getAllocaAddrSpace()), 9126 ValueVTs); 9127 MVT VT = ValueVTs[0].getSimpleVT(); 9128 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9129 Optional<ISD::NodeType> AssertOp = None; 9130 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9131 nullptr, F.getCallingConv(), AssertOp); 9132 9133 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9134 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9135 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9136 FuncInfo->DemoteRegister = SRetReg; 9137 NewRoot = 9138 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9139 DAG.setRoot(NewRoot); 9140 9141 // i indexes lowered arguments. Bump it past the hidden sret argument. 9142 ++i; 9143 } 9144 9145 SmallVector<SDValue, 4> Chains; 9146 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9147 for (const Argument &Arg : F.args()) { 9148 SmallVector<SDValue, 4> ArgValues; 9149 SmallVector<EVT, 4> ValueVTs; 9150 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9151 unsigned NumValues = ValueVTs.size(); 9152 if (NumValues == 0) 9153 continue; 9154 9155 bool ArgHasUses = !Arg.use_empty(); 9156 9157 // Elide the copying store if the target loaded this argument from a 9158 // suitable fixed stack object. 9159 if (Ins[i].Flags.isCopyElisionCandidate()) { 9160 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9161 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9162 InVals[i], ArgHasUses); 9163 } 9164 9165 // If this argument is unused then remember its value. It is used to generate 9166 // debugging information. 9167 bool isSwiftErrorArg = 9168 TLI->supportSwiftError() && 9169 Arg.hasAttribute(Attribute::SwiftError); 9170 if (!ArgHasUses && !isSwiftErrorArg) { 9171 SDB->setUnusedArgValue(&Arg, InVals[i]); 9172 9173 // Also remember any frame index for use in FastISel. 9174 if (FrameIndexSDNode *FI = 9175 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9176 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9177 } 9178 9179 for (unsigned Val = 0; Val != NumValues; ++Val) { 9180 EVT VT = ValueVTs[Val]; 9181 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9182 F.getCallingConv(), VT); 9183 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9184 *CurDAG->getContext(), F.getCallingConv(), VT); 9185 9186 // Even an apparant 'unused' swifterror argument needs to be returned. So 9187 // we do generate a copy for it that can be used on return from the 9188 // function. 9189 if (ArgHasUses || isSwiftErrorArg) { 9190 Optional<ISD::NodeType> AssertOp; 9191 if (Arg.hasAttribute(Attribute::SExt)) 9192 AssertOp = ISD::AssertSext; 9193 else if (Arg.hasAttribute(Attribute::ZExt)) 9194 AssertOp = ISD::AssertZext; 9195 9196 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9197 PartVT, VT, nullptr, 9198 F.getCallingConv(), AssertOp)); 9199 } 9200 9201 i += NumParts; 9202 } 9203 9204 // We don't need to do anything else for unused arguments. 9205 if (ArgValues.empty()) 9206 continue; 9207 9208 // Note down frame index. 9209 if (FrameIndexSDNode *FI = 9210 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9211 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9212 9213 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9214 SDB->getCurSDLoc()); 9215 9216 SDB->setValue(&Arg, Res); 9217 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9218 // We want to associate the argument with the frame index, among 9219 // involved operands, that correspond to the lowest address. The 9220 // getCopyFromParts function, called earlier, is swapping the order of 9221 // the operands to BUILD_PAIR depending on endianness. The result of 9222 // that swapping is that the least significant bits of the argument will 9223 // be in the first operand of the BUILD_PAIR node, and the most 9224 // significant bits will be in the second operand. 9225 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9226 if (LoadSDNode *LNode = 9227 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9228 if (FrameIndexSDNode *FI = 9229 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9230 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9231 } 9232 9233 // Update the SwiftErrorVRegDefMap. 9234 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9235 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9236 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9237 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9238 FuncInfo->SwiftErrorArg, Reg); 9239 } 9240 9241 // If this argument is live outside of the entry block, insert a copy from 9242 // wherever we got it to the vreg that other BB's will reference it as. 9243 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9244 // If we can, though, try to skip creating an unnecessary vreg. 9245 // FIXME: This isn't very clean... it would be nice to make this more 9246 // general. It's also subtly incompatible with the hacks FastISel 9247 // uses with vregs. 9248 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9249 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9250 FuncInfo->ValueMap[&Arg] = Reg; 9251 continue; 9252 } 9253 } 9254 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9255 FuncInfo->InitializeRegForValue(&Arg); 9256 SDB->CopyToExportRegsIfNeeded(&Arg); 9257 } 9258 } 9259 9260 if (!Chains.empty()) { 9261 Chains.push_back(NewRoot); 9262 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9263 } 9264 9265 DAG.setRoot(NewRoot); 9266 9267 assert(i == InVals.size() && "Argument register count mismatch!"); 9268 9269 // If any argument copy elisions occurred and we have debug info, update the 9270 // stale frame indices used in the dbg.declare variable info table. 9271 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9272 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9273 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9274 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9275 if (I != ArgCopyElisionFrameIndexMap.end()) 9276 VI.Slot = I->second; 9277 } 9278 } 9279 9280 // Finally, if the target has anything special to do, allow it to do so. 9281 EmitFunctionEntryCode(); 9282 } 9283 9284 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9285 /// ensure constants are generated when needed. Remember the virtual registers 9286 /// that need to be added to the Machine PHI nodes as input. We cannot just 9287 /// directly add them, because expansion might result in multiple MBB's for one 9288 /// BB. As such, the start of the BB might correspond to a different MBB than 9289 /// the end. 9290 void 9291 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9292 const Instruction *TI = LLVMBB->getTerminator(); 9293 9294 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9295 9296 // Check PHI nodes in successors that expect a value to be available from this 9297 // block. 9298 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9299 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9300 if (!isa<PHINode>(SuccBB->begin())) continue; 9301 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9302 9303 // If this terminator has multiple identical successors (common for 9304 // switches), only handle each succ once. 9305 if (!SuccsHandled.insert(SuccMBB).second) 9306 continue; 9307 9308 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9309 9310 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9311 // nodes and Machine PHI nodes, but the incoming operands have not been 9312 // emitted yet. 9313 for (const PHINode &PN : SuccBB->phis()) { 9314 // Ignore dead phi's. 9315 if (PN.use_empty()) 9316 continue; 9317 9318 // Skip empty types 9319 if (PN.getType()->isEmptyTy()) 9320 continue; 9321 9322 unsigned Reg; 9323 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9324 9325 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9326 unsigned &RegOut = ConstantsOut[C]; 9327 if (RegOut == 0) { 9328 RegOut = FuncInfo.CreateRegs(C->getType()); 9329 CopyValueToVirtualRegister(C, RegOut); 9330 } 9331 Reg = RegOut; 9332 } else { 9333 DenseMap<const Value *, unsigned>::iterator I = 9334 FuncInfo.ValueMap.find(PHIOp); 9335 if (I != FuncInfo.ValueMap.end()) 9336 Reg = I->second; 9337 else { 9338 assert(isa<AllocaInst>(PHIOp) && 9339 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9340 "Didn't codegen value into a register!??"); 9341 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9342 CopyValueToVirtualRegister(PHIOp, Reg); 9343 } 9344 } 9345 9346 // Remember that this register needs to added to the machine PHI node as 9347 // the input for this MBB. 9348 SmallVector<EVT, 4> ValueVTs; 9349 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9350 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9351 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9352 EVT VT = ValueVTs[vti]; 9353 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9354 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9355 FuncInfo.PHINodesToUpdate.push_back( 9356 std::make_pair(&*MBBI++, Reg + i)); 9357 Reg += NumRegisters; 9358 } 9359 } 9360 } 9361 9362 ConstantsOut.clear(); 9363 } 9364 9365 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9366 /// is 0. 9367 MachineBasicBlock * 9368 SelectionDAGBuilder::StackProtectorDescriptor:: 9369 AddSuccessorMBB(const BasicBlock *BB, 9370 MachineBasicBlock *ParentMBB, 9371 bool IsLikely, 9372 MachineBasicBlock *SuccMBB) { 9373 // If SuccBB has not been created yet, create it. 9374 if (!SuccMBB) { 9375 MachineFunction *MF = ParentMBB->getParent(); 9376 MachineFunction::iterator BBI(ParentMBB); 9377 SuccMBB = MF->CreateMachineBasicBlock(BB); 9378 MF->insert(++BBI, SuccMBB); 9379 } 9380 // Add it as a successor of ParentMBB. 9381 ParentMBB->addSuccessor( 9382 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9383 return SuccMBB; 9384 } 9385 9386 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9387 MachineFunction::iterator I(MBB); 9388 if (++I == FuncInfo.MF->end()) 9389 return nullptr; 9390 return &*I; 9391 } 9392 9393 /// During lowering new call nodes can be created (such as memset, etc.). 9394 /// Those will become new roots of the current DAG, but complications arise 9395 /// when they are tail calls. In such cases, the call lowering will update 9396 /// the root, but the builder still needs to know that a tail call has been 9397 /// lowered in order to avoid generating an additional return. 9398 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9399 // If the node is null, we do have a tail call. 9400 if (MaybeTC.getNode() != nullptr) 9401 DAG.setRoot(MaybeTC); 9402 else 9403 HasTailCall = true; 9404 } 9405 9406 uint64_t 9407 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9408 unsigned First, unsigned Last) const { 9409 assert(Last >= First); 9410 const APInt &LowCase = Clusters[First].Low->getValue(); 9411 const APInt &HighCase = Clusters[Last].High->getValue(); 9412 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9413 9414 // FIXME: A range of consecutive cases has 100% density, but only requires one 9415 // comparison to lower. We should discriminate against such consecutive ranges 9416 // in jump tables. 9417 9418 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9419 } 9420 9421 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9422 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9423 unsigned Last) const { 9424 assert(Last >= First); 9425 assert(TotalCases[Last] >= TotalCases[First]); 9426 uint64_t NumCases = 9427 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9428 return NumCases; 9429 } 9430 9431 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9432 unsigned First, unsigned Last, 9433 const SwitchInst *SI, 9434 MachineBasicBlock *DefaultMBB, 9435 CaseCluster &JTCluster) { 9436 assert(First <= Last); 9437 9438 auto Prob = BranchProbability::getZero(); 9439 unsigned NumCmps = 0; 9440 std::vector<MachineBasicBlock*> Table; 9441 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9442 9443 // Initialize probabilities in JTProbs. 9444 for (unsigned I = First; I <= Last; ++I) 9445 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9446 9447 for (unsigned I = First; I <= Last; ++I) { 9448 assert(Clusters[I].Kind == CC_Range); 9449 Prob += Clusters[I].Prob; 9450 const APInt &Low = Clusters[I].Low->getValue(); 9451 const APInt &High = Clusters[I].High->getValue(); 9452 NumCmps += (Low == High) ? 1 : 2; 9453 if (I != First) { 9454 // Fill the gap between this and the previous cluster. 9455 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9456 assert(PreviousHigh.slt(Low)); 9457 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9458 for (uint64_t J = 0; J < Gap; J++) 9459 Table.push_back(DefaultMBB); 9460 } 9461 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9462 for (uint64_t J = 0; J < ClusterSize; ++J) 9463 Table.push_back(Clusters[I].MBB); 9464 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9465 } 9466 9467 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9468 unsigned NumDests = JTProbs.size(); 9469 if (TLI.isSuitableForBitTests( 9470 NumDests, NumCmps, Clusters[First].Low->getValue(), 9471 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9472 // Clusters[First..Last] should be lowered as bit tests instead. 9473 return false; 9474 } 9475 9476 // Create the MBB that will load from and jump through the table. 9477 // Note: We create it here, but it's not inserted into the function yet. 9478 MachineFunction *CurMF = FuncInfo.MF; 9479 MachineBasicBlock *JumpTableMBB = 9480 CurMF->CreateMachineBasicBlock(SI->getParent()); 9481 9482 // Add successors. Note: use table order for determinism. 9483 SmallPtrSet<MachineBasicBlock *, 8> Done; 9484 for (MachineBasicBlock *Succ : Table) { 9485 if (Done.count(Succ)) 9486 continue; 9487 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9488 Done.insert(Succ); 9489 } 9490 JumpTableMBB->normalizeSuccProbs(); 9491 9492 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9493 ->createJumpTableIndex(Table); 9494 9495 // Set up the jump table info. 9496 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9497 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9498 Clusters[Last].High->getValue(), SI->getCondition(), 9499 nullptr, false); 9500 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9501 9502 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9503 JTCases.size() - 1, Prob); 9504 return true; 9505 } 9506 9507 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9508 const SwitchInst *SI, 9509 MachineBasicBlock *DefaultMBB) { 9510 #ifndef NDEBUG 9511 // Clusters must be non-empty, sorted, and only contain Range clusters. 9512 assert(!Clusters.empty()); 9513 for (CaseCluster &C : Clusters) 9514 assert(C.Kind == CC_Range); 9515 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9516 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9517 #endif 9518 9519 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9520 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9521 return; 9522 9523 const int64_t N = Clusters.size(); 9524 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9525 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9526 9527 if (N < 2 || N < MinJumpTableEntries) 9528 return; 9529 9530 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9531 SmallVector<unsigned, 8> TotalCases(N); 9532 for (unsigned i = 0; i < N; ++i) { 9533 const APInt &Hi = Clusters[i].High->getValue(); 9534 const APInt &Lo = Clusters[i].Low->getValue(); 9535 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9536 if (i != 0) 9537 TotalCases[i] += TotalCases[i - 1]; 9538 } 9539 9540 // Cheap case: the whole range may be suitable for jump table. 9541 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9542 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9543 assert(NumCases < UINT64_MAX / 100); 9544 assert(Range >= NumCases); 9545 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9546 CaseCluster JTCluster; 9547 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9548 Clusters[0] = JTCluster; 9549 Clusters.resize(1); 9550 return; 9551 } 9552 } 9553 9554 // The algorithm below is not suitable for -O0. 9555 if (TM.getOptLevel() == CodeGenOpt::None) 9556 return; 9557 9558 // Split Clusters into minimum number of dense partitions. The algorithm uses 9559 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9560 // for the Case Statement'" (1994), but builds the MinPartitions array in 9561 // reverse order to make it easier to reconstruct the partitions in ascending 9562 // order. In the choice between two optimal partitionings, it picks the one 9563 // which yields more jump tables. 9564 9565 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9566 SmallVector<unsigned, 8> MinPartitions(N); 9567 // LastElement[i] is the last element of the partition starting at i. 9568 SmallVector<unsigned, 8> LastElement(N); 9569 // PartitionsScore[i] is used to break ties when choosing between two 9570 // partitionings resulting in the same number of partitions. 9571 SmallVector<unsigned, 8> PartitionsScore(N); 9572 // For PartitionsScore, a small number of comparisons is considered as good as 9573 // a jump table and a single comparison is considered better than a jump 9574 // table. 9575 enum PartitionScores : unsigned { 9576 NoTable = 0, 9577 Table = 1, 9578 FewCases = 1, 9579 SingleCase = 2 9580 }; 9581 9582 // Base case: There is only one way to partition Clusters[N-1]. 9583 MinPartitions[N - 1] = 1; 9584 LastElement[N - 1] = N - 1; 9585 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9586 9587 // Note: loop indexes are signed to avoid underflow. 9588 for (int64_t i = N - 2; i >= 0; i--) { 9589 // Find optimal partitioning of Clusters[i..N-1]. 9590 // Baseline: Put Clusters[i] into a partition on its own. 9591 MinPartitions[i] = MinPartitions[i + 1] + 1; 9592 LastElement[i] = i; 9593 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9594 9595 // Search for a solution that results in fewer partitions. 9596 for (int64_t j = N - 1; j > i; j--) { 9597 // Try building a partition from Clusters[i..j]. 9598 uint64_t Range = getJumpTableRange(Clusters, i, j); 9599 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9600 assert(NumCases < UINT64_MAX / 100); 9601 assert(Range >= NumCases); 9602 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9603 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9604 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9605 int64_t NumEntries = j - i + 1; 9606 9607 if (NumEntries == 1) 9608 Score += PartitionScores::SingleCase; 9609 else if (NumEntries <= SmallNumberOfEntries) 9610 Score += PartitionScores::FewCases; 9611 else if (NumEntries >= MinJumpTableEntries) 9612 Score += PartitionScores::Table; 9613 9614 // If this leads to fewer partitions, or to the same number of 9615 // partitions with better score, it is a better partitioning. 9616 if (NumPartitions < MinPartitions[i] || 9617 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9618 MinPartitions[i] = NumPartitions; 9619 LastElement[i] = j; 9620 PartitionsScore[i] = Score; 9621 } 9622 } 9623 } 9624 } 9625 9626 // Iterate over the partitions, replacing some with jump tables in-place. 9627 unsigned DstIndex = 0; 9628 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9629 Last = LastElement[First]; 9630 assert(Last >= First); 9631 assert(DstIndex <= First); 9632 unsigned NumClusters = Last - First + 1; 9633 9634 CaseCluster JTCluster; 9635 if (NumClusters >= MinJumpTableEntries && 9636 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9637 Clusters[DstIndex++] = JTCluster; 9638 } else { 9639 for (unsigned I = First; I <= Last; ++I) 9640 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9641 } 9642 } 9643 Clusters.resize(DstIndex); 9644 } 9645 9646 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9647 unsigned First, unsigned Last, 9648 const SwitchInst *SI, 9649 CaseCluster &BTCluster) { 9650 assert(First <= Last); 9651 if (First == Last) 9652 return false; 9653 9654 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9655 unsigned NumCmps = 0; 9656 for (int64_t I = First; I <= Last; ++I) { 9657 assert(Clusters[I].Kind == CC_Range); 9658 Dests.set(Clusters[I].MBB->getNumber()); 9659 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9660 } 9661 unsigned NumDests = Dests.count(); 9662 9663 APInt Low = Clusters[First].Low->getValue(); 9664 APInt High = Clusters[Last].High->getValue(); 9665 assert(Low.slt(High)); 9666 9667 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9668 const DataLayout &DL = DAG.getDataLayout(); 9669 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9670 return false; 9671 9672 APInt LowBound; 9673 APInt CmpRange; 9674 9675 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9676 assert(TLI.rangeFitsInWord(Low, High, DL) && 9677 "Case range must fit in bit mask!"); 9678 9679 // Check if the clusters cover a contiguous range such that no value in the 9680 // range will jump to the default statement. 9681 bool ContiguousRange = true; 9682 for (int64_t I = First + 1; I <= Last; ++I) { 9683 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9684 ContiguousRange = false; 9685 break; 9686 } 9687 } 9688 9689 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9690 // Optimize the case where all the case values fit in a word without having 9691 // to subtract minValue. In this case, we can optimize away the subtraction. 9692 LowBound = APInt::getNullValue(Low.getBitWidth()); 9693 CmpRange = High; 9694 ContiguousRange = false; 9695 } else { 9696 LowBound = Low; 9697 CmpRange = High - Low; 9698 } 9699 9700 CaseBitsVector CBV; 9701 auto TotalProb = BranchProbability::getZero(); 9702 for (unsigned i = First; i <= Last; ++i) { 9703 // Find the CaseBits for this destination. 9704 unsigned j; 9705 for (j = 0; j < CBV.size(); ++j) 9706 if (CBV[j].BB == Clusters[i].MBB) 9707 break; 9708 if (j == CBV.size()) 9709 CBV.push_back( 9710 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9711 CaseBits *CB = &CBV[j]; 9712 9713 // Update Mask, Bits and ExtraProb. 9714 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9715 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9716 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9717 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9718 CB->Bits += Hi - Lo + 1; 9719 CB->ExtraProb += Clusters[i].Prob; 9720 TotalProb += Clusters[i].Prob; 9721 } 9722 9723 BitTestInfo BTI; 9724 llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) { 9725 // Sort by probability first, number of bits second, bit mask third. 9726 if (a.ExtraProb != b.ExtraProb) 9727 return a.ExtraProb > b.ExtraProb; 9728 if (a.Bits != b.Bits) 9729 return a.Bits > b.Bits; 9730 return a.Mask < b.Mask; 9731 }); 9732 9733 for (auto &CB : CBV) { 9734 MachineBasicBlock *BitTestBB = 9735 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9736 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9737 } 9738 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9739 SI->getCondition(), -1U, MVT::Other, false, 9740 ContiguousRange, nullptr, nullptr, std::move(BTI), 9741 TotalProb); 9742 9743 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9744 BitTestCases.size() - 1, TotalProb); 9745 return true; 9746 } 9747 9748 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9749 const SwitchInst *SI) { 9750 // Partition Clusters into as few subsets as possible, where each subset has a 9751 // range that fits in a machine word and has <= 3 unique destinations. 9752 9753 #ifndef NDEBUG 9754 // Clusters must be sorted and contain Range or JumpTable clusters. 9755 assert(!Clusters.empty()); 9756 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9757 for (const CaseCluster &C : Clusters) 9758 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9759 for (unsigned i = 1; i < Clusters.size(); ++i) 9760 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9761 #endif 9762 9763 // The algorithm below is not suitable for -O0. 9764 if (TM.getOptLevel() == CodeGenOpt::None) 9765 return; 9766 9767 // If target does not have legal shift left, do not emit bit tests at all. 9768 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9769 const DataLayout &DL = DAG.getDataLayout(); 9770 9771 EVT PTy = TLI.getPointerTy(DL); 9772 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9773 return; 9774 9775 int BitWidth = PTy.getSizeInBits(); 9776 const int64_t N = Clusters.size(); 9777 9778 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9779 SmallVector<unsigned, 8> MinPartitions(N); 9780 // LastElement[i] is the last element of the partition starting at i. 9781 SmallVector<unsigned, 8> LastElement(N); 9782 9783 // FIXME: This might not be the best algorithm for finding bit test clusters. 9784 9785 // Base case: There is only one way to partition Clusters[N-1]. 9786 MinPartitions[N - 1] = 1; 9787 LastElement[N - 1] = N - 1; 9788 9789 // Note: loop indexes are signed to avoid underflow. 9790 for (int64_t i = N - 2; i >= 0; --i) { 9791 // Find optimal partitioning of Clusters[i..N-1]. 9792 // Baseline: Put Clusters[i] into a partition on its own. 9793 MinPartitions[i] = MinPartitions[i + 1] + 1; 9794 LastElement[i] = i; 9795 9796 // Search for a solution that results in fewer partitions. 9797 // Note: the search is limited by BitWidth, reducing time complexity. 9798 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9799 // Try building a partition from Clusters[i..j]. 9800 9801 // Check the range. 9802 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9803 Clusters[j].High->getValue(), DL)) 9804 continue; 9805 9806 // Check nbr of destinations and cluster types. 9807 // FIXME: This works, but doesn't seem very efficient. 9808 bool RangesOnly = true; 9809 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9810 for (int64_t k = i; k <= j; k++) { 9811 if (Clusters[k].Kind != CC_Range) { 9812 RangesOnly = false; 9813 break; 9814 } 9815 Dests.set(Clusters[k].MBB->getNumber()); 9816 } 9817 if (!RangesOnly || Dests.count() > 3) 9818 break; 9819 9820 // Check if it's a better partition. 9821 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9822 if (NumPartitions < MinPartitions[i]) { 9823 // Found a better partition. 9824 MinPartitions[i] = NumPartitions; 9825 LastElement[i] = j; 9826 } 9827 } 9828 } 9829 9830 // Iterate over the partitions, replacing with bit-test clusters in-place. 9831 unsigned DstIndex = 0; 9832 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9833 Last = LastElement[First]; 9834 assert(First <= Last); 9835 assert(DstIndex <= First); 9836 9837 CaseCluster BitTestCluster; 9838 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9839 Clusters[DstIndex++] = BitTestCluster; 9840 } else { 9841 size_t NumClusters = Last - First + 1; 9842 std::memmove(&Clusters[DstIndex], &Clusters[First], 9843 sizeof(Clusters[0]) * NumClusters); 9844 DstIndex += NumClusters; 9845 } 9846 } 9847 Clusters.resize(DstIndex); 9848 } 9849 9850 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9851 MachineBasicBlock *SwitchMBB, 9852 MachineBasicBlock *DefaultMBB) { 9853 MachineFunction *CurMF = FuncInfo.MF; 9854 MachineBasicBlock *NextMBB = nullptr; 9855 MachineFunction::iterator BBI(W.MBB); 9856 if (++BBI != FuncInfo.MF->end()) 9857 NextMBB = &*BBI; 9858 9859 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9860 9861 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9862 9863 if (Size == 2 && W.MBB == SwitchMBB) { 9864 // If any two of the cases has the same destination, and if one value 9865 // is the same as the other, but has one bit unset that the other has set, 9866 // use bit manipulation to do two compares at once. For example: 9867 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9868 // TODO: This could be extended to merge any 2 cases in switches with 3 9869 // cases. 9870 // TODO: Handle cases where W.CaseBB != SwitchBB. 9871 CaseCluster &Small = *W.FirstCluster; 9872 CaseCluster &Big = *W.LastCluster; 9873 9874 if (Small.Low == Small.High && Big.Low == Big.High && 9875 Small.MBB == Big.MBB) { 9876 const APInt &SmallValue = Small.Low->getValue(); 9877 const APInt &BigValue = Big.Low->getValue(); 9878 9879 // Check that there is only one bit different. 9880 APInt CommonBit = BigValue ^ SmallValue; 9881 if (CommonBit.isPowerOf2()) { 9882 SDValue CondLHS = getValue(Cond); 9883 EVT VT = CondLHS.getValueType(); 9884 SDLoc DL = getCurSDLoc(); 9885 9886 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9887 DAG.getConstant(CommonBit, DL, VT)); 9888 SDValue Cond = DAG.getSetCC( 9889 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9890 ISD::SETEQ); 9891 9892 // Update successor info. 9893 // Both Small and Big will jump to Small.BB, so we sum up the 9894 // probabilities. 9895 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9896 if (BPI) 9897 addSuccessorWithProb( 9898 SwitchMBB, DefaultMBB, 9899 // The default destination is the first successor in IR. 9900 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 9901 else 9902 addSuccessorWithProb(SwitchMBB, DefaultMBB); 9903 9904 // Insert the true branch. 9905 SDValue BrCond = 9906 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 9907 DAG.getBasicBlock(Small.MBB)); 9908 // Insert the false branch. 9909 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 9910 DAG.getBasicBlock(DefaultMBB)); 9911 9912 DAG.setRoot(BrCond); 9913 return; 9914 } 9915 } 9916 } 9917 9918 if (TM.getOptLevel() != CodeGenOpt::None) { 9919 // Here, we order cases by probability so the most likely case will be 9920 // checked first. However, two clusters can have the same probability in 9921 // which case their relative ordering is non-deterministic. So we use Low 9922 // as a tie-breaker as clusters are guaranteed to never overlap. 9923 llvm::sort(W.FirstCluster, W.LastCluster + 1, 9924 [](const CaseCluster &a, const CaseCluster &b) { 9925 return a.Prob != b.Prob ? 9926 a.Prob > b.Prob : 9927 a.Low->getValue().slt(b.Low->getValue()); 9928 }); 9929 9930 // Rearrange the case blocks so that the last one falls through if possible 9931 // without changing the order of probabilities. 9932 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 9933 --I; 9934 if (I->Prob > W.LastCluster->Prob) 9935 break; 9936 if (I->Kind == CC_Range && I->MBB == NextMBB) { 9937 std::swap(*I, *W.LastCluster); 9938 break; 9939 } 9940 } 9941 } 9942 9943 // Compute total probability. 9944 BranchProbability DefaultProb = W.DefaultProb; 9945 BranchProbability UnhandledProbs = DefaultProb; 9946 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 9947 UnhandledProbs += I->Prob; 9948 9949 MachineBasicBlock *CurMBB = W.MBB; 9950 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 9951 MachineBasicBlock *Fallthrough; 9952 if (I == W.LastCluster) { 9953 // For the last cluster, fall through to the default destination. 9954 Fallthrough = DefaultMBB; 9955 } else { 9956 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 9957 CurMF->insert(BBI, Fallthrough); 9958 // Put Cond in a virtual register to make it available from the new blocks. 9959 ExportFromCurrentBlock(Cond); 9960 } 9961 UnhandledProbs -= I->Prob; 9962 9963 switch (I->Kind) { 9964 case CC_JumpTable: { 9965 // FIXME: Optimize away range check based on pivot comparisons. 9966 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 9967 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 9968 9969 // The jump block hasn't been inserted yet; insert it here. 9970 MachineBasicBlock *JumpMBB = JT->MBB; 9971 CurMF->insert(BBI, JumpMBB); 9972 9973 auto JumpProb = I->Prob; 9974 auto FallthroughProb = UnhandledProbs; 9975 9976 // If the default statement is a target of the jump table, we evenly 9977 // distribute the default probability to successors of CurMBB. Also 9978 // update the probability on the edge from JumpMBB to Fallthrough. 9979 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 9980 SE = JumpMBB->succ_end(); 9981 SI != SE; ++SI) { 9982 if (*SI == DefaultMBB) { 9983 JumpProb += DefaultProb / 2; 9984 FallthroughProb -= DefaultProb / 2; 9985 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 9986 JumpMBB->normalizeSuccProbs(); 9987 break; 9988 } 9989 } 9990 9991 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 9992 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 9993 CurMBB->normalizeSuccProbs(); 9994 9995 // The jump table header will be inserted in our current block, do the 9996 // range check, and fall through to our fallthrough block. 9997 JTH->HeaderBB = CurMBB; 9998 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 9999 10000 // If we're in the right place, emit the jump table header right now. 10001 if (CurMBB == SwitchMBB) { 10002 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10003 JTH->Emitted = true; 10004 } 10005 break; 10006 } 10007 case CC_BitTests: { 10008 // FIXME: Optimize away range check based on pivot comparisons. 10009 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 10010 10011 // The bit test blocks haven't been inserted yet; insert them here. 10012 for (BitTestCase &BTC : BTB->Cases) 10013 CurMF->insert(BBI, BTC.ThisBB); 10014 10015 // Fill in fields of the BitTestBlock. 10016 BTB->Parent = CurMBB; 10017 BTB->Default = Fallthrough; 10018 10019 BTB->DefaultProb = UnhandledProbs; 10020 // If the cases in bit test don't form a contiguous range, we evenly 10021 // distribute the probability on the edge to Fallthrough to two 10022 // successors of CurMBB. 10023 if (!BTB->ContiguousRange) { 10024 BTB->Prob += DefaultProb / 2; 10025 BTB->DefaultProb -= DefaultProb / 2; 10026 } 10027 10028 // If we're in the right place, emit the bit test header right now. 10029 if (CurMBB == SwitchMBB) { 10030 visitBitTestHeader(*BTB, SwitchMBB); 10031 BTB->Emitted = true; 10032 } 10033 break; 10034 } 10035 case CC_Range: { 10036 const Value *RHS, *LHS, *MHS; 10037 ISD::CondCode CC; 10038 if (I->Low == I->High) { 10039 // Check Cond == I->Low. 10040 CC = ISD::SETEQ; 10041 LHS = Cond; 10042 RHS=I->Low; 10043 MHS = nullptr; 10044 } else { 10045 // Check I->Low <= Cond <= I->High. 10046 CC = ISD::SETLE; 10047 LHS = I->Low; 10048 MHS = Cond; 10049 RHS = I->High; 10050 } 10051 10052 // The false probability is the sum of all unhandled cases. 10053 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10054 getCurSDLoc(), I->Prob, UnhandledProbs); 10055 10056 if (CurMBB == SwitchMBB) 10057 visitSwitchCase(CB, SwitchMBB); 10058 else 10059 SwitchCases.push_back(CB); 10060 10061 break; 10062 } 10063 } 10064 CurMBB = Fallthrough; 10065 } 10066 } 10067 10068 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10069 CaseClusterIt First, 10070 CaseClusterIt Last) { 10071 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10072 if (X.Prob != CC.Prob) 10073 return X.Prob > CC.Prob; 10074 10075 // Ties are broken by comparing the case value. 10076 return X.Low->getValue().slt(CC.Low->getValue()); 10077 }); 10078 } 10079 10080 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10081 const SwitchWorkListItem &W, 10082 Value *Cond, 10083 MachineBasicBlock *SwitchMBB) { 10084 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10085 "Clusters not sorted?"); 10086 10087 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10088 10089 // Balance the tree based on branch probabilities to create a near-optimal (in 10090 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10091 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10092 CaseClusterIt LastLeft = W.FirstCluster; 10093 CaseClusterIt FirstRight = W.LastCluster; 10094 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10095 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10096 10097 // Move LastLeft and FirstRight towards each other from opposite directions to 10098 // find a partitioning of the clusters which balances the probability on both 10099 // sides. If LeftProb and RightProb are equal, alternate which side is 10100 // taken to ensure 0-probability nodes are distributed evenly. 10101 unsigned I = 0; 10102 while (LastLeft + 1 < FirstRight) { 10103 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10104 LeftProb += (++LastLeft)->Prob; 10105 else 10106 RightProb += (--FirstRight)->Prob; 10107 I++; 10108 } 10109 10110 while (true) { 10111 // Our binary search tree differs from a typical BST in that ours can have up 10112 // to three values in each leaf. The pivot selection above doesn't take that 10113 // into account, which means the tree might require more nodes and be less 10114 // efficient. We compensate for this here. 10115 10116 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10117 unsigned NumRight = W.LastCluster - FirstRight + 1; 10118 10119 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10120 // If one side has less than 3 clusters, and the other has more than 3, 10121 // consider taking a cluster from the other side. 10122 10123 if (NumLeft < NumRight) { 10124 // Consider moving the first cluster on the right to the left side. 10125 CaseCluster &CC = *FirstRight; 10126 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10127 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10128 if (LeftSideRank <= RightSideRank) { 10129 // Moving the cluster to the left does not demote it. 10130 ++LastLeft; 10131 ++FirstRight; 10132 continue; 10133 } 10134 } else { 10135 assert(NumRight < NumLeft); 10136 // Consider moving the last element on the left to the right side. 10137 CaseCluster &CC = *LastLeft; 10138 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10139 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10140 if (RightSideRank <= LeftSideRank) { 10141 // Moving the cluster to the right does not demot it. 10142 --LastLeft; 10143 --FirstRight; 10144 continue; 10145 } 10146 } 10147 } 10148 break; 10149 } 10150 10151 assert(LastLeft + 1 == FirstRight); 10152 assert(LastLeft >= W.FirstCluster); 10153 assert(FirstRight <= W.LastCluster); 10154 10155 // Use the first element on the right as pivot since we will make less-than 10156 // comparisons against it. 10157 CaseClusterIt PivotCluster = FirstRight; 10158 assert(PivotCluster > W.FirstCluster); 10159 assert(PivotCluster <= W.LastCluster); 10160 10161 CaseClusterIt FirstLeft = W.FirstCluster; 10162 CaseClusterIt LastRight = W.LastCluster; 10163 10164 const ConstantInt *Pivot = PivotCluster->Low; 10165 10166 // New blocks will be inserted immediately after the current one. 10167 MachineFunction::iterator BBI(W.MBB); 10168 ++BBI; 10169 10170 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10171 // we can branch to its destination directly if it's squeezed exactly in 10172 // between the known lower bound and Pivot - 1. 10173 MachineBasicBlock *LeftMBB; 10174 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10175 FirstLeft->Low == W.GE && 10176 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10177 LeftMBB = FirstLeft->MBB; 10178 } else { 10179 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10180 FuncInfo.MF->insert(BBI, LeftMBB); 10181 WorkList.push_back( 10182 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10183 // Put Cond in a virtual register to make it available from the new blocks. 10184 ExportFromCurrentBlock(Cond); 10185 } 10186 10187 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10188 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10189 // directly if RHS.High equals the current upper bound. 10190 MachineBasicBlock *RightMBB; 10191 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10192 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10193 RightMBB = FirstRight->MBB; 10194 } else { 10195 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10196 FuncInfo.MF->insert(BBI, RightMBB); 10197 WorkList.push_back( 10198 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10199 // Put Cond in a virtual register to make it available from the new blocks. 10200 ExportFromCurrentBlock(Cond); 10201 } 10202 10203 // Create the CaseBlock record that will be used to lower the branch. 10204 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10205 getCurSDLoc(), LeftProb, RightProb); 10206 10207 if (W.MBB == SwitchMBB) 10208 visitSwitchCase(CB, SwitchMBB); 10209 else 10210 SwitchCases.push_back(CB); 10211 } 10212 10213 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10214 // from the swith statement. 10215 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10216 BranchProbability PeeledCaseProb) { 10217 if (PeeledCaseProb == BranchProbability::getOne()) 10218 return BranchProbability::getZero(); 10219 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10220 10221 uint32_t Numerator = CaseProb.getNumerator(); 10222 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10223 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10224 } 10225 10226 // Try to peel the top probability case if it exceeds the threshold. 10227 // Return current MachineBasicBlock for the switch statement if the peeling 10228 // does not occur. 10229 // If the peeling is performed, return the newly created MachineBasicBlock 10230 // for the peeled switch statement. Also update Clusters to remove the peeled 10231 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10232 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10233 const SwitchInst &SI, CaseClusterVector &Clusters, 10234 BranchProbability &PeeledCaseProb) { 10235 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10236 // Don't perform if there is only one cluster or optimizing for size. 10237 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10238 TM.getOptLevel() == CodeGenOpt::None || 10239 SwitchMBB->getParent()->getFunction().optForMinSize()) 10240 return SwitchMBB; 10241 10242 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10243 unsigned PeeledCaseIndex = 0; 10244 bool SwitchPeeled = false; 10245 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10246 CaseCluster &CC = Clusters[Index]; 10247 if (CC.Prob < TopCaseProb) 10248 continue; 10249 TopCaseProb = CC.Prob; 10250 PeeledCaseIndex = Index; 10251 SwitchPeeled = true; 10252 } 10253 if (!SwitchPeeled) 10254 return SwitchMBB; 10255 10256 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10257 << TopCaseProb << "\n"); 10258 10259 // Record the MBB for the peeled switch statement. 10260 MachineFunction::iterator BBI(SwitchMBB); 10261 ++BBI; 10262 MachineBasicBlock *PeeledSwitchMBB = 10263 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10264 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10265 10266 ExportFromCurrentBlock(SI.getCondition()); 10267 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10268 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10269 nullptr, nullptr, TopCaseProb.getCompl()}; 10270 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10271 10272 Clusters.erase(PeeledCaseIt); 10273 for (CaseCluster &CC : Clusters) { 10274 LLVM_DEBUG( 10275 dbgs() << "Scale the probablity for one cluster, before scaling: " 10276 << CC.Prob << "\n"); 10277 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10278 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10279 } 10280 PeeledCaseProb = TopCaseProb; 10281 return PeeledSwitchMBB; 10282 } 10283 10284 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10285 // Extract cases from the switch. 10286 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10287 CaseClusterVector Clusters; 10288 Clusters.reserve(SI.getNumCases()); 10289 for (auto I : SI.cases()) { 10290 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10291 const ConstantInt *CaseVal = I.getCaseValue(); 10292 BranchProbability Prob = 10293 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10294 : BranchProbability(1, SI.getNumCases() + 1); 10295 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10296 } 10297 10298 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10299 10300 // Cluster adjacent cases with the same destination. We do this at all 10301 // optimization levels because it's cheap to do and will make codegen faster 10302 // if there are many clusters. 10303 sortAndRangeify(Clusters); 10304 10305 if (TM.getOptLevel() != CodeGenOpt::None) { 10306 // Replace an unreachable default with the most popular destination. 10307 // FIXME: Exploit unreachable default more aggressively. 10308 bool UnreachableDefault = 10309 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 10310 if (UnreachableDefault && !Clusters.empty()) { 10311 DenseMap<const BasicBlock *, unsigned> Popularity; 10312 unsigned MaxPop = 0; 10313 const BasicBlock *MaxBB = nullptr; 10314 for (auto I : SI.cases()) { 10315 const BasicBlock *BB = I.getCaseSuccessor(); 10316 if (++Popularity[BB] > MaxPop) { 10317 MaxPop = Popularity[BB]; 10318 MaxBB = BB; 10319 } 10320 } 10321 // Set new default. 10322 assert(MaxPop > 0 && MaxBB); 10323 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 10324 10325 // Remove cases that were pointing to the destination that is now the 10326 // default. 10327 CaseClusterVector New; 10328 New.reserve(Clusters.size()); 10329 for (CaseCluster &CC : Clusters) { 10330 if (CC.MBB != DefaultMBB) 10331 New.push_back(CC); 10332 } 10333 Clusters = std::move(New); 10334 } 10335 } 10336 10337 // The branch probablity of the peeled case. 10338 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10339 MachineBasicBlock *PeeledSwitchMBB = 10340 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10341 10342 // If there is only the default destination, jump there directly. 10343 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10344 if (Clusters.empty()) { 10345 assert(PeeledSwitchMBB == SwitchMBB); 10346 SwitchMBB->addSuccessor(DefaultMBB); 10347 if (DefaultMBB != NextBlock(SwitchMBB)) { 10348 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10349 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10350 } 10351 return; 10352 } 10353 10354 findJumpTables(Clusters, &SI, DefaultMBB); 10355 findBitTestClusters(Clusters, &SI); 10356 10357 LLVM_DEBUG({ 10358 dbgs() << "Case clusters: "; 10359 for (const CaseCluster &C : Clusters) { 10360 if (C.Kind == CC_JumpTable) 10361 dbgs() << "JT:"; 10362 if (C.Kind == CC_BitTests) 10363 dbgs() << "BT:"; 10364 10365 C.Low->getValue().print(dbgs(), true); 10366 if (C.Low != C.High) { 10367 dbgs() << '-'; 10368 C.High->getValue().print(dbgs(), true); 10369 } 10370 dbgs() << ' '; 10371 } 10372 dbgs() << '\n'; 10373 }); 10374 10375 assert(!Clusters.empty()); 10376 SwitchWorkList WorkList; 10377 CaseClusterIt First = Clusters.begin(); 10378 CaseClusterIt Last = Clusters.end() - 1; 10379 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10380 // Scale the branchprobability for DefaultMBB if the peel occurs and 10381 // DefaultMBB is not replaced. 10382 if (PeeledCaseProb != BranchProbability::getZero() && 10383 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10384 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10385 WorkList.push_back( 10386 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10387 10388 while (!WorkList.empty()) { 10389 SwitchWorkListItem W = WorkList.back(); 10390 WorkList.pop_back(); 10391 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10392 10393 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10394 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10395 // For optimized builds, lower large range as a balanced binary tree. 10396 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10397 continue; 10398 } 10399 10400 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10401 } 10402 } 10403