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 if (!JTH.OmitRangeCheck) { 2180 // Emit the range check for the jump table, and branch to the default block 2181 // for the switch statement if the value being switched on exceeds the 2182 // largest case in the switch. 2183 SDValue CMP = DAG.getSetCC( 2184 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2185 Sub.getValueType()), 2186 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2187 2188 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2189 MVT::Other, CopyTo, CMP, 2190 DAG.getBasicBlock(JT.Default)); 2191 2192 // Avoid emitting unnecessary branches to the next block. 2193 if (JT.MBB != NextBlock(SwitchBB)) 2194 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2195 DAG.getBasicBlock(JT.MBB)); 2196 2197 DAG.setRoot(BrCond); 2198 } else { 2199 SDValue BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2200 DAG.getBasicBlock(JT.MBB)); 2201 DAG.setRoot(BrCond); 2202 SwitchBB->removeSuccessor(JT.Default, true); 2203 } 2204 } 2205 2206 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2207 /// variable if there exists one. 2208 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2209 SDValue &Chain) { 2210 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2211 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2212 MachineFunction &MF = DAG.getMachineFunction(); 2213 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2214 MachineSDNode *Node = 2215 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2216 if (Global) { 2217 MachinePointerInfo MPInfo(Global); 2218 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2219 MachineMemOperand::MODereferenceable; 2220 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2221 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2222 DAG.setNodeMemRefs(Node, {MemRef}); 2223 } 2224 return SDValue(Node, 0); 2225 } 2226 2227 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2228 /// tail spliced into a stack protector check success bb. 2229 /// 2230 /// For a high level explanation of how this fits into the stack protector 2231 /// generation see the comment on the declaration of class 2232 /// StackProtectorDescriptor. 2233 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2234 MachineBasicBlock *ParentBB) { 2235 2236 // First create the loads to the guard/stack slot for the comparison. 2237 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2238 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2239 2240 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2241 int FI = MFI.getStackProtectorIndex(); 2242 2243 SDValue Guard; 2244 SDLoc dl = getCurSDLoc(); 2245 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2246 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2247 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2248 2249 // Generate code to load the content of the guard slot. 2250 SDValue GuardVal = DAG.getLoad( 2251 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2252 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2253 MachineMemOperand::MOVolatile); 2254 2255 if (TLI.useStackGuardXorFP()) 2256 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2257 2258 // Retrieve guard check function, nullptr if instrumentation is inlined. 2259 if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) { 2260 // The target provides a guard check function to validate the guard value. 2261 // Generate a call to that function with the content of the guard slot as 2262 // argument. 2263 auto *Fn = cast<Function>(GuardCheck); 2264 FunctionType *FnTy = Fn->getFunctionType(); 2265 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2266 2267 TargetLowering::ArgListTy Args; 2268 TargetLowering::ArgListEntry Entry; 2269 Entry.Node = GuardVal; 2270 Entry.Ty = FnTy->getParamType(0); 2271 if (Fn->hasAttribute(1, Attribute::AttrKind::InReg)) 2272 Entry.IsInReg = true; 2273 Args.push_back(Entry); 2274 2275 TargetLowering::CallLoweringInfo CLI(DAG); 2276 CLI.setDebugLoc(getCurSDLoc()) 2277 .setChain(DAG.getEntryNode()) 2278 .setCallee(Fn->getCallingConv(), FnTy->getReturnType(), 2279 getValue(GuardCheck), std::move(Args)); 2280 2281 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2282 DAG.setRoot(Result.second); 2283 return; 2284 } 2285 2286 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2287 // Otherwise, emit a volatile load to retrieve the stack guard value. 2288 SDValue Chain = DAG.getEntryNode(); 2289 if (TLI.useLoadStackGuardNode()) { 2290 Guard = getLoadStackGuard(DAG, dl, Chain); 2291 } else { 2292 const Value *IRGuard = TLI.getSDagStackGuard(M); 2293 SDValue GuardPtr = getValue(IRGuard); 2294 2295 Guard = 2296 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2297 Align, MachineMemOperand::MOVolatile); 2298 } 2299 2300 // Perform the comparison via a subtract/getsetcc. 2301 EVT VT = Guard.getValueType(); 2302 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2303 2304 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2305 *DAG.getContext(), 2306 Sub.getValueType()), 2307 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2308 2309 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2310 // branch to failure MBB. 2311 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2312 MVT::Other, GuardVal.getOperand(0), 2313 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2314 // Otherwise branch to success MBB. 2315 SDValue Br = DAG.getNode(ISD::BR, dl, 2316 MVT::Other, BrCond, 2317 DAG.getBasicBlock(SPD.getSuccessMBB())); 2318 2319 DAG.setRoot(Br); 2320 } 2321 2322 /// Codegen the failure basic block for a stack protector check. 2323 /// 2324 /// A failure stack protector machine basic block consists simply of a call to 2325 /// __stack_chk_fail(). 2326 /// 2327 /// For a high level explanation of how this fits into the stack protector 2328 /// generation see the comment on the declaration of class 2329 /// StackProtectorDescriptor. 2330 void 2331 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2332 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2333 SDValue Chain = 2334 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2335 None, false, getCurSDLoc(), false, false).second; 2336 DAG.setRoot(Chain); 2337 } 2338 2339 /// visitBitTestHeader - This function emits necessary code to produce value 2340 /// suitable for "bit tests" 2341 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2342 MachineBasicBlock *SwitchBB) { 2343 SDLoc dl = getCurSDLoc(); 2344 2345 // Subtract the minimum value 2346 SDValue SwitchOp = getValue(B.SValue); 2347 EVT VT = SwitchOp.getValueType(); 2348 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2349 DAG.getConstant(B.First, dl, VT)); 2350 2351 // Check range 2352 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2353 SDValue RangeCmp = DAG.getSetCC( 2354 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2355 Sub.getValueType()), 2356 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2357 2358 // Determine the type of the test operands. 2359 bool UsePtrType = false; 2360 if (!TLI.isTypeLegal(VT)) 2361 UsePtrType = true; 2362 else { 2363 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2364 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2365 // Switch table case range are encoded into series of masks. 2366 // Just use pointer type, it's guaranteed to fit. 2367 UsePtrType = true; 2368 break; 2369 } 2370 } 2371 if (UsePtrType) { 2372 VT = TLI.getPointerTy(DAG.getDataLayout()); 2373 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2374 } 2375 2376 B.RegVT = VT.getSimpleVT(); 2377 B.Reg = FuncInfo.CreateReg(B.RegVT); 2378 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2379 2380 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2381 2382 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2383 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2384 SwitchBB->normalizeSuccProbs(); 2385 2386 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2387 MVT::Other, CopyTo, RangeCmp, 2388 DAG.getBasicBlock(B.Default)); 2389 2390 // Avoid emitting unnecessary branches to the next block. 2391 if (MBB != NextBlock(SwitchBB)) 2392 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2393 DAG.getBasicBlock(MBB)); 2394 2395 DAG.setRoot(BrRange); 2396 } 2397 2398 /// visitBitTestCase - this function produces one "bit test" 2399 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2400 MachineBasicBlock* NextMBB, 2401 BranchProbability BranchProbToNext, 2402 unsigned Reg, 2403 BitTestCase &B, 2404 MachineBasicBlock *SwitchBB) { 2405 SDLoc dl = getCurSDLoc(); 2406 MVT VT = BB.RegVT; 2407 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2408 SDValue Cmp; 2409 unsigned PopCount = countPopulation(B.Mask); 2410 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2411 if (PopCount == 1) { 2412 // Testing for a single bit; just compare the shift count with what it 2413 // would need to be to shift a 1 bit in that position. 2414 Cmp = DAG.getSetCC( 2415 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2416 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2417 ISD::SETEQ); 2418 } else if (PopCount == BB.Range) { 2419 // There is only one zero bit in the range, test for it directly. 2420 Cmp = DAG.getSetCC( 2421 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2422 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2423 ISD::SETNE); 2424 } else { 2425 // Make desired shift 2426 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2427 DAG.getConstant(1, dl, VT), ShiftOp); 2428 2429 // Emit bit tests and jumps 2430 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2431 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2432 Cmp = DAG.getSetCC( 2433 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2434 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2435 } 2436 2437 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2438 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2439 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2440 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2441 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2442 // one as they are relative probabilities (and thus work more like weights), 2443 // and hence we need to normalize them to let the sum of them become one. 2444 SwitchBB->normalizeSuccProbs(); 2445 2446 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2447 MVT::Other, getControlRoot(), 2448 Cmp, DAG.getBasicBlock(B.TargetBB)); 2449 2450 // Avoid emitting unnecessary branches to the next block. 2451 if (NextMBB != NextBlock(SwitchBB)) 2452 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2453 DAG.getBasicBlock(NextMBB)); 2454 2455 DAG.setRoot(BrAnd); 2456 } 2457 2458 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2459 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2460 2461 // Retrieve successors. Look through artificial IR level blocks like 2462 // catchswitch for successors. 2463 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2464 const BasicBlock *EHPadBB = I.getSuccessor(1); 2465 2466 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2467 // have to do anything here to lower funclet bundles. 2468 assert(!I.hasOperandBundlesOtherThan( 2469 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2470 "Cannot lower invokes with arbitrary operand bundles yet!"); 2471 2472 const Value *Callee(I.getCalledValue()); 2473 const Function *Fn = dyn_cast<Function>(Callee); 2474 if (isa<InlineAsm>(Callee)) 2475 visitInlineAsm(&I); 2476 else if (Fn && Fn->isIntrinsic()) { 2477 switch (Fn->getIntrinsicID()) { 2478 default: 2479 llvm_unreachable("Cannot invoke this intrinsic"); 2480 case Intrinsic::donothing: 2481 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2482 break; 2483 case Intrinsic::experimental_patchpoint_void: 2484 case Intrinsic::experimental_patchpoint_i64: 2485 visitPatchpoint(&I, EHPadBB); 2486 break; 2487 case Intrinsic::experimental_gc_statepoint: 2488 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2489 break; 2490 } 2491 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2492 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2493 // Eventually we will support lowering the @llvm.experimental.deoptimize 2494 // intrinsic, and right now there are no plans to support other intrinsics 2495 // with deopt state. 2496 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2497 } else { 2498 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2499 } 2500 2501 // If the value of the invoke is used outside of its defining block, make it 2502 // available as a virtual register. 2503 // We already took care of the exported value for the statepoint instruction 2504 // during call to the LowerStatepoint. 2505 if (!isStatepoint(I)) { 2506 CopyToExportRegsIfNeeded(&I); 2507 } 2508 2509 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2510 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2511 BranchProbability EHPadBBProb = 2512 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2513 : BranchProbability::getZero(); 2514 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2515 2516 // Update successor info. 2517 addSuccessorWithProb(InvokeMBB, Return); 2518 for (auto &UnwindDest : UnwindDests) { 2519 UnwindDest.first->setIsEHPad(); 2520 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2521 } 2522 InvokeMBB->normalizeSuccProbs(); 2523 2524 // Drop into normal successor. 2525 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2526 MVT::Other, getControlRoot(), 2527 DAG.getBasicBlock(Return))); 2528 } 2529 2530 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2531 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2532 } 2533 2534 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2535 assert(FuncInfo.MBB->isEHPad() && 2536 "Call to landingpad not in landing pad!"); 2537 2538 // If there aren't registers to copy the values into (e.g., during SjLj 2539 // exceptions), then don't bother to create these DAG nodes. 2540 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2541 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2542 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2543 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2544 return; 2545 2546 // If landingpad's return type is token type, we don't create DAG nodes 2547 // for its exception pointer and selector value. The extraction of exception 2548 // pointer or selector value from token type landingpads is not currently 2549 // supported. 2550 if (LP.getType()->isTokenTy()) 2551 return; 2552 2553 SmallVector<EVT, 2> ValueVTs; 2554 SDLoc dl = getCurSDLoc(); 2555 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2556 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2557 2558 // Get the two live-in registers as SDValues. The physregs have already been 2559 // copied into virtual registers. 2560 SDValue Ops[2]; 2561 if (FuncInfo.ExceptionPointerVirtReg) { 2562 Ops[0] = DAG.getZExtOrTrunc( 2563 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2564 FuncInfo.ExceptionPointerVirtReg, 2565 TLI.getPointerTy(DAG.getDataLayout())), 2566 dl, ValueVTs[0]); 2567 } else { 2568 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2569 } 2570 Ops[1] = DAG.getZExtOrTrunc( 2571 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2572 FuncInfo.ExceptionSelectorVirtReg, 2573 TLI.getPointerTy(DAG.getDataLayout())), 2574 dl, ValueVTs[1]); 2575 2576 // Merge into one. 2577 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2578 DAG.getVTList(ValueVTs), Ops); 2579 setValue(&LP, Res); 2580 } 2581 2582 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2583 #ifndef NDEBUG 2584 for (const CaseCluster &CC : Clusters) 2585 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2586 #endif 2587 2588 llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) { 2589 return a.Low->getValue().slt(b.Low->getValue()); 2590 }); 2591 2592 // Merge adjacent clusters with the same destination. 2593 const unsigned N = Clusters.size(); 2594 unsigned DstIndex = 0; 2595 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2596 CaseCluster &CC = Clusters[SrcIndex]; 2597 const ConstantInt *CaseVal = CC.Low; 2598 MachineBasicBlock *Succ = CC.MBB; 2599 2600 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2601 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2602 // If this case has the same successor and is a neighbour, merge it into 2603 // the previous cluster. 2604 Clusters[DstIndex - 1].High = CaseVal; 2605 Clusters[DstIndex - 1].Prob += CC.Prob; 2606 } else { 2607 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2608 sizeof(Clusters[SrcIndex])); 2609 } 2610 } 2611 Clusters.resize(DstIndex); 2612 } 2613 2614 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2615 MachineBasicBlock *Last) { 2616 // Update JTCases. 2617 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2618 if (JTCases[i].first.HeaderBB == First) 2619 JTCases[i].first.HeaderBB = Last; 2620 2621 // Update BitTestCases. 2622 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2623 if (BitTestCases[i].Parent == First) 2624 BitTestCases[i].Parent = Last; 2625 } 2626 2627 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2628 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2629 2630 // Update machine-CFG edges with unique successors. 2631 SmallSet<BasicBlock*, 32> Done; 2632 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2633 BasicBlock *BB = I.getSuccessor(i); 2634 bool Inserted = Done.insert(BB).second; 2635 if (!Inserted) 2636 continue; 2637 2638 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2639 addSuccessorWithProb(IndirectBrMBB, Succ); 2640 } 2641 IndirectBrMBB->normalizeSuccProbs(); 2642 2643 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2644 MVT::Other, getControlRoot(), 2645 getValue(I.getAddress()))); 2646 } 2647 2648 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2649 if (!DAG.getTarget().Options.TrapUnreachable) 2650 return; 2651 2652 // We may be able to ignore unreachable behind a noreturn call. 2653 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2654 const BasicBlock &BB = *I.getParent(); 2655 if (&I != &BB.front()) { 2656 BasicBlock::const_iterator PredI = 2657 std::prev(BasicBlock::const_iterator(&I)); 2658 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2659 if (Call->doesNotReturn()) 2660 return; 2661 } 2662 } 2663 } 2664 2665 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2666 } 2667 2668 void SelectionDAGBuilder::visitFSub(const User &I) { 2669 // -0.0 - X --> fneg 2670 Type *Ty = I.getType(); 2671 if (isa<Constant>(I.getOperand(0)) && 2672 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2673 SDValue Op2 = getValue(I.getOperand(1)); 2674 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2675 Op2.getValueType(), Op2)); 2676 return; 2677 } 2678 2679 visitBinary(I, ISD::FSUB); 2680 } 2681 2682 /// Checks if the given instruction performs a vector reduction, in which case 2683 /// we have the freedom to alter the elements in the result as long as the 2684 /// reduction of them stays unchanged. 2685 static bool isVectorReductionOp(const User *I) { 2686 const Instruction *Inst = dyn_cast<Instruction>(I); 2687 if (!Inst || !Inst->getType()->isVectorTy()) 2688 return false; 2689 2690 auto OpCode = Inst->getOpcode(); 2691 switch (OpCode) { 2692 case Instruction::Add: 2693 case Instruction::Mul: 2694 case Instruction::And: 2695 case Instruction::Or: 2696 case Instruction::Xor: 2697 break; 2698 case Instruction::FAdd: 2699 case Instruction::FMul: 2700 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2701 if (FPOp->getFastMathFlags().isFast()) 2702 break; 2703 LLVM_FALLTHROUGH; 2704 default: 2705 return false; 2706 } 2707 2708 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2709 // Ensure the reduction size is a power of 2. 2710 if (!isPowerOf2_32(ElemNum)) 2711 return false; 2712 2713 unsigned ElemNumToReduce = ElemNum; 2714 2715 // Do DFS search on the def-use chain from the given instruction. We only 2716 // allow four kinds of operations during the search until we reach the 2717 // instruction that extracts the first element from the vector: 2718 // 2719 // 1. The reduction operation of the same opcode as the given instruction. 2720 // 2721 // 2. PHI node. 2722 // 2723 // 3. ShuffleVector instruction together with a reduction operation that 2724 // does a partial reduction. 2725 // 2726 // 4. ExtractElement that extracts the first element from the vector, and we 2727 // stop searching the def-use chain here. 2728 // 2729 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2730 // from 1-3 to the stack to continue the DFS. The given instruction is not 2731 // a reduction operation if we meet any other instructions other than those 2732 // listed above. 2733 2734 SmallVector<const User *, 16> UsersToVisit{Inst}; 2735 SmallPtrSet<const User *, 16> Visited; 2736 bool ReduxExtracted = false; 2737 2738 while (!UsersToVisit.empty()) { 2739 auto User = UsersToVisit.back(); 2740 UsersToVisit.pop_back(); 2741 if (!Visited.insert(User).second) 2742 continue; 2743 2744 for (const auto &U : User->users()) { 2745 auto Inst = dyn_cast<Instruction>(U); 2746 if (!Inst) 2747 return false; 2748 2749 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2750 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2751 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 2752 return false; 2753 UsersToVisit.push_back(U); 2754 } else if (const ShuffleVectorInst *ShufInst = 2755 dyn_cast<ShuffleVectorInst>(U)) { 2756 // Detect the following pattern: A ShuffleVector instruction together 2757 // with a reduction that do partial reduction on the first and second 2758 // ElemNumToReduce / 2 elements, and store the result in 2759 // ElemNumToReduce / 2 elements in another vector. 2760 2761 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2762 if (ResultElements < ElemNum) 2763 return false; 2764 2765 if (ElemNumToReduce == 1) 2766 return false; 2767 if (!isa<UndefValue>(U->getOperand(1))) 2768 return false; 2769 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2770 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2771 return false; 2772 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2773 if (ShufInst->getMaskValue(i) != -1) 2774 return false; 2775 2776 // There is only one user of this ShuffleVector instruction, which 2777 // must be a reduction operation. 2778 if (!U->hasOneUse()) 2779 return false; 2780 2781 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2782 if (!U2 || U2->getOpcode() != OpCode) 2783 return false; 2784 2785 // Check operands of the reduction operation. 2786 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2787 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2788 UsersToVisit.push_back(U2); 2789 ElemNumToReduce /= 2; 2790 } else 2791 return false; 2792 } else if (isa<ExtractElementInst>(U)) { 2793 // At this moment we should have reduced all elements in the vector. 2794 if (ElemNumToReduce != 1) 2795 return false; 2796 2797 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2798 if (!Val || !Val->isZero()) 2799 return false; 2800 2801 ReduxExtracted = true; 2802 } else 2803 return false; 2804 } 2805 } 2806 return ReduxExtracted; 2807 } 2808 2809 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 2810 SDNodeFlags Flags; 2811 2812 SDValue Op = getValue(I.getOperand(0)); 2813 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 2814 Op, Flags); 2815 setValue(&I, UnNodeValue); 2816 } 2817 2818 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 2819 SDNodeFlags Flags; 2820 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 2821 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 2822 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 2823 } 2824 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 2825 Flags.setExact(ExactOp->isExact()); 2826 } 2827 if (isVectorReductionOp(&I)) { 2828 Flags.setVectorReduction(true); 2829 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2830 } 2831 2832 SDValue Op1 = getValue(I.getOperand(0)); 2833 SDValue Op2 = getValue(I.getOperand(1)); 2834 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 2835 Op1, Op2, Flags); 2836 setValue(&I, BinNodeValue); 2837 } 2838 2839 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2840 SDValue Op1 = getValue(I.getOperand(0)); 2841 SDValue Op2 = getValue(I.getOperand(1)); 2842 2843 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2844 Op1.getValueType(), DAG.getDataLayout()); 2845 2846 // Coerce the shift amount to the right type if we can. 2847 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2848 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2849 unsigned Op2Size = Op2.getValueSizeInBits(); 2850 SDLoc DL = getCurSDLoc(); 2851 2852 // If the operand is smaller than the shift count type, promote it. 2853 if (ShiftSize > Op2Size) 2854 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2855 2856 // If the operand is larger than the shift count type but the shift 2857 // count type has enough bits to represent any shift value, truncate 2858 // it now. This is a common case and it exposes the truncate to 2859 // optimization early. 2860 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 2861 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2862 // Otherwise we'll need to temporarily settle for some other convenient 2863 // type. Type legalization will make adjustments once the shiftee is split. 2864 else 2865 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2866 } 2867 2868 bool nuw = false; 2869 bool nsw = false; 2870 bool exact = false; 2871 2872 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2873 2874 if (const OverflowingBinaryOperator *OFBinOp = 2875 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2876 nuw = OFBinOp->hasNoUnsignedWrap(); 2877 nsw = OFBinOp->hasNoSignedWrap(); 2878 } 2879 if (const PossiblyExactOperator *ExactOp = 2880 dyn_cast<const PossiblyExactOperator>(&I)) 2881 exact = ExactOp->isExact(); 2882 } 2883 SDNodeFlags Flags; 2884 Flags.setExact(exact); 2885 Flags.setNoSignedWrap(nsw); 2886 Flags.setNoUnsignedWrap(nuw); 2887 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2888 Flags); 2889 setValue(&I, Res); 2890 } 2891 2892 void SelectionDAGBuilder::visitSDiv(const User &I) { 2893 SDValue Op1 = getValue(I.getOperand(0)); 2894 SDValue Op2 = getValue(I.getOperand(1)); 2895 2896 SDNodeFlags Flags; 2897 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2898 cast<PossiblyExactOperator>(&I)->isExact()); 2899 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2900 Op2, Flags)); 2901 } 2902 2903 void SelectionDAGBuilder::visitICmp(const User &I) { 2904 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2905 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2906 predicate = IC->getPredicate(); 2907 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2908 predicate = ICmpInst::Predicate(IC->getPredicate()); 2909 SDValue Op1 = getValue(I.getOperand(0)); 2910 SDValue Op2 = getValue(I.getOperand(1)); 2911 ISD::CondCode Opcode = getICmpCondCode(predicate); 2912 2913 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2914 I.getType()); 2915 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2916 } 2917 2918 void SelectionDAGBuilder::visitFCmp(const User &I) { 2919 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2920 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2921 predicate = FC->getPredicate(); 2922 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2923 predicate = FCmpInst::Predicate(FC->getPredicate()); 2924 SDValue Op1 = getValue(I.getOperand(0)); 2925 SDValue Op2 = getValue(I.getOperand(1)); 2926 2927 ISD::CondCode Condition = getFCmpCondCode(predicate); 2928 auto *FPMO = dyn_cast<FPMathOperator>(&I); 2929 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 2930 Condition = getFCmpCodeWithoutNaN(Condition); 2931 2932 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2933 I.getType()); 2934 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2935 } 2936 2937 // Check if the condition of the select has one use or two users that are both 2938 // selects with the same condition. 2939 static bool hasOnlySelectUsers(const Value *Cond) { 2940 return llvm::all_of(Cond->users(), [](const Value *V) { 2941 return isa<SelectInst>(V); 2942 }); 2943 } 2944 2945 void SelectionDAGBuilder::visitSelect(const User &I) { 2946 SmallVector<EVT, 4> ValueVTs; 2947 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2948 ValueVTs); 2949 unsigned NumValues = ValueVTs.size(); 2950 if (NumValues == 0) return; 2951 2952 SmallVector<SDValue, 4> Values(NumValues); 2953 SDValue Cond = getValue(I.getOperand(0)); 2954 SDValue LHSVal = getValue(I.getOperand(1)); 2955 SDValue RHSVal = getValue(I.getOperand(2)); 2956 auto BaseOps = {Cond}; 2957 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2958 ISD::VSELECT : ISD::SELECT; 2959 2960 // Min/max matching is only viable if all output VTs are the same. 2961 if (is_splat(ValueVTs)) { 2962 EVT VT = ValueVTs[0]; 2963 LLVMContext &Ctx = *DAG.getContext(); 2964 auto &TLI = DAG.getTargetLoweringInfo(); 2965 2966 // We care about the legality of the operation after it has been type 2967 // legalized. 2968 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 2969 VT != TLI.getTypeToTransformTo(Ctx, VT)) 2970 VT = TLI.getTypeToTransformTo(Ctx, VT); 2971 2972 // If the vselect is legal, assume we want to leave this as a vector setcc + 2973 // vselect. Otherwise, if this is going to be scalarized, we want to see if 2974 // min/max is legal on the scalar type. 2975 bool UseScalarMinMax = VT.isVector() && 2976 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 2977 2978 Value *LHS, *RHS; 2979 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2980 ISD::NodeType Opc = ISD::DELETED_NODE; 2981 switch (SPR.Flavor) { 2982 case SPF_UMAX: Opc = ISD::UMAX; break; 2983 case SPF_UMIN: Opc = ISD::UMIN; break; 2984 case SPF_SMAX: Opc = ISD::SMAX; break; 2985 case SPF_SMIN: Opc = ISD::SMIN; break; 2986 case SPF_FMINNUM: 2987 switch (SPR.NaNBehavior) { 2988 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2989 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 2990 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 2991 case SPNB_RETURNS_ANY: { 2992 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 2993 Opc = ISD::FMINNUM; 2994 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 2995 Opc = ISD::FMINIMUM; 2996 else if (UseScalarMinMax) 2997 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 2998 ISD::FMINNUM : ISD::FMINIMUM; 2999 break; 3000 } 3001 } 3002 break; 3003 case SPF_FMAXNUM: 3004 switch (SPR.NaNBehavior) { 3005 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3006 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3007 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3008 case SPNB_RETURNS_ANY: 3009 3010 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3011 Opc = ISD::FMAXNUM; 3012 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3013 Opc = ISD::FMAXIMUM; 3014 else if (UseScalarMinMax) 3015 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3016 ISD::FMAXNUM : ISD::FMAXIMUM; 3017 break; 3018 } 3019 break; 3020 default: break; 3021 } 3022 3023 if (Opc != ISD::DELETED_NODE && 3024 (TLI.isOperationLegalOrCustom(Opc, VT) || 3025 (UseScalarMinMax && 3026 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3027 // If the underlying comparison instruction is used by any other 3028 // instruction, the consumed instructions won't be destroyed, so it is 3029 // not profitable to convert to a min/max. 3030 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3031 OpCode = Opc; 3032 LHSVal = getValue(LHS); 3033 RHSVal = getValue(RHS); 3034 BaseOps = {}; 3035 } 3036 } 3037 3038 for (unsigned i = 0; i != NumValues; ++i) { 3039 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3040 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3041 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3042 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 3043 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 3044 Ops); 3045 } 3046 3047 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3048 DAG.getVTList(ValueVTs), Values)); 3049 } 3050 3051 void SelectionDAGBuilder::visitTrunc(const User &I) { 3052 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3053 SDValue N = getValue(I.getOperand(0)); 3054 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3055 I.getType()); 3056 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3057 } 3058 3059 void SelectionDAGBuilder::visitZExt(const User &I) { 3060 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3061 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3062 SDValue N = getValue(I.getOperand(0)); 3063 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3064 I.getType()); 3065 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3066 } 3067 3068 void SelectionDAGBuilder::visitSExt(const User &I) { 3069 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3070 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3071 SDValue N = getValue(I.getOperand(0)); 3072 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3073 I.getType()); 3074 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3075 } 3076 3077 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3078 // FPTrunc is never a no-op cast, no need to check 3079 SDValue N = getValue(I.getOperand(0)); 3080 SDLoc dl = getCurSDLoc(); 3081 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3082 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3083 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3084 DAG.getTargetConstant( 3085 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3086 } 3087 3088 void SelectionDAGBuilder::visitFPExt(const User &I) { 3089 // FPExt is never a no-op cast, no need to check 3090 SDValue N = getValue(I.getOperand(0)); 3091 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3092 I.getType()); 3093 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3094 } 3095 3096 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3097 // FPToUI is never a no-op cast, no need to check 3098 SDValue N = getValue(I.getOperand(0)); 3099 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3100 I.getType()); 3101 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3102 } 3103 3104 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3105 // FPToSI is never a no-op cast, no need to check 3106 SDValue N = getValue(I.getOperand(0)); 3107 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3108 I.getType()); 3109 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3110 } 3111 3112 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3113 // UIToFP is never a no-op cast, no need to check 3114 SDValue N = getValue(I.getOperand(0)); 3115 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3116 I.getType()); 3117 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3118 } 3119 3120 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3121 // SIToFP is never a no-op cast, no need to check 3122 SDValue N = getValue(I.getOperand(0)); 3123 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3124 I.getType()); 3125 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3126 } 3127 3128 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3129 // What to do depends on the size of the integer and the size of the pointer. 3130 // We can either truncate, zero extend, or no-op, accordingly. 3131 SDValue N = getValue(I.getOperand(0)); 3132 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3133 I.getType()); 3134 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3135 } 3136 3137 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3138 // What to do depends on the size of the integer and the size of the pointer. 3139 // We can either truncate, zero extend, or no-op, accordingly. 3140 SDValue N = getValue(I.getOperand(0)); 3141 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3142 I.getType()); 3143 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3144 } 3145 3146 void SelectionDAGBuilder::visitBitCast(const User &I) { 3147 SDValue N = getValue(I.getOperand(0)); 3148 SDLoc dl = getCurSDLoc(); 3149 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3150 I.getType()); 3151 3152 // BitCast assures us that source and destination are the same size so this is 3153 // either a BITCAST or a no-op. 3154 if (DestVT != N.getValueType()) 3155 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3156 DestVT, N)); // convert types. 3157 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3158 // might fold any kind of constant expression to an integer constant and that 3159 // is not what we are looking for. Only recognize a bitcast of a genuine 3160 // constant integer as an opaque constant. 3161 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3162 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3163 /*isOpaque*/true)); 3164 else 3165 setValue(&I, N); // noop cast. 3166 } 3167 3168 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3169 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3170 const Value *SV = I.getOperand(0); 3171 SDValue N = getValue(SV); 3172 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3173 3174 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3175 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3176 3177 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3178 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3179 3180 setValue(&I, N); 3181 } 3182 3183 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3184 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3185 SDValue InVec = getValue(I.getOperand(0)); 3186 SDValue InVal = getValue(I.getOperand(1)); 3187 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3188 TLI.getVectorIdxTy(DAG.getDataLayout())); 3189 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3190 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3191 InVec, InVal, InIdx)); 3192 } 3193 3194 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3195 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3196 SDValue InVec = getValue(I.getOperand(0)); 3197 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3198 TLI.getVectorIdxTy(DAG.getDataLayout())); 3199 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3200 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3201 InVec, InIdx)); 3202 } 3203 3204 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3205 SDValue Src1 = getValue(I.getOperand(0)); 3206 SDValue Src2 = getValue(I.getOperand(1)); 3207 SDLoc DL = getCurSDLoc(); 3208 3209 SmallVector<int, 8> Mask; 3210 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3211 unsigned MaskNumElts = Mask.size(); 3212 3213 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3214 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3215 EVT SrcVT = Src1.getValueType(); 3216 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3217 3218 if (SrcNumElts == MaskNumElts) { 3219 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3220 return; 3221 } 3222 3223 // Normalize the shuffle vector since mask and vector length don't match. 3224 if (SrcNumElts < MaskNumElts) { 3225 // Mask is longer than the source vectors. We can use concatenate vector to 3226 // make the mask and vectors lengths match. 3227 3228 if (MaskNumElts % SrcNumElts == 0) { 3229 // Mask length is a multiple of the source vector length. 3230 // Check if the shuffle is some kind of concatenation of the input 3231 // vectors. 3232 unsigned NumConcat = MaskNumElts / SrcNumElts; 3233 bool IsConcat = true; 3234 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3235 for (unsigned i = 0; i != MaskNumElts; ++i) { 3236 int Idx = Mask[i]; 3237 if (Idx < 0) 3238 continue; 3239 // Ensure the indices in each SrcVT sized piece are sequential and that 3240 // the same source is used for the whole piece. 3241 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3242 (ConcatSrcs[i / SrcNumElts] >= 0 && 3243 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3244 IsConcat = false; 3245 break; 3246 } 3247 // Remember which source this index came from. 3248 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3249 } 3250 3251 // The shuffle is concatenating multiple vectors together. Just emit 3252 // a CONCAT_VECTORS operation. 3253 if (IsConcat) { 3254 SmallVector<SDValue, 8> ConcatOps; 3255 for (auto Src : ConcatSrcs) { 3256 if (Src < 0) 3257 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3258 else if (Src == 0) 3259 ConcatOps.push_back(Src1); 3260 else 3261 ConcatOps.push_back(Src2); 3262 } 3263 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3264 return; 3265 } 3266 } 3267 3268 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3269 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3270 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3271 PaddedMaskNumElts); 3272 3273 // Pad both vectors with undefs to make them the same length as the mask. 3274 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3275 3276 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3277 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3278 MOps1[0] = Src1; 3279 MOps2[0] = Src2; 3280 3281 Src1 = Src1.isUndef() 3282 ? DAG.getUNDEF(PaddedVT) 3283 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3284 Src2 = Src2.isUndef() 3285 ? DAG.getUNDEF(PaddedVT) 3286 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3287 3288 // Readjust mask for new input vector length. 3289 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3290 for (unsigned i = 0; i != MaskNumElts; ++i) { 3291 int Idx = Mask[i]; 3292 if (Idx >= (int)SrcNumElts) 3293 Idx -= SrcNumElts - PaddedMaskNumElts; 3294 MappedOps[i] = Idx; 3295 } 3296 3297 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3298 3299 // If the concatenated vector was padded, extract a subvector with the 3300 // correct number of elements. 3301 if (MaskNumElts != PaddedMaskNumElts) 3302 Result = DAG.getNode( 3303 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3304 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3305 3306 setValue(&I, Result); 3307 return; 3308 } 3309 3310 if (SrcNumElts > MaskNumElts) { 3311 // Analyze the access pattern of the vector to see if we can extract 3312 // two subvectors and do the shuffle. 3313 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3314 bool CanExtract = true; 3315 for (int Idx : Mask) { 3316 unsigned Input = 0; 3317 if (Idx < 0) 3318 continue; 3319 3320 if (Idx >= (int)SrcNumElts) { 3321 Input = 1; 3322 Idx -= SrcNumElts; 3323 } 3324 3325 // If all the indices come from the same MaskNumElts sized portion of 3326 // the sources we can use extract. Also make sure the extract wouldn't 3327 // extract past the end of the source. 3328 int NewStartIdx = alignDown(Idx, MaskNumElts); 3329 if (NewStartIdx + MaskNumElts > SrcNumElts || 3330 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3331 CanExtract = false; 3332 // Make sure we always update StartIdx as we use it to track if all 3333 // elements are undef. 3334 StartIdx[Input] = NewStartIdx; 3335 } 3336 3337 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3338 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3339 return; 3340 } 3341 if (CanExtract) { 3342 // Extract appropriate subvector and generate a vector shuffle 3343 for (unsigned Input = 0; Input < 2; ++Input) { 3344 SDValue &Src = Input == 0 ? Src1 : Src2; 3345 if (StartIdx[Input] < 0) 3346 Src = DAG.getUNDEF(VT); 3347 else { 3348 Src = DAG.getNode( 3349 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3350 DAG.getConstant(StartIdx[Input], DL, 3351 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3352 } 3353 } 3354 3355 // Calculate new mask. 3356 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3357 for (int &Idx : MappedOps) { 3358 if (Idx >= (int)SrcNumElts) 3359 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3360 else if (Idx >= 0) 3361 Idx -= StartIdx[0]; 3362 } 3363 3364 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3365 return; 3366 } 3367 } 3368 3369 // We can't use either concat vectors or extract subvectors so fall back to 3370 // replacing the shuffle with extract and build vector. 3371 // to insert and build vector. 3372 EVT EltVT = VT.getVectorElementType(); 3373 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3374 SmallVector<SDValue,8> Ops; 3375 for (int Idx : Mask) { 3376 SDValue Res; 3377 3378 if (Idx < 0) { 3379 Res = DAG.getUNDEF(EltVT); 3380 } else { 3381 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3382 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3383 3384 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3385 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3386 } 3387 3388 Ops.push_back(Res); 3389 } 3390 3391 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3392 } 3393 3394 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3395 ArrayRef<unsigned> Indices; 3396 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3397 Indices = IV->getIndices(); 3398 else 3399 Indices = cast<ConstantExpr>(&I)->getIndices(); 3400 3401 const Value *Op0 = I.getOperand(0); 3402 const Value *Op1 = I.getOperand(1); 3403 Type *AggTy = I.getType(); 3404 Type *ValTy = Op1->getType(); 3405 bool IntoUndef = isa<UndefValue>(Op0); 3406 bool FromUndef = isa<UndefValue>(Op1); 3407 3408 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3409 3410 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3411 SmallVector<EVT, 4> AggValueVTs; 3412 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3413 SmallVector<EVT, 4> ValValueVTs; 3414 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3415 3416 unsigned NumAggValues = AggValueVTs.size(); 3417 unsigned NumValValues = ValValueVTs.size(); 3418 SmallVector<SDValue, 4> Values(NumAggValues); 3419 3420 // Ignore an insertvalue that produces an empty object 3421 if (!NumAggValues) { 3422 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3423 return; 3424 } 3425 3426 SDValue Agg = getValue(Op0); 3427 unsigned i = 0; 3428 // Copy the beginning value(s) from the original aggregate. 3429 for (; i != LinearIndex; ++i) 3430 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3431 SDValue(Agg.getNode(), Agg.getResNo() + i); 3432 // Copy values from the inserted value(s). 3433 if (NumValValues) { 3434 SDValue Val = getValue(Op1); 3435 for (; i != LinearIndex + NumValValues; ++i) 3436 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3437 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3438 } 3439 // Copy remaining value(s) from the original aggregate. 3440 for (; i != NumAggValues; ++i) 3441 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3442 SDValue(Agg.getNode(), Agg.getResNo() + i); 3443 3444 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3445 DAG.getVTList(AggValueVTs), Values)); 3446 } 3447 3448 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3449 ArrayRef<unsigned> Indices; 3450 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3451 Indices = EV->getIndices(); 3452 else 3453 Indices = cast<ConstantExpr>(&I)->getIndices(); 3454 3455 const Value *Op0 = I.getOperand(0); 3456 Type *AggTy = Op0->getType(); 3457 Type *ValTy = I.getType(); 3458 bool OutOfUndef = isa<UndefValue>(Op0); 3459 3460 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3461 3462 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3463 SmallVector<EVT, 4> ValValueVTs; 3464 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3465 3466 unsigned NumValValues = ValValueVTs.size(); 3467 3468 // Ignore a extractvalue that produces an empty object 3469 if (!NumValValues) { 3470 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3471 return; 3472 } 3473 3474 SmallVector<SDValue, 4> Values(NumValValues); 3475 3476 SDValue Agg = getValue(Op0); 3477 // Copy out the selected value(s). 3478 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3479 Values[i - LinearIndex] = 3480 OutOfUndef ? 3481 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3482 SDValue(Agg.getNode(), Agg.getResNo() + i); 3483 3484 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3485 DAG.getVTList(ValValueVTs), Values)); 3486 } 3487 3488 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3489 Value *Op0 = I.getOperand(0); 3490 // Note that the pointer operand may be a vector of pointers. Take the scalar 3491 // element which holds a pointer. 3492 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3493 SDValue N = getValue(Op0); 3494 SDLoc dl = getCurSDLoc(); 3495 3496 // Normalize Vector GEP - all scalar operands should be converted to the 3497 // splat vector. 3498 unsigned VectorWidth = I.getType()->isVectorTy() ? 3499 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3500 3501 if (VectorWidth && !N.getValueType().isVector()) { 3502 LLVMContext &Context = *DAG.getContext(); 3503 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3504 N = DAG.getSplatBuildVector(VT, dl, N); 3505 } 3506 3507 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3508 GTI != E; ++GTI) { 3509 const Value *Idx = GTI.getOperand(); 3510 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3511 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3512 if (Field) { 3513 // N = N + Offset 3514 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3515 3516 // In an inbounds GEP with an offset that is nonnegative even when 3517 // interpreted as signed, assume there is no unsigned overflow. 3518 SDNodeFlags Flags; 3519 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3520 Flags.setNoUnsignedWrap(true); 3521 3522 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3523 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3524 } 3525 } else { 3526 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3527 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3528 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3529 3530 // If this is a scalar constant or a splat vector of constants, 3531 // handle it quickly. 3532 const auto *CI = dyn_cast<ConstantInt>(Idx); 3533 if (!CI && isa<ConstantDataVector>(Idx) && 3534 cast<ConstantDataVector>(Idx)->getSplatValue()) 3535 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3536 3537 if (CI) { 3538 if (CI->isZero()) 3539 continue; 3540 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3541 LLVMContext &Context = *DAG.getContext(); 3542 SDValue OffsVal = VectorWidth ? 3543 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3544 DAG.getConstant(Offs, dl, IdxTy); 3545 3546 // In an inbouds GEP with an offset that is nonnegative even when 3547 // interpreted as signed, assume there is no unsigned overflow. 3548 SDNodeFlags Flags; 3549 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3550 Flags.setNoUnsignedWrap(true); 3551 3552 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3553 continue; 3554 } 3555 3556 // N = N + Idx * ElementSize; 3557 SDValue IdxN = getValue(Idx); 3558 3559 if (!IdxN.getValueType().isVector() && VectorWidth) { 3560 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3561 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3562 } 3563 3564 // If the index is smaller or larger than intptr_t, truncate or extend 3565 // it. 3566 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3567 3568 // If this is a multiply by a power of two, turn it into a shl 3569 // immediately. This is a very common case. 3570 if (ElementSize != 1) { 3571 if (ElementSize.isPowerOf2()) { 3572 unsigned Amt = ElementSize.logBase2(); 3573 IdxN = DAG.getNode(ISD::SHL, dl, 3574 N.getValueType(), IdxN, 3575 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3576 } else { 3577 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3578 IdxN = DAG.getNode(ISD::MUL, dl, 3579 N.getValueType(), IdxN, Scale); 3580 } 3581 } 3582 3583 N = DAG.getNode(ISD::ADD, dl, 3584 N.getValueType(), N, IdxN); 3585 } 3586 } 3587 3588 setValue(&I, N); 3589 } 3590 3591 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3592 // If this is a fixed sized alloca in the entry block of the function, 3593 // allocate it statically on the stack. 3594 if (FuncInfo.StaticAllocaMap.count(&I)) 3595 return; // getValue will auto-populate this. 3596 3597 SDLoc dl = getCurSDLoc(); 3598 Type *Ty = I.getAllocatedType(); 3599 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3600 auto &DL = DAG.getDataLayout(); 3601 uint64_t TySize = DL.getTypeAllocSize(Ty); 3602 unsigned Align = 3603 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3604 3605 SDValue AllocSize = getValue(I.getArraySize()); 3606 3607 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3608 if (AllocSize.getValueType() != IntPtr) 3609 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3610 3611 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3612 AllocSize, 3613 DAG.getConstant(TySize, dl, IntPtr)); 3614 3615 // Handle alignment. If the requested alignment is less than or equal to 3616 // the stack alignment, ignore it. If the size is greater than or equal to 3617 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3618 unsigned StackAlign = 3619 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3620 if (Align <= StackAlign) 3621 Align = 0; 3622 3623 // Round the size of the allocation up to the stack alignment size 3624 // by add SA-1 to the size. This doesn't overflow because we're computing 3625 // an address inside an alloca. 3626 SDNodeFlags Flags; 3627 Flags.setNoUnsignedWrap(true); 3628 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3629 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3630 3631 // Mask out the low bits for alignment purposes. 3632 AllocSize = 3633 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3634 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3635 3636 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3637 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3638 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3639 setValue(&I, DSA); 3640 DAG.setRoot(DSA.getValue(1)); 3641 3642 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3643 } 3644 3645 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3646 if (I.isAtomic()) 3647 return visitAtomicLoad(I); 3648 3649 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3650 const Value *SV = I.getOperand(0); 3651 if (TLI.supportSwiftError()) { 3652 // Swifterror values can come from either a function parameter with 3653 // swifterror attribute or an alloca with swifterror attribute. 3654 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3655 if (Arg->hasSwiftErrorAttr()) 3656 return visitLoadFromSwiftError(I); 3657 } 3658 3659 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3660 if (Alloca->isSwiftError()) 3661 return visitLoadFromSwiftError(I); 3662 } 3663 } 3664 3665 SDValue Ptr = getValue(SV); 3666 3667 Type *Ty = I.getType(); 3668 3669 bool isVolatile = I.isVolatile(); 3670 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3671 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3672 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3673 unsigned Alignment = I.getAlignment(); 3674 3675 AAMDNodes AAInfo; 3676 I.getAAMetadata(AAInfo); 3677 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3678 3679 SmallVector<EVT, 4> ValueVTs; 3680 SmallVector<uint64_t, 4> Offsets; 3681 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3682 unsigned NumValues = ValueVTs.size(); 3683 if (NumValues == 0) 3684 return; 3685 3686 SDValue Root; 3687 bool ConstantMemory = false; 3688 if (isVolatile || NumValues > MaxParallelChains) 3689 // Serialize volatile loads with other side effects. 3690 Root = getRoot(); 3691 else if (AA && 3692 AA->pointsToConstantMemory(MemoryLocation( 3693 SV, 3694 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3695 AAInfo))) { 3696 // Do not serialize (non-volatile) loads of constant memory with anything. 3697 Root = DAG.getEntryNode(); 3698 ConstantMemory = true; 3699 } else { 3700 // Do not serialize non-volatile loads against each other. 3701 Root = DAG.getRoot(); 3702 } 3703 3704 SDLoc dl = getCurSDLoc(); 3705 3706 if (isVolatile) 3707 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3708 3709 // An aggregate load cannot wrap around the address space, so offsets to its 3710 // parts don't wrap either. 3711 SDNodeFlags Flags; 3712 Flags.setNoUnsignedWrap(true); 3713 3714 SmallVector<SDValue, 4> Values(NumValues); 3715 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3716 EVT PtrVT = Ptr.getValueType(); 3717 unsigned ChainI = 0; 3718 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3719 // Serializing loads here may result in excessive register pressure, and 3720 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3721 // could recover a bit by hoisting nodes upward in the chain by recognizing 3722 // they are side-effect free or do not alias. The optimizer should really 3723 // avoid this case by converting large object/array copies to llvm.memcpy 3724 // (MaxParallelChains should always remain as failsafe). 3725 if (ChainI == MaxParallelChains) { 3726 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3727 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3728 makeArrayRef(Chains.data(), ChainI)); 3729 Root = Chain; 3730 ChainI = 0; 3731 } 3732 SDValue A = DAG.getNode(ISD::ADD, dl, 3733 PtrVT, Ptr, 3734 DAG.getConstant(Offsets[i], dl, PtrVT), 3735 Flags); 3736 auto MMOFlags = MachineMemOperand::MONone; 3737 if (isVolatile) 3738 MMOFlags |= MachineMemOperand::MOVolatile; 3739 if (isNonTemporal) 3740 MMOFlags |= MachineMemOperand::MONonTemporal; 3741 if (isInvariant) 3742 MMOFlags |= MachineMemOperand::MOInvariant; 3743 if (isDereferenceable) 3744 MMOFlags |= MachineMemOperand::MODereferenceable; 3745 MMOFlags |= TLI.getMMOFlags(I); 3746 3747 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3748 MachinePointerInfo(SV, Offsets[i]), Alignment, 3749 MMOFlags, AAInfo, Ranges); 3750 3751 Values[i] = L; 3752 Chains[ChainI] = L.getValue(1); 3753 } 3754 3755 if (!ConstantMemory) { 3756 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3757 makeArrayRef(Chains.data(), ChainI)); 3758 if (isVolatile) 3759 DAG.setRoot(Chain); 3760 else 3761 PendingLoads.push_back(Chain); 3762 } 3763 3764 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3765 DAG.getVTList(ValueVTs), Values)); 3766 } 3767 3768 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3769 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3770 "call visitStoreToSwiftError when backend supports swifterror"); 3771 3772 SmallVector<EVT, 4> ValueVTs; 3773 SmallVector<uint64_t, 4> Offsets; 3774 const Value *SrcV = I.getOperand(0); 3775 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3776 SrcV->getType(), ValueVTs, &Offsets); 3777 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3778 "expect a single EVT for swifterror"); 3779 3780 SDValue Src = getValue(SrcV); 3781 // Create a virtual register, then update the virtual register. 3782 unsigned VReg; bool CreatedVReg; 3783 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 3784 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3785 // Chain can be getRoot or getControlRoot. 3786 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3787 SDValue(Src.getNode(), Src.getResNo())); 3788 DAG.setRoot(CopyNode); 3789 if (CreatedVReg) 3790 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3791 } 3792 3793 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3794 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3795 "call visitLoadFromSwiftError when backend supports swifterror"); 3796 3797 assert(!I.isVolatile() && 3798 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3799 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3800 "Support volatile, non temporal, invariant for load_from_swift_error"); 3801 3802 const Value *SV = I.getOperand(0); 3803 Type *Ty = I.getType(); 3804 AAMDNodes AAInfo; 3805 I.getAAMetadata(AAInfo); 3806 assert( 3807 (!AA || 3808 !AA->pointsToConstantMemory(MemoryLocation( 3809 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3810 AAInfo))) && 3811 "load_from_swift_error should not be constant memory"); 3812 3813 SmallVector<EVT, 4> ValueVTs; 3814 SmallVector<uint64_t, 4> Offsets; 3815 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3816 ValueVTs, &Offsets); 3817 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3818 "expect a single EVT for swifterror"); 3819 3820 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3821 SDValue L = DAG.getCopyFromReg( 3822 getRoot(), getCurSDLoc(), 3823 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 3824 ValueVTs[0]); 3825 3826 setValue(&I, L); 3827 } 3828 3829 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3830 if (I.isAtomic()) 3831 return visitAtomicStore(I); 3832 3833 const Value *SrcV = I.getOperand(0); 3834 const Value *PtrV = I.getOperand(1); 3835 3836 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3837 if (TLI.supportSwiftError()) { 3838 // Swifterror values can come from either a function parameter with 3839 // swifterror attribute or an alloca with swifterror attribute. 3840 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3841 if (Arg->hasSwiftErrorAttr()) 3842 return visitStoreToSwiftError(I); 3843 } 3844 3845 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3846 if (Alloca->isSwiftError()) 3847 return visitStoreToSwiftError(I); 3848 } 3849 } 3850 3851 SmallVector<EVT, 4> ValueVTs; 3852 SmallVector<uint64_t, 4> Offsets; 3853 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3854 SrcV->getType(), ValueVTs, &Offsets); 3855 unsigned NumValues = ValueVTs.size(); 3856 if (NumValues == 0) 3857 return; 3858 3859 // Get the lowered operands. Note that we do this after 3860 // checking if NumResults is zero, because with zero results 3861 // the operands won't have values in the map. 3862 SDValue Src = getValue(SrcV); 3863 SDValue Ptr = getValue(PtrV); 3864 3865 SDValue Root = getRoot(); 3866 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3867 SDLoc dl = getCurSDLoc(); 3868 EVT PtrVT = Ptr.getValueType(); 3869 unsigned Alignment = I.getAlignment(); 3870 AAMDNodes AAInfo; 3871 I.getAAMetadata(AAInfo); 3872 3873 auto MMOFlags = MachineMemOperand::MONone; 3874 if (I.isVolatile()) 3875 MMOFlags |= MachineMemOperand::MOVolatile; 3876 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3877 MMOFlags |= MachineMemOperand::MONonTemporal; 3878 MMOFlags |= TLI.getMMOFlags(I); 3879 3880 // An aggregate load cannot wrap around the address space, so offsets to its 3881 // parts don't wrap either. 3882 SDNodeFlags Flags; 3883 Flags.setNoUnsignedWrap(true); 3884 3885 unsigned ChainI = 0; 3886 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3887 // See visitLoad comments. 3888 if (ChainI == MaxParallelChains) { 3889 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3890 makeArrayRef(Chains.data(), ChainI)); 3891 Root = Chain; 3892 ChainI = 0; 3893 } 3894 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3895 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 3896 SDValue St = DAG.getStore( 3897 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3898 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3899 Chains[ChainI] = St; 3900 } 3901 3902 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3903 makeArrayRef(Chains.data(), ChainI)); 3904 DAG.setRoot(StoreNode); 3905 } 3906 3907 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 3908 bool IsCompressing) { 3909 SDLoc sdl = getCurSDLoc(); 3910 3911 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3912 unsigned& Alignment) { 3913 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3914 Src0 = I.getArgOperand(0); 3915 Ptr = I.getArgOperand(1); 3916 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3917 Mask = I.getArgOperand(3); 3918 }; 3919 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3920 unsigned& Alignment) { 3921 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 3922 Src0 = I.getArgOperand(0); 3923 Ptr = I.getArgOperand(1); 3924 Mask = I.getArgOperand(2); 3925 Alignment = 0; 3926 }; 3927 3928 Value *PtrOperand, *MaskOperand, *Src0Operand; 3929 unsigned Alignment; 3930 if (IsCompressing) 3931 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3932 else 3933 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3934 3935 SDValue Ptr = getValue(PtrOperand); 3936 SDValue Src0 = getValue(Src0Operand); 3937 SDValue Mask = getValue(MaskOperand); 3938 3939 EVT VT = Src0.getValueType(); 3940 if (!Alignment) 3941 Alignment = DAG.getEVTAlignment(VT); 3942 3943 AAMDNodes AAInfo; 3944 I.getAAMetadata(AAInfo); 3945 3946 MachineMemOperand *MMO = 3947 DAG.getMachineFunction(). 3948 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3949 MachineMemOperand::MOStore, VT.getStoreSize(), 3950 Alignment, AAInfo); 3951 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3952 MMO, false /* Truncating */, 3953 IsCompressing); 3954 DAG.setRoot(StoreNode); 3955 setValue(&I, StoreNode); 3956 } 3957 3958 // Get a uniform base for the Gather/Scatter intrinsic. 3959 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 3960 // We try to represent it as a base pointer + vector of indices. 3961 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 3962 // The first operand of the GEP may be a single pointer or a vector of pointers 3963 // Example: 3964 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 3965 // or 3966 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 3967 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 3968 // 3969 // When the first GEP operand is a single pointer - it is the uniform base we 3970 // are looking for. If first operand of the GEP is a splat vector - we 3971 // extract the splat value and use it as a uniform base. 3972 // In all other cases the function returns 'false'. 3973 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 3974 SDValue &Scale, SelectionDAGBuilder* SDB) { 3975 SelectionDAG& DAG = SDB->DAG; 3976 LLVMContext &Context = *DAG.getContext(); 3977 3978 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 3979 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 3980 if (!GEP) 3981 return false; 3982 3983 const Value *GEPPtr = GEP->getPointerOperand(); 3984 if (!GEPPtr->getType()->isVectorTy()) 3985 Ptr = GEPPtr; 3986 else if (!(Ptr = getSplatValue(GEPPtr))) 3987 return false; 3988 3989 unsigned FinalIndex = GEP->getNumOperands() - 1; 3990 Value *IndexVal = GEP->getOperand(FinalIndex); 3991 3992 // Ensure all the other indices are 0. 3993 for (unsigned i = 1; i < FinalIndex; ++i) { 3994 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 3995 if (!C || !C->isZero()) 3996 return false; 3997 } 3998 3999 // The operands of the GEP may be defined in another basic block. 4000 // In this case we'll not find nodes for the operands. 4001 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 4002 return false; 4003 4004 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4005 const DataLayout &DL = DAG.getDataLayout(); 4006 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4007 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4008 Base = SDB->getValue(Ptr); 4009 Index = SDB->getValue(IndexVal); 4010 4011 if (!Index.getValueType().isVector()) { 4012 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4013 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4014 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4015 } 4016 return true; 4017 } 4018 4019 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4020 SDLoc sdl = getCurSDLoc(); 4021 4022 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4023 const Value *Ptr = I.getArgOperand(1); 4024 SDValue Src0 = getValue(I.getArgOperand(0)); 4025 SDValue Mask = getValue(I.getArgOperand(3)); 4026 EVT VT = Src0.getValueType(); 4027 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4028 if (!Alignment) 4029 Alignment = DAG.getEVTAlignment(VT); 4030 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4031 4032 AAMDNodes AAInfo; 4033 I.getAAMetadata(AAInfo); 4034 4035 SDValue Base; 4036 SDValue Index; 4037 SDValue Scale; 4038 const Value *BasePtr = Ptr; 4039 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4040 4041 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4042 MachineMemOperand *MMO = DAG.getMachineFunction(). 4043 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4044 MachineMemOperand::MOStore, VT.getStoreSize(), 4045 Alignment, AAInfo); 4046 if (!UniformBase) { 4047 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4048 Index = getValue(Ptr); 4049 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4050 } 4051 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4052 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4053 Ops, MMO); 4054 DAG.setRoot(Scatter); 4055 setValue(&I, Scatter); 4056 } 4057 4058 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4059 SDLoc sdl = getCurSDLoc(); 4060 4061 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4062 unsigned& Alignment) { 4063 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4064 Ptr = I.getArgOperand(0); 4065 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4066 Mask = I.getArgOperand(2); 4067 Src0 = I.getArgOperand(3); 4068 }; 4069 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4070 unsigned& Alignment) { 4071 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4072 Ptr = I.getArgOperand(0); 4073 Alignment = 0; 4074 Mask = I.getArgOperand(1); 4075 Src0 = I.getArgOperand(2); 4076 }; 4077 4078 Value *PtrOperand, *MaskOperand, *Src0Operand; 4079 unsigned Alignment; 4080 if (IsExpanding) 4081 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4082 else 4083 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4084 4085 SDValue Ptr = getValue(PtrOperand); 4086 SDValue Src0 = getValue(Src0Operand); 4087 SDValue Mask = getValue(MaskOperand); 4088 4089 EVT VT = Src0.getValueType(); 4090 if (!Alignment) 4091 Alignment = DAG.getEVTAlignment(VT); 4092 4093 AAMDNodes AAInfo; 4094 I.getAAMetadata(AAInfo); 4095 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4096 4097 // Do not serialize masked loads of constant memory with anything. 4098 bool AddToChain = 4099 !AA || !AA->pointsToConstantMemory(MemoryLocation( 4100 PtrOperand, 4101 LocationSize::precise( 4102 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4103 AAInfo)); 4104 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4105 4106 MachineMemOperand *MMO = 4107 DAG.getMachineFunction(). 4108 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4109 MachineMemOperand::MOLoad, VT.getStoreSize(), 4110 Alignment, AAInfo, Ranges); 4111 4112 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4113 ISD::NON_EXTLOAD, IsExpanding); 4114 if (AddToChain) 4115 PendingLoads.push_back(Load.getValue(1)); 4116 setValue(&I, Load); 4117 } 4118 4119 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4120 SDLoc sdl = getCurSDLoc(); 4121 4122 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4123 const Value *Ptr = I.getArgOperand(0); 4124 SDValue Src0 = getValue(I.getArgOperand(3)); 4125 SDValue Mask = getValue(I.getArgOperand(2)); 4126 4127 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4128 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4129 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4130 if (!Alignment) 4131 Alignment = DAG.getEVTAlignment(VT); 4132 4133 AAMDNodes AAInfo; 4134 I.getAAMetadata(AAInfo); 4135 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4136 4137 SDValue Root = DAG.getRoot(); 4138 SDValue Base; 4139 SDValue Index; 4140 SDValue Scale; 4141 const Value *BasePtr = Ptr; 4142 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4143 bool ConstantMemory = false; 4144 if (UniformBase && AA && 4145 AA->pointsToConstantMemory( 4146 MemoryLocation(BasePtr, 4147 LocationSize::precise( 4148 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4149 AAInfo))) { 4150 // Do not serialize (non-volatile) loads of constant memory with anything. 4151 Root = DAG.getEntryNode(); 4152 ConstantMemory = true; 4153 } 4154 4155 MachineMemOperand *MMO = 4156 DAG.getMachineFunction(). 4157 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4158 MachineMemOperand::MOLoad, VT.getStoreSize(), 4159 Alignment, AAInfo, Ranges); 4160 4161 if (!UniformBase) { 4162 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4163 Index = getValue(Ptr); 4164 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4165 } 4166 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4167 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4168 Ops, MMO); 4169 4170 SDValue OutChain = Gather.getValue(1); 4171 if (!ConstantMemory) 4172 PendingLoads.push_back(OutChain); 4173 setValue(&I, Gather); 4174 } 4175 4176 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4177 SDLoc dl = getCurSDLoc(); 4178 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 4179 AtomicOrdering FailureOrder = I.getFailureOrdering(); 4180 SyncScope::ID SSID = I.getSyncScopeID(); 4181 4182 SDValue InChain = getRoot(); 4183 4184 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4185 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4186 SDValue L = DAG.getAtomicCmpSwap( 4187 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 4188 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 4189 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 4190 /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID); 4191 4192 SDValue OutChain = L.getValue(2); 4193 4194 setValue(&I, L); 4195 DAG.setRoot(OutChain); 4196 } 4197 4198 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4199 SDLoc dl = getCurSDLoc(); 4200 ISD::NodeType NT; 4201 switch (I.getOperation()) { 4202 default: llvm_unreachable("Unknown atomicrmw operation"); 4203 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4204 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4205 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4206 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4207 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4208 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4209 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4210 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4211 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4212 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4213 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4214 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4215 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4216 } 4217 AtomicOrdering Order = I.getOrdering(); 4218 SyncScope::ID SSID = I.getSyncScopeID(); 4219 4220 SDValue InChain = getRoot(); 4221 4222 SDValue L = 4223 DAG.getAtomic(NT, dl, 4224 getValue(I.getValOperand()).getSimpleValueType(), 4225 InChain, 4226 getValue(I.getPointerOperand()), 4227 getValue(I.getValOperand()), 4228 I.getPointerOperand(), 4229 /* Alignment=*/ 0, Order, SSID); 4230 4231 SDValue OutChain = L.getValue(1); 4232 4233 setValue(&I, L); 4234 DAG.setRoot(OutChain); 4235 } 4236 4237 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4238 SDLoc dl = getCurSDLoc(); 4239 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4240 SDValue Ops[3]; 4241 Ops[0] = getRoot(); 4242 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4243 TLI.getFenceOperandTy(DAG.getDataLayout())); 4244 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4245 TLI.getFenceOperandTy(DAG.getDataLayout())); 4246 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4247 } 4248 4249 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4250 SDLoc dl = getCurSDLoc(); 4251 AtomicOrdering Order = I.getOrdering(); 4252 SyncScope::ID SSID = I.getSyncScopeID(); 4253 4254 SDValue InChain = getRoot(); 4255 4256 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4257 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4258 4259 if (!TLI.supportsUnalignedAtomics() && 4260 I.getAlignment() < VT.getStoreSize()) 4261 report_fatal_error("Cannot generate unaligned atomic load"); 4262 4263 MachineMemOperand *MMO = 4264 DAG.getMachineFunction(). 4265 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4266 MachineMemOperand::MOVolatile | 4267 MachineMemOperand::MOLoad, 4268 VT.getStoreSize(), 4269 I.getAlignment() ? I.getAlignment() : 4270 DAG.getEVTAlignment(VT), 4271 AAMDNodes(), nullptr, SSID, Order); 4272 4273 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4274 SDValue L = 4275 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4276 getValue(I.getPointerOperand()), MMO); 4277 4278 SDValue OutChain = L.getValue(1); 4279 4280 setValue(&I, L); 4281 DAG.setRoot(OutChain); 4282 } 4283 4284 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4285 SDLoc dl = getCurSDLoc(); 4286 4287 AtomicOrdering Order = I.getOrdering(); 4288 SyncScope::ID SSID = I.getSyncScopeID(); 4289 4290 SDValue InChain = getRoot(); 4291 4292 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4293 EVT VT = 4294 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4295 4296 if (I.getAlignment() < VT.getStoreSize()) 4297 report_fatal_error("Cannot generate unaligned atomic store"); 4298 4299 SDValue OutChain = 4300 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4301 InChain, 4302 getValue(I.getPointerOperand()), 4303 getValue(I.getValueOperand()), 4304 I.getPointerOperand(), I.getAlignment(), 4305 Order, SSID); 4306 4307 DAG.setRoot(OutChain); 4308 } 4309 4310 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4311 /// node. 4312 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4313 unsigned Intrinsic) { 4314 // Ignore the callsite's attributes. A specific call site may be marked with 4315 // readnone, but the lowering code will expect the chain based on the 4316 // definition. 4317 const Function *F = I.getCalledFunction(); 4318 bool HasChain = !F->doesNotAccessMemory(); 4319 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4320 4321 // Build the operand list. 4322 SmallVector<SDValue, 8> Ops; 4323 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4324 if (OnlyLoad) { 4325 // We don't need to serialize loads against other loads. 4326 Ops.push_back(DAG.getRoot()); 4327 } else { 4328 Ops.push_back(getRoot()); 4329 } 4330 } 4331 4332 // Info is set by getTgtMemInstrinsic 4333 TargetLowering::IntrinsicInfo Info; 4334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4335 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4336 DAG.getMachineFunction(), 4337 Intrinsic); 4338 4339 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4340 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4341 Info.opc == ISD::INTRINSIC_W_CHAIN) 4342 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4343 TLI.getPointerTy(DAG.getDataLayout()))); 4344 4345 // Add all operands of the call to the operand list. 4346 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4347 SDValue Op = getValue(I.getArgOperand(i)); 4348 Ops.push_back(Op); 4349 } 4350 4351 SmallVector<EVT, 4> ValueVTs; 4352 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4353 4354 if (HasChain) 4355 ValueVTs.push_back(MVT::Other); 4356 4357 SDVTList VTs = DAG.getVTList(ValueVTs); 4358 4359 // Create the node. 4360 SDValue Result; 4361 if (IsTgtIntrinsic) { 4362 // This is target intrinsic that touches memory 4363 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4364 Ops, Info.memVT, 4365 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4366 Info.flags, Info.size); 4367 } else if (!HasChain) { 4368 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4369 } else if (!I.getType()->isVoidTy()) { 4370 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4371 } else { 4372 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4373 } 4374 4375 if (HasChain) { 4376 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4377 if (OnlyLoad) 4378 PendingLoads.push_back(Chain); 4379 else 4380 DAG.setRoot(Chain); 4381 } 4382 4383 if (!I.getType()->isVoidTy()) { 4384 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4385 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4386 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4387 } else 4388 Result = lowerRangeToAssertZExt(DAG, I, Result); 4389 4390 setValue(&I, Result); 4391 } 4392 } 4393 4394 /// GetSignificand - Get the significand and build it into a floating-point 4395 /// number with exponent of 1: 4396 /// 4397 /// Op = (Op & 0x007fffff) | 0x3f800000; 4398 /// 4399 /// where Op is the hexadecimal representation of floating point value. 4400 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4401 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4402 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4403 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4404 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4405 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4406 } 4407 4408 /// GetExponent - Get the exponent: 4409 /// 4410 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4411 /// 4412 /// where Op is the hexadecimal representation of floating point value. 4413 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4414 const TargetLowering &TLI, const SDLoc &dl) { 4415 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4416 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4417 SDValue t1 = DAG.getNode( 4418 ISD::SRL, dl, MVT::i32, t0, 4419 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4420 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4421 DAG.getConstant(127, dl, MVT::i32)); 4422 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4423 } 4424 4425 /// getF32Constant - Get 32-bit floating point constant. 4426 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4427 const SDLoc &dl) { 4428 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4429 MVT::f32); 4430 } 4431 4432 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4433 SelectionDAG &DAG) { 4434 // TODO: What fast-math-flags should be set on the floating-point nodes? 4435 4436 // IntegerPartOfX = ((int32_t)(t0); 4437 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4438 4439 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4440 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4441 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4442 4443 // IntegerPartOfX <<= 23; 4444 IntegerPartOfX = DAG.getNode( 4445 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4446 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4447 DAG.getDataLayout()))); 4448 4449 SDValue TwoToFractionalPartOfX; 4450 if (LimitFloatPrecision <= 6) { 4451 // For floating-point precision of 6: 4452 // 4453 // TwoToFractionalPartOfX = 4454 // 0.997535578f + 4455 // (0.735607626f + 0.252464424f * x) * x; 4456 // 4457 // error 0.0144103317, which is 6 bits 4458 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4459 getF32Constant(DAG, 0x3e814304, dl)); 4460 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4461 getF32Constant(DAG, 0x3f3c50c8, dl)); 4462 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4463 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4464 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4465 } else if (LimitFloatPrecision <= 12) { 4466 // For floating-point precision of 12: 4467 // 4468 // TwoToFractionalPartOfX = 4469 // 0.999892986f + 4470 // (0.696457318f + 4471 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4472 // 4473 // error 0.000107046256, which is 13 to 14 bits 4474 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4475 getF32Constant(DAG, 0x3da235e3, dl)); 4476 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4477 getF32Constant(DAG, 0x3e65b8f3, dl)); 4478 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4479 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4480 getF32Constant(DAG, 0x3f324b07, dl)); 4481 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4482 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4483 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4484 } else { // LimitFloatPrecision <= 18 4485 // For floating-point precision of 18: 4486 // 4487 // TwoToFractionalPartOfX = 4488 // 0.999999982f + 4489 // (0.693148872f + 4490 // (0.240227044f + 4491 // (0.554906021e-1f + 4492 // (0.961591928e-2f + 4493 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4494 // error 2.47208000*10^(-7), which is better than 18 bits 4495 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4496 getF32Constant(DAG, 0x3924b03e, dl)); 4497 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4498 getF32Constant(DAG, 0x3ab24b87, dl)); 4499 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4500 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4501 getF32Constant(DAG, 0x3c1d8c17, dl)); 4502 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4503 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4504 getF32Constant(DAG, 0x3d634a1d, dl)); 4505 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4506 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4507 getF32Constant(DAG, 0x3e75fe14, dl)); 4508 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4509 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4510 getF32Constant(DAG, 0x3f317234, dl)); 4511 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4512 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4513 getF32Constant(DAG, 0x3f800000, dl)); 4514 } 4515 4516 // Add the exponent into the result in integer domain. 4517 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4518 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4519 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4520 } 4521 4522 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4523 /// limited-precision mode. 4524 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4525 const TargetLowering &TLI) { 4526 if (Op.getValueType() == MVT::f32 && 4527 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4528 4529 // Put the exponent in the right bit position for later addition to the 4530 // final result: 4531 // 4532 // #define LOG2OFe 1.4426950f 4533 // t0 = Op * LOG2OFe 4534 4535 // TODO: What fast-math-flags should be set here? 4536 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4537 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4538 return getLimitedPrecisionExp2(t0, dl, DAG); 4539 } 4540 4541 // No special expansion. 4542 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4543 } 4544 4545 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4546 /// limited-precision mode. 4547 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4548 const TargetLowering &TLI) { 4549 // TODO: What fast-math-flags should be set on the floating-point nodes? 4550 4551 if (Op.getValueType() == MVT::f32 && 4552 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4553 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4554 4555 // Scale the exponent by log(2) [0.69314718f]. 4556 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4557 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4558 getF32Constant(DAG, 0x3f317218, dl)); 4559 4560 // Get the significand and build it into a floating-point number with 4561 // exponent of 1. 4562 SDValue X = GetSignificand(DAG, Op1, dl); 4563 4564 SDValue LogOfMantissa; 4565 if (LimitFloatPrecision <= 6) { 4566 // For floating-point precision of 6: 4567 // 4568 // LogofMantissa = 4569 // -1.1609546f + 4570 // (1.4034025f - 0.23903021f * x) * x; 4571 // 4572 // error 0.0034276066, which is better than 8 bits 4573 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4574 getF32Constant(DAG, 0xbe74c456, dl)); 4575 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4576 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4577 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4578 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4579 getF32Constant(DAG, 0x3f949a29, dl)); 4580 } else if (LimitFloatPrecision <= 12) { 4581 // For floating-point precision of 12: 4582 // 4583 // LogOfMantissa = 4584 // -1.7417939f + 4585 // (2.8212026f + 4586 // (-1.4699568f + 4587 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4588 // 4589 // error 0.000061011436, which is 14 bits 4590 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4591 getF32Constant(DAG, 0xbd67b6d6, dl)); 4592 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4593 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4594 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4595 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4596 getF32Constant(DAG, 0x3fbc278b, dl)); 4597 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4598 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4599 getF32Constant(DAG, 0x40348e95, dl)); 4600 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4601 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4602 getF32Constant(DAG, 0x3fdef31a, dl)); 4603 } else { // LimitFloatPrecision <= 18 4604 // For floating-point precision of 18: 4605 // 4606 // LogOfMantissa = 4607 // -2.1072184f + 4608 // (4.2372794f + 4609 // (-3.7029485f + 4610 // (2.2781945f + 4611 // (-0.87823314f + 4612 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4613 // 4614 // error 0.0000023660568, which is better than 18 bits 4615 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4616 getF32Constant(DAG, 0xbc91e5ac, dl)); 4617 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4618 getF32Constant(DAG, 0x3e4350aa, dl)); 4619 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4620 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4621 getF32Constant(DAG, 0x3f60d3e3, dl)); 4622 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4623 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4624 getF32Constant(DAG, 0x4011cdf0, dl)); 4625 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4626 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4627 getF32Constant(DAG, 0x406cfd1c, dl)); 4628 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4629 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4630 getF32Constant(DAG, 0x408797cb, dl)); 4631 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4632 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4633 getF32Constant(DAG, 0x4006dcab, dl)); 4634 } 4635 4636 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4637 } 4638 4639 // No special expansion. 4640 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4641 } 4642 4643 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4644 /// limited-precision mode. 4645 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4646 const TargetLowering &TLI) { 4647 // TODO: What fast-math-flags should be set on the floating-point nodes? 4648 4649 if (Op.getValueType() == MVT::f32 && 4650 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4651 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4652 4653 // Get the exponent. 4654 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4655 4656 // Get the significand and build it into a floating-point number with 4657 // exponent of 1. 4658 SDValue X = GetSignificand(DAG, Op1, dl); 4659 4660 // Different possible minimax approximations of significand in 4661 // floating-point for various degrees of accuracy over [1,2]. 4662 SDValue Log2ofMantissa; 4663 if (LimitFloatPrecision <= 6) { 4664 // For floating-point precision of 6: 4665 // 4666 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4667 // 4668 // error 0.0049451742, which is more than 7 bits 4669 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4670 getF32Constant(DAG, 0xbeb08fe0, dl)); 4671 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4672 getF32Constant(DAG, 0x40019463, dl)); 4673 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4674 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4675 getF32Constant(DAG, 0x3fd6633d, dl)); 4676 } else if (LimitFloatPrecision <= 12) { 4677 // For floating-point precision of 12: 4678 // 4679 // Log2ofMantissa = 4680 // -2.51285454f + 4681 // (4.07009056f + 4682 // (-2.12067489f + 4683 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4684 // 4685 // error 0.0000876136000, which is better than 13 bits 4686 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4687 getF32Constant(DAG, 0xbda7262e, dl)); 4688 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4689 getF32Constant(DAG, 0x3f25280b, dl)); 4690 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4691 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4692 getF32Constant(DAG, 0x4007b923, dl)); 4693 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4694 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4695 getF32Constant(DAG, 0x40823e2f, dl)); 4696 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4697 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4698 getF32Constant(DAG, 0x4020d29c, dl)); 4699 } else { // LimitFloatPrecision <= 18 4700 // For floating-point precision of 18: 4701 // 4702 // Log2ofMantissa = 4703 // -3.0400495f + 4704 // (6.1129976f + 4705 // (-5.3420409f + 4706 // (3.2865683f + 4707 // (-1.2669343f + 4708 // (0.27515199f - 4709 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4710 // 4711 // error 0.0000018516, which is better than 18 bits 4712 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4713 getF32Constant(DAG, 0xbcd2769e, dl)); 4714 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4715 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4716 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4717 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4718 getF32Constant(DAG, 0x3fa22ae7, dl)); 4719 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4720 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4721 getF32Constant(DAG, 0x40525723, dl)); 4722 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4723 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4724 getF32Constant(DAG, 0x40aaf200, dl)); 4725 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4726 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4727 getF32Constant(DAG, 0x40c39dad, dl)); 4728 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4729 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4730 getF32Constant(DAG, 0x4042902c, dl)); 4731 } 4732 4733 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4734 } 4735 4736 // No special expansion. 4737 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4738 } 4739 4740 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4741 /// limited-precision mode. 4742 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4743 const TargetLowering &TLI) { 4744 // TODO: What fast-math-flags should be set on the floating-point nodes? 4745 4746 if (Op.getValueType() == MVT::f32 && 4747 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4748 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4749 4750 // Scale the exponent by log10(2) [0.30102999f]. 4751 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4752 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4753 getF32Constant(DAG, 0x3e9a209a, dl)); 4754 4755 // Get the significand and build it into a floating-point number with 4756 // exponent of 1. 4757 SDValue X = GetSignificand(DAG, Op1, dl); 4758 4759 SDValue Log10ofMantissa; 4760 if (LimitFloatPrecision <= 6) { 4761 // For floating-point precision of 6: 4762 // 4763 // Log10ofMantissa = 4764 // -0.50419619f + 4765 // (0.60948995f - 0.10380950f * x) * x; 4766 // 4767 // error 0.0014886165, which is 6 bits 4768 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4769 getF32Constant(DAG, 0xbdd49a13, dl)); 4770 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4771 getF32Constant(DAG, 0x3f1c0789, dl)); 4772 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4773 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4774 getF32Constant(DAG, 0x3f011300, dl)); 4775 } else if (LimitFloatPrecision <= 12) { 4776 // For floating-point precision of 12: 4777 // 4778 // Log10ofMantissa = 4779 // -0.64831180f + 4780 // (0.91751397f + 4781 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4782 // 4783 // error 0.00019228036, which is better than 12 bits 4784 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4785 getF32Constant(DAG, 0x3d431f31, dl)); 4786 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4787 getF32Constant(DAG, 0x3ea21fb2, dl)); 4788 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4789 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4790 getF32Constant(DAG, 0x3f6ae232, dl)); 4791 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4792 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4793 getF32Constant(DAG, 0x3f25f7c3, dl)); 4794 } else { // LimitFloatPrecision <= 18 4795 // For floating-point precision of 18: 4796 // 4797 // Log10ofMantissa = 4798 // -0.84299375f + 4799 // (1.5327582f + 4800 // (-1.0688956f + 4801 // (0.49102474f + 4802 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4803 // 4804 // error 0.0000037995730, which is better than 18 bits 4805 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4806 getF32Constant(DAG, 0x3c5d51ce, dl)); 4807 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4808 getF32Constant(DAG, 0x3e00685a, dl)); 4809 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4810 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4811 getF32Constant(DAG, 0x3efb6798, dl)); 4812 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4813 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4814 getF32Constant(DAG, 0x3f88d192, dl)); 4815 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4816 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4817 getF32Constant(DAG, 0x3fc4316c, dl)); 4818 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4819 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4820 getF32Constant(DAG, 0x3f57ce70, dl)); 4821 } 4822 4823 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4824 } 4825 4826 // No special expansion. 4827 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4828 } 4829 4830 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4831 /// limited-precision mode. 4832 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4833 const TargetLowering &TLI) { 4834 if (Op.getValueType() == MVT::f32 && 4835 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4836 return getLimitedPrecisionExp2(Op, dl, DAG); 4837 4838 // No special expansion. 4839 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4840 } 4841 4842 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4843 /// limited-precision mode with x == 10.0f. 4844 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4845 SelectionDAG &DAG, const TargetLowering &TLI) { 4846 bool IsExp10 = false; 4847 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4848 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4849 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4850 APFloat Ten(10.0f); 4851 IsExp10 = LHSC->isExactlyValue(Ten); 4852 } 4853 } 4854 4855 // TODO: What fast-math-flags should be set on the FMUL node? 4856 if (IsExp10) { 4857 // Put the exponent in the right bit position for later addition to the 4858 // final result: 4859 // 4860 // #define LOG2OF10 3.3219281f 4861 // t0 = Op * LOG2OF10; 4862 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4863 getF32Constant(DAG, 0x40549a78, dl)); 4864 return getLimitedPrecisionExp2(t0, dl, DAG); 4865 } 4866 4867 // No special expansion. 4868 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4869 } 4870 4871 /// ExpandPowI - Expand a llvm.powi intrinsic. 4872 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4873 SelectionDAG &DAG) { 4874 // If RHS is a constant, we can expand this out to a multiplication tree, 4875 // otherwise we end up lowering to a call to __powidf2 (for example). When 4876 // optimizing for size, we only want to do this if the expansion would produce 4877 // a small number of multiplies, otherwise we do the full expansion. 4878 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4879 // Get the exponent as a positive value. 4880 unsigned Val = RHSC->getSExtValue(); 4881 if ((int)Val < 0) Val = -Val; 4882 4883 // powi(x, 0) -> 1.0 4884 if (Val == 0) 4885 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4886 4887 const Function &F = DAG.getMachineFunction().getFunction(); 4888 if (!F.optForSize() || 4889 // If optimizing for size, don't insert too many multiplies. 4890 // This inserts up to 5 multiplies. 4891 countPopulation(Val) + Log2_32(Val) < 7) { 4892 // We use the simple binary decomposition method to generate the multiply 4893 // sequence. There are more optimal ways to do this (for example, 4894 // powi(x,15) generates one more multiply than it should), but this has 4895 // the benefit of being both really simple and much better than a libcall. 4896 SDValue Res; // Logically starts equal to 1.0 4897 SDValue CurSquare = LHS; 4898 // TODO: Intrinsics should have fast-math-flags that propagate to these 4899 // nodes. 4900 while (Val) { 4901 if (Val & 1) { 4902 if (Res.getNode()) 4903 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4904 else 4905 Res = CurSquare; // 1.0*CurSquare. 4906 } 4907 4908 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4909 CurSquare, CurSquare); 4910 Val >>= 1; 4911 } 4912 4913 // If the original was negative, invert the result, producing 1/(x*x*x). 4914 if (RHSC->getSExtValue() < 0) 4915 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4916 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4917 return Res; 4918 } 4919 } 4920 4921 // Otherwise, expand to a libcall. 4922 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4923 } 4924 4925 // getUnderlyingArgReg - Find underlying register used for a truncated or 4926 // bitcasted argument. 4927 static unsigned getUnderlyingArgReg(const SDValue &N) { 4928 switch (N.getOpcode()) { 4929 case ISD::CopyFromReg: 4930 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4931 case ISD::BITCAST: 4932 case ISD::AssertZext: 4933 case ISD::AssertSext: 4934 case ISD::TRUNCATE: 4935 return getUnderlyingArgReg(N.getOperand(0)); 4936 default: 4937 return 0; 4938 } 4939 } 4940 4941 /// If the DbgValueInst is a dbg_value of a function argument, create the 4942 /// corresponding DBG_VALUE machine instruction for it now. At the end of 4943 /// instruction selection, they will be inserted to the entry BB. 4944 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4945 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4946 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 4947 const Argument *Arg = dyn_cast<Argument>(V); 4948 if (!Arg) 4949 return false; 4950 4951 MachineFunction &MF = DAG.getMachineFunction(); 4952 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4953 4954 bool IsIndirect = false; 4955 Optional<MachineOperand> Op; 4956 // Some arguments' frame index is recorded during argument lowering. 4957 int FI = FuncInfo.getArgumentFrameIndex(Arg); 4958 if (FI != std::numeric_limits<int>::max()) 4959 Op = MachineOperand::CreateFI(FI); 4960 4961 if (!Op && N.getNode()) { 4962 unsigned Reg = getUnderlyingArgReg(N); 4963 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4964 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4965 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4966 if (PR) 4967 Reg = PR; 4968 } 4969 if (Reg) { 4970 Op = MachineOperand::CreateReg(Reg, false); 4971 IsIndirect = IsDbgDeclare; 4972 } 4973 } 4974 4975 if (!Op && N.getNode()) 4976 // Check if frame index is available. 4977 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4978 if (FrameIndexSDNode *FINode = 4979 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4980 Op = MachineOperand::CreateFI(FINode->getIndex()); 4981 4982 if (!Op) { 4983 // Check if ValueMap has reg number. 4984 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4985 if (VMI != FuncInfo.ValueMap.end()) { 4986 const auto &TLI = DAG.getTargetLoweringInfo(); 4987 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 4988 V->getType(), getABIRegCopyCC(V)); 4989 if (RFV.occupiesMultipleRegs()) { 4990 unsigned Offset = 0; 4991 for (auto RegAndSize : RFV.getRegsAndSizes()) { 4992 Op = MachineOperand::CreateReg(RegAndSize.first, false); 4993 auto FragmentExpr = DIExpression::createFragmentExpression( 4994 Expr, Offset, RegAndSize.second); 4995 if (!FragmentExpr) 4996 continue; 4997 FuncInfo.ArgDbgValues.push_back( 4998 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 4999 Op->getReg(), Variable, *FragmentExpr)); 5000 Offset += RegAndSize.second; 5001 } 5002 return true; 5003 } 5004 Op = MachineOperand::CreateReg(VMI->second, false); 5005 IsIndirect = IsDbgDeclare; 5006 } 5007 } 5008 5009 if (!Op) 5010 return false; 5011 5012 assert(Variable->isValidLocationForIntrinsic(DL) && 5013 "Expected inlined-at fields to agree"); 5014 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5015 FuncInfo.ArgDbgValues.push_back( 5016 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5017 *Op, Variable, Expr)); 5018 5019 return true; 5020 } 5021 5022 /// Return the appropriate SDDbgValue based on N. 5023 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5024 DILocalVariable *Variable, 5025 DIExpression *Expr, 5026 const DebugLoc &dl, 5027 unsigned DbgSDNodeOrder) { 5028 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5029 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5030 // stack slot locations. 5031 // 5032 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5033 // debug values here after optimization: 5034 // 5035 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5036 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5037 // 5038 // Both describe the direct values of their associated variables. 5039 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5040 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5041 } 5042 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5043 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5044 } 5045 5046 // VisualStudio defines setjmp as _setjmp 5047 #if defined(_MSC_VER) && defined(setjmp) && \ 5048 !defined(setjmp_undefined_for_msvc) 5049 # pragma push_macro("setjmp") 5050 # undef setjmp 5051 # define setjmp_undefined_for_msvc 5052 #endif 5053 5054 /// Lower the call to the specified intrinsic function. If we want to emit this 5055 /// as a call to a named external function, return the name. Otherwise, lower it 5056 /// and return null. 5057 const char * 5058 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5059 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5060 SDLoc sdl = getCurSDLoc(); 5061 DebugLoc dl = getCurDebugLoc(); 5062 SDValue Res; 5063 5064 switch (Intrinsic) { 5065 default: 5066 // By default, turn this into a target intrinsic node. 5067 visitTargetIntrinsic(I, Intrinsic); 5068 return nullptr; 5069 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5070 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5071 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5072 case Intrinsic::returnaddress: 5073 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5074 TLI.getPointerTy(DAG.getDataLayout()), 5075 getValue(I.getArgOperand(0)))); 5076 return nullptr; 5077 case Intrinsic::addressofreturnaddress: 5078 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5079 TLI.getPointerTy(DAG.getDataLayout()))); 5080 return nullptr; 5081 case Intrinsic::sponentry: 5082 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5083 TLI.getPointerTy(DAG.getDataLayout()))); 5084 return nullptr; 5085 case Intrinsic::frameaddress: 5086 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5087 TLI.getPointerTy(DAG.getDataLayout()), 5088 getValue(I.getArgOperand(0)))); 5089 return nullptr; 5090 case Intrinsic::read_register: { 5091 Value *Reg = I.getArgOperand(0); 5092 SDValue Chain = getRoot(); 5093 SDValue RegName = 5094 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5095 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5096 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5097 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5098 setValue(&I, Res); 5099 DAG.setRoot(Res.getValue(1)); 5100 return nullptr; 5101 } 5102 case Intrinsic::write_register: { 5103 Value *Reg = I.getArgOperand(0); 5104 Value *RegValue = I.getArgOperand(1); 5105 SDValue Chain = getRoot(); 5106 SDValue RegName = 5107 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5108 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5109 RegName, getValue(RegValue))); 5110 return nullptr; 5111 } 5112 case Intrinsic::setjmp: 5113 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5114 case Intrinsic::longjmp: 5115 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5116 case Intrinsic::memcpy: { 5117 const auto &MCI = cast<MemCpyInst>(I); 5118 SDValue Op1 = getValue(I.getArgOperand(0)); 5119 SDValue Op2 = getValue(I.getArgOperand(1)); 5120 SDValue Op3 = getValue(I.getArgOperand(2)); 5121 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5122 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5123 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5124 unsigned Align = MinAlign(DstAlign, SrcAlign); 5125 bool isVol = MCI.isVolatile(); 5126 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5127 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5128 // node. 5129 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5130 false, isTC, 5131 MachinePointerInfo(I.getArgOperand(0)), 5132 MachinePointerInfo(I.getArgOperand(1))); 5133 updateDAGForMaybeTailCall(MC); 5134 return nullptr; 5135 } 5136 case Intrinsic::memset: { 5137 const auto &MSI = cast<MemSetInst>(I); 5138 SDValue Op1 = getValue(I.getArgOperand(0)); 5139 SDValue Op2 = getValue(I.getArgOperand(1)); 5140 SDValue Op3 = getValue(I.getArgOperand(2)); 5141 // @llvm.memset defines 0 and 1 to both mean no alignment. 5142 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5143 bool isVol = MSI.isVolatile(); 5144 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5145 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5146 isTC, MachinePointerInfo(I.getArgOperand(0))); 5147 updateDAGForMaybeTailCall(MS); 5148 return nullptr; 5149 } 5150 case Intrinsic::memmove: { 5151 const auto &MMI = cast<MemMoveInst>(I); 5152 SDValue Op1 = getValue(I.getArgOperand(0)); 5153 SDValue Op2 = getValue(I.getArgOperand(1)); 5154 SDValue Op3 = getValue(I.getArgOperand(2)); 5155 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5156 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5157 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5158 unsigned Align = MinAlign(DstAlign, SrcAlign); 5159 bool isVol = MMI.isVolatile(); 5160 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5161 // FIXME: Support passing different dest/src alignments to the memmove DAG 5162 // node. 5163 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5164 isTC, MachinePointerInfo(I.getArgOperand(0)), 5165 MachinePointerInfo(I.getArgOperand(1))); 5166 updateDAGForMaybeTailCall(MM); 5167 return nullptr; 5168 } 5169 case Intrinsic::memcpy_element_unordered_atomic: { 5170 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5171 SDValue Dst = getValue(MI.getRawDest()); 5172 SDValue Src = getValue(MI.getRawSource()); 5173 SDValue Length = getValue(MI.getLength()); 5174 5175 unsigned DstAlign = MI.getDestAlignment(); 5176 unsigned SrcAlign = MI.getSourceAlignment(); 5177 Type *LengthTy = MI.getLength()->getType(); 5178 unsigned ElemSz = MI.getElementSizeInBytes(); 5179 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5180 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5181 SrcAlign, Length, LengthTy, ElemSz, isTC, 5182 MachinePointerInfo(MI.getRawDest()), 5183 MachinePointerInfo(MI.getRawSource())); 5184 updateDAGForMaybeTailCall(MC); 5185 return nullptr; 5186 } 5187 case Intrinsic::memmove_element_unordered_atomic: { 5188 auto &MI = cast<AtomicMemMoveInst>(I); 5189 SDValue Dst = getValue(MI.getRawDest()); 5190 SDValue Src = getValue(MI.getRawSource()); 5191 SDValue Length = getValue(MI.getLength()); 5192 5193 unsigned DstAlign = MI.getDestAlignment(); 5194 unsigned SrcAlign = MI.getSourceAlignment(); 5195 Type *LengthTy = MI.getLength()->getType(); 5196 unsigned ElemSz = MI.getElementSizeInBytes(); 5197 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5198 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5199 SrcAlign, Length, LengthTy, ElemSz, isTC, 5200 MachinePointerInfo(MI.getRawDest()), 5201 MachinePointerInfo(MI.getRawSource())); 5202 updateDAGForMaybeTailCall(MC); 5203 return nullptr; 5204 } 5205 case Intrinsic::memset_element_unordered_atomic: { 5206 auto &MI = cast<AtomicMemSetInst>(I); 5207 SDValue Dst = getValue(MI.getRawDest()); 5208 SDValue Val = getValue(MI.getValue()); 5209 SDValue Length = getValue(MI.getLength()); 5210 5211 unsigned DstAlign = MI.getDestAlignment(); 5212 Type *LengthTy = MI.getLength()->getType(); 5213 unsigned ElemSz = MI.getElementSizeInBytes(); 5214 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5215 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5216 LengthTy, ElemSz, isTC, 5217 MachinePointerInfo(MI.getRawDest())); 5218 updateDAGForMaybeTailCall(MC); 5219 return nullptr; 5220 } 5221 case Intrinsic::dbg_addr: 5222 case Intrinsic::dbg_declare: { 5223 const auto &DI = cast<DbgVariableIntrinsic>(I); 5224 DILocalVariable *Variable = DI.getVariable(); 5225 DIExpression *Expression = DI.getExpression(); 5226 dropDanglingDebugInfo(Variable, Expression); 5227 assert(Variable && "Missing variable"); 5228 5229 // Check if address has undef value. 5230 const Value *Address = DI.getVariableLocation(); 5231 if (!Address || isa<UndefValue>(Address) || 5232 (Address->use_empty() && !isa<Argument>(Address))) { 5233 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5234 return nullptr; 5235 } 5236 5237 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5238 5239 // Check if this variable can be described by a frame index, typically 5240 // either as a static alloca or a byval parameter. 5241 int FI = std::numeric_limits<int>::max(); 5242 if (const auto *AI = 5243 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5244 if (AI->isStaticAlloca()) { 5245 auto I = FuncInfo.StaticAllocaMap.find(AI); 5246 if (I != FuncInfo.StaticAllocaMap.end()) 5247 FI = I->second; 5248 } 5249 } else if (const auto *Arg = dyn_cast<Argument>( 5250 Address->stripInBoundsConstantOffsets())) { 5251 FI = FuncInfo.getArgumentFrameIndex(Arg); 5252 } 5253 5254 // llvm.dbg.addr is control dependent and always generates indirect 5255 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5256 // the MachineFunction variable table. 5257 if (FI != std::numeric_limits<int>::max()) { 5258 if (Intrinsic == Intrinsic::dbg_addr) { 5259 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5260 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5261 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5262 } 5263 return nullptr; 5264 } 5265 5266 SDValue &N = NodeMap[Address]; 5267 if (!N.getNode() && isa<Argument>(Address)) 5268 // Check unused arguments map. 5269 N = UnusedArgNodeMap[Address]; 5270 SDDbgValue *SDV; 5271 if (N.getNode()) { 5272 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5273 Address = BCI->getOperand(0); 5274 // Parameters are handled specially. 5275 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5276 if (isParameter && FINode) { 5277 // Byval parameter. We have a frame index at this point. 5278 SDV = 5279 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5280 /*IsIndirect*/ true, dl, SDNodeOrder); 5281 } else if (isa<Argument>(Address)) { 5282 // Address is an argument, so try to emit its dbg value using 5283 // virtual register info from the FuncInfo.ValueMap. 5284 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5285 return nullptr; 5286 } else { 5287 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5288 true, dl, SDNodeOrder); 5289 } 5290 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5291 } else { 5292 // If Address is an argument then try to emit its dbg value using 5293 // virtual register info from the FuncInfo.ValueMap. 5294 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5295 N)) { 5296 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5297 } 5298 } 5299 return nullptr; 5300 } 5301 case Intrinsic::dbg_label: { 5302 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5303 DILabel *Label = DI.getLabel(); 5304 assert(Label && "Missing label"); 5305 5306 SDDbgLabel *SDV; 5307 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5308 DAG.AddDbgLabel(SDV); 5309 return nullptr; 5310 } 5311 case Intrinsic::dbg_value: { 5312 const DbgValueInst &DI = cast<DbgValueInst>(I); 5313 assert(DI.getVariable() && "Missing variable"); 5314 5315 DILocalVariable *Variable = DI.getVariable(); 5316 DIExpression *Expression = DI.getExpression(); 5317 dropDanglingDebugInfo(Variable, Expression); 5318 const Value *V = DI.getValue(); 5319 if (!V) 5320 return nullptr; 5321 5322 SDDbgValue *SDV; 5323 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 5324 isa<ConstantPointerNull>(V)) { 5325 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5326 DAG.AddDbgValue(SDV, nullptr, false); 5327 return nullptr; 5328 } 5329 5330 // If the Value is a frame index, we can create a FrameIndex debug value 5331 // without relying on the DAG at all. 5332 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 5333 auto SI = FuncInfo.StaticAllocaMap.find(AI); 5334 if (SI != FuncInfo.StaticAllocaMap.end()) { 5335 auto SDV = 5336 DAG.getFrameIndexDbgValue(Variable, Expression, SI->second, 5337 /*IsIndirect*/ false, dl, SDNodeOrder); 5338 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 5339 // is still available even if the SDNode gets optimized out. 5340 DAG.AddDbgValue(SDV, nullptr, false); 5341 return nullptr; 5342 } 5343 } 5344 5345 // Do not use getValue() in here; we don't want to generate code at 5346 // this point if it hasn't been done yet. 5347 SDValue N = NodeMap[V]; 5348 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5349 N = UnusedArgNodeMap[V]; 5350 if (N.getNode()) { 5351 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5352 return nullptr; 5353 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5354 DAG.AddDbgValue(SDV, N.getNode(), false); 5355 return nullptr; 5356 } 5357 5358 // The value is not used in this block yet (or it would have an SDNode). 5359 // We still want the value to appear for the user if possible -- if it has 5360 // an associated VReg, we can refer to that instead. 5361 if (!isa<Argument>(V)) { 5362 auto VMI = FuncInfo.ValueMap.find(V); 5363 if (VMI != FuncInfo.ValueMap.end()) { 5364 unsigned Reg = VMI->second; 5365 // If this is a PHI node, it may be split up into several MI PHI nodes 5366 // (in FunctionLoweringInfo::set). 5367 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 5368 V->getType(), None); 5369 if (RFV.occupiesMultipleRegs()) { 5370 unsigned Offset = 0; 5371 unsigned BitsToDescribe = 0; 5372 if (auto VarSize = Variable->getSizeInBits()) 5373 BitsToDescribe = *VarSize; 5374 if (auto Fragment = Expression->getFragmentInfo()) 5375 BitsToDescribe = Fragment->SizeInBits; 5376 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5377 unsigned RegisterSize = RegAndSize.second; 5378 // Bail out if all bits are described already. 5379 if (Offset >= BitsToDescribe) 5380 break; 5381 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 5382 ? BitsToDescribe - Offset 5383 : RegisterSize; 5384 auto FragmentExpr = DIExpression::createFragmentExpression( 5385 Expression, Offset, FragmentSize); 5386 if (!FragmentExpr) 5387 continue; 5388 SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first, 5389 false, dl, SDNodeOrder); 5390 DAG.AddDbgValue(SDV, nullptr, false); 5391 Offset += RegisterSize; 5392 } 5393 } else { 5394 SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl, 5395 SDNodeOrder); 5396 DAG.AddDbgValue(SDV, nullptr, false); 5397 } 5398 return nullptr; 5399 } 5400 } 5401 5402 // TODO: When we get here we will either drop the dbg.value completely, or 5403 // we try to move it forward by letting it dangle for awhile. So we should 5404 // probably add an extra DbgValue to the DAG here, with a reference to 5405 // "noreg", to indicate that we have lost the debug location for the 5406 // variable. 5407 5408 if (!V->use_empty() ) { 5409 // Do not call getValue(V) yet, as we don't want to generate code. 5410 // Remember it for later. 5411 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5412 return nullptr; 5413 } 5414 5415 LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5416 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5417 return nullptr; 5418 } 5419 5420 case Intrinsic::eh_typeid_for: { 5421 // Find the type id for the given typeinfo. 5422 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5423 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5424 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5425 setValue(&I, Res); 5426 return nullptr; 5427 } 5428 5429 case Intrinsic::eh_return_i32: 5430 case Intrinsic::eh_return_i64: 5431 DAG.getMachineFunction().setCallsEHReturn(true); 5432 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5433 MVT::Other, 5434 getControlRoot(), 5435 getValue(I.getArgOperand(0)), 5436 getValue(I.getArgOperand(1)))); 5437 return nullptr; 5438 case Intrinsic::eh_unwind_init: 5439 DAG.getMachineFunction().setCallsUnwindInit(true); 5440 return nullptr; 5441 case Intrinsic::eh_dwarf_cfa: 5442 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5443 TLI.getPointerTy(DAG.getDataLayout()), 5444 getValue(I.getArgOperand(0)))); 5445 return nullptr; 5446 case Intrinsic::eh_sjlj_callsite: { 5447 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5448 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5449 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5450 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5451 5452 MMI.setCurrentCallSite(CI->getZExtValue()); 5453 return nullptr; 5454 } 5455 case Intrinsic::eh_sjlj_functioncontext: { 5456 // Get and store the index of the function context. 5457 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5458 AllocaInst *FnCtx = 5459 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5460 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5461 MFI.setFunctionContextIndex(FI); 5462 return nullptr; 5463 } 5464 case Intrinsic::eh_sjlj_setjmp: { 5465 SDValue Ops[2]; 5466 Ops[0] = getRoot(); 5467 Ops[1] = getValue(I.getArgOperand(0)); 5468 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5469 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5470 setValue(&I, Op.getValue(0)); 5471 DAG.setRoot(Op.getValue(1)); 5472 return nullptr; 5473 } 5474 case Intrinsic::eh_sjlj_longjmp: 5475 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5476 getRoot(), getValue(I.getArgOperand(0)))); 5477 return nullptr; 5478 case Intrinsic::eh_sjlj_setup_dispatch: 5479 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5480 getRoot())); 5481 return nullptr; 5482 case Intrinsic::masked_gather: 5483 visitMaskedGather(I); 5484 return nullptr; 5485 case Intrinsic::masked_load: 5486 visitMaskedLoad(I); 5487 return nullptr; 5488 case Intrinsic::masked_scatter: 5489 visitMaskedScatter(I); 5490 return nullptr; 5491 case Intrinsic::masked_store: 5492 visitMaskedStore(I); 5493 return nullptr; 5494 case Intrinsic::masked_expandload: 5495 visitMaskedLoad(I, true /* IsExpanding */); 5496 return nullptr; 5497 case Intrinsic::masked_compressstore: 5498 visitMaskedStore(I, true /* IsCompressing */); 5499 return nullptr; 5500 case Intrinsic::x86_mmx_pslli_w: 5501 case Intrinsic::x86_mmx_pslli_d: 5502 case Intrinsic::x86_mmx_pslli_q: 5503 case Intrinsic::x86_mmx_psrli_w: 5504 case Intrinsic::x86_mmx_psrli_d: 5505 case Intrinsic::x86_mmx_psrli_q: 5506 case Intrinsic::x86_mmx_psrai_w: 5507 case Intrinsic::x86_mmx_psrai_d: { 5508 SDValue ShAmt = getValue(I.getArgOperand(1)); 5509 if (isa<ConstantSDNode>(ShAmt)) { 5510 visitTargetIntrinsic(I, Intrinsic); 5511 return nullptr; 5512 } 5513 unsigned NewIntrinsic = 0; 5514 EVT ShAmtVT = MVT::v2i32; 5515 switch (Intrinsic) { 5516 case Intrinsic::x86_mmx_pslli_w: 5517 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5518 break; 5519 case Intrinsic::x86_mmx_pslli_d: 5520 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5521 break; 5522 case Intrinsic::x86_mmx_pslli_q: 5523 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5524 break; 5525 case Intrinsic::x86_mmx_psrli_w: 5526 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5527 break; 5528 case Intrinsic::x86_mmx_psrli_d: 5529 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5530 break; 5531 case Intrinsic::x86_mmx_psrli_q: 5532 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5533 break; 5534 case Intrinsic::x86_mmx_psrai_w: 5535 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5536 break; 5537 case Intrinsic::x86_mmx_psrai_d: 5538 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5539 break; 5540 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5541 } 5542 5543 // The vector shift intrinsics with scalars uses 32b shift amounts but 5544 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5545 // to be zero. 5546 // We must do this early because v2i32 is not a legal type. 5547 SDValue ShOps[2]; 5548 ShOps[0] = ShAmt; 5549 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5550 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5551 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5552 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5553 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5554 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5555 getValue(I.getArgOperand(0)), ShAmt); 5556 setValue(&I, Res); 5557 return nullptr; 5558 } 5559 case Intrinsic::powi: 5560 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5561 getValue(I.getArgOperand(1)), DAG)); 5562 return nullptr; 5563 case Intrinsic::log: 5564 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5565 return nullptr; 5566 case Intrinsic::log2: 5567 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5568 return nullptr; 5569 case Intrinsic::log10: 5570 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5571 return nullptr; 5572 case Intrinsic::exp: 5573 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5574 return nullptr; 5575 case Intrinsic::exp2: 5576 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5577 return nullptr; 5578 case Intrinsic::pow: 5579 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5580 getValue(I.getArgOperand(1)), DAG, TLI)); 5581 return nullptr; 5582 case Intrinsic::sqrt: 5583 case Intrinsic::fabs: 5584 case Intrinsic::sin: 5585 case Intrinsic::cos: 5586 case Intrinsic::floor: 5587 case Intrinsic::ceil: 5588 case Intrinsic::trunc: 5589 case Intrinsic::rint: 5590 case Intrinsic::nearbyint: 5591 case Intrinsic::round: 5592 case Intrinsic::canonicalize: { 5593 unsigned Opcode; 5594 switch (Intrinsic) { 5595 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5596 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5597 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5598 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5599 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5600 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5601 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5602 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5603 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5604 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5605 case Intrinsic::round: Opcode = ISD::FROUND; break; 5606 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5607 } 5608 5609 setValue(&I, DAG.getNode(Opcode, sdl, 5610 getValue(I.getArgOperand(0)).getValueType(), 5611 getValue(I.getArgOperand(0)))); 5612 return nullptr; 5613 } 5614 case Intrinsic::minnum: { 5615 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5616 unsigned Opc = 5617 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT) 5618 ? ISD::FMINIMUM 5619 : ISD::FMINNUM; 5620 setValue(&I, DAG.getNode(Opc, sdl, VT, 5621 getValue(I.getArgOperand(0)), 5622 getValue(I.getArgOperand(1)))); 5623 return nullptr; 5624 } 5625 case Intrinsic::maxnum: { 5626 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5627 unsigned Opc = 5628 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT) 5629 ? ISD::FMAXIMUM 5630 : ISD::FMAXNUM; 5631 setValue(&I, DAG.getNode(Opc, sdl, VT, 5632 getValue(I.getArgOperand(0)), 5633 getValue(I.getArgOperand(1)))); 5634 return nullptr; 5635 } 5636 case Intrinsic::minimum: 5637 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 5638 getValue(I.getArgOperand(0)).getValueType(), 5639 getValue(I.getArgOperand(0)), 5640 getValue(I.getArgOperand(1)))); 5641 return nullptr; 5642 case Intrinsic::maximum: 5643 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 5644 getValue(I.getArgOperand(0)).getValueType(), 5645 getValue(I.getArgOperand(0)), 5646 getValue(I.getArgOperand(1)))); 5647 return nullptr; 5648 case Intrinsic::copysign: 5649 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5650 getValue(I.getArgOperand(0)).getValueType(), 5651 getValue(I.getArgOperand(0)), 5652 getValue(I.getArgOperand(1)))); 5653 return nullptr; 5654 case Intrinsic::fma: 5655 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5656 getValue(I.getArgOperand(0)).getValueType(), 5657 getValue(I.getArgOperand(0)), 5658 getValue(I.getArgOperand(1)), 5659 getValue(I.getArgOperand(2)))); 5660 return nullptr; 5661 case Intrinsic::experimental_constrained_fadd: 5662 case Intrinsic::experimental_constrained_fsub: 5663 case Intrinsic::experimental_constrained_fmul: 5664 case Intrinsic::experimental_constrained_fdiv: 5665 case Intrinsic::experimental_constrained_frem: 5666 case Intrinsic::experimental_constrained_fma: 5667 case Intrinsic::experimental_constrained_sqrt: 5668 case Intrinsic::experimental_constrained_pow: 5669 case Intrinsic::experimental_constrained_powi: 5670 case Intrinsic::experimental_constrained_sin: 5671 case Intrinsic::experimental_constrained_cos: 5672 case Intrinsic::experimental_constrained_exp: 5673 case Intrinsic::experimental_constrained_exp2: 5674 case Intrinsic::experimental_constrained_log: 5675 case Intrinsic::experimental_constrained_log10: 5676 case Intrinsic::experimental_constrained_log2: 5677 case Intrinsic::experimental_constrained_rint: 5678 case Intrinsic::experimental_constrained_nearbyint: 5679 case Intrinsic::experimental_constrained_maxnum: 5680 case Intrinsic::experimental_constrained_minnum: 5681 case Intrinsic::experimental_constrained_ceil: 5682 case Intrinsic::experimental_constrained_floor: 5683 case Intrinsic::experimental_constrained_round: 5684 case Intrinsic::experimental_constrained_trunc: 5685 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5686 return nullptr; 5687 case Intrinsic::fmuladd: { 5688 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5689 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5690 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5691 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5692 getValue(I.getArgOperand(0)).getValueType(), 5693 getValue(I.getArgOperand(0)), 5694 getValue(I.getArgOperand(1)), 5695 getValue(I.getArgOperand(2)))); 5696 } else { 5697 // TODO: Intrinsic calls should have fast-math-flags. 5698 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5699 getValue(I.getArgOperand(0)).getValueType(), 5700 getValue(I.getArgOperand(0)), 5701 getValue(I.getArgOperand(1))); 5702 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5703 getValue(I.getArgOperand(0)).getValueType(), 5704 Mul, 5705 getValue(I.getArgOperand(2))); 5706 setValue(&I, Add); 5707 } 5708 return nullptr; 5709 } 5710 case Intrinsic::convert_to_fp16: 5711 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5712 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5713 getValue(I.getArgOperand(0)), 5714 DAG.getTargetConstant(0, sdl, 5715 MVT::i32)))); 5716 return nullptr; 5717 case Intrinsic::convert_from_fp16: 5718 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5719 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5720 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5721 getValue(I.getArgOperand(0))))); 5722 return nullptr; 5723 case Intrinsic::pcmarker: { 5724 SDValue Tmp = getValue(I.getArgOperand(0)); 5725 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5726 return nullptr; 5727 } 5728 case Intrinsic::readcyclecounter: { 5729 SDValue Op = getRoot(); 5730 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5731 DAG.getVTList(MVT::i64, MVT::Other), Op); 5732 setValue(&I, Res); 5733 DAG.setRoot(Res.getValue(1)); 5734 return nullptr; 5735 } 5736 case Intrinsic::bitreverse: 5737 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5738 getValue(I.getArgOperand(0)).getValueType(), 5739 getValue(I.getArgOperand(0)))); 5740 return nullptr; 5741 case Intrinsic::bswap: 5742 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5743 getValue(I.getArgOperand(0)).getValueType(), 5744 getValue(I.getArgOperand(0)))); 5745 return nullptr; 5746 case Intrinsic::cttz: { 5747 SDValue Arg = getValue(I.getArgOperand(0)); 5748 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5749 EVT Ty = Arg.getValueType(); 5750 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5751 sdl, Ty, Arg)); 5752 return nullptr; 5753 } 5754 case Intrinsic::ctlz: { 5755 SDValue Arg = getValue(I.getArgOperand(0)); 5756 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5757 EVT Ty = Arg.getValueType(); 5758 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5759 sdl, Ty, Arg)); 5760 return nullptr; 5761 } 5762 case Intrinsic::ctpop: { 5763 SDValue Arg = getValue(I.getArgOperand(0)); 5764 EVT Ty = Arg.getValueType(); 5765 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5766 return nullptr; 5767 } 5768 case Intrinsic::fshl: 5769 case Intrinsic::fshr: { 5770 bool IsFSHL = Intrinsic == Intrinsic::fshl; 5771 SDValue X = getValue(I.getArgOperand(0)); 5772 SDValue Y = getValue(I.getArgOperand(1)); 5773 SDValue Z = getValue(I.getArgOperand(2)); 5774 EVT VT = X.getValueType(); 5775 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 5776 SDValue Zero = DAG.getConstant(0, sdl, VT); 5777 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 5778 5779 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 5780 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 5781 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 5782 return nullptr; 5783 } 5784 5785 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 5786 // avoid the select that is necessary in the general case to filter out 5787 // the 0-shift possibility that leads to UB. 5788 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 5789 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 5790 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5791 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 5792 return nullptr; 5793 } 5794 5795 // Some targets only rotate one way. Try the opposite direction. 5796 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 5797 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5798 // Negate the shift amount because it is safe to ignore the high bits. 5799 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5800 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 5801 return nullptr; 5802 } 5803 5804 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 5805 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 5806 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5807 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 5808 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 5809 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 5810 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 5811 return nullptr; 5812 } 5813 5814 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 5815 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 5816 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 5817 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 5818 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 5819 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 5820 5821 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 5822 // and that is undefined. We must compare and select to avoid UB. 5823 EVT CCVT = MVT::i1; 5824 if (VT.isVector()) 5825 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 5826 5827 // For fshl, 0-shift returns the 1st arg (X). 5828 // For fshr, 0-shift returns the 2nd arg (Y). 5829 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 5830 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 5831 return nullptr; 5832 } 5833 case Intrinsic::sadd_sat: { 5834 SDValue Op1 = getValue(I.getArgOperand(0)); 5835 SDValue Op2 = getValue(I.getArgOperand(1)); 5836 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5837 return nullptr; 5838 } 5839 case Intrinsic::uadd_sat: { 5840 SDValue Op1 = getValue(I.getArgOperand(0)); 5841 SDValue Op2 = getValue(I.getArgOperand(1)); 5842 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5843 return nullptr; 5844 } 5845 case Intrinsic::ssub_sat: { 5846 SDValue Op1 = getValue(I.getArgOperand(0)); 5847 SDValue Op2 = getValue(I.getArgOperand(1)); 5848 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5849 return nullptr; 5850 } 5851 case Intrinsic::usub_sat: { 5852 SDValue Op1 = getValue(I.getArgOperand(0)); 5853 SDValue Op2 = getValue(I.getArgOperand(1)); 5854 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5855 return nullptr; 5856 } 5857 case Intrinsic::smul_fix: { 5858 SDValue Op1 = getValue(I.getArgOperand(0)); 5859 SDValue Op2 = getValue(I.getArgOperand(1)); 5860 SDValue Op3 = getValue(I.getArgOperand(2)); 5861 setValue(&I, 5862 DAG.getNode(ISD::SMULFIX, sdl, Op1.getValueType(), Op1, Op2, Op3)); 5863 return nullptr; 5864 } 5865 case Intrinsic::stacksave: { 5866 SDValue Op = getRoot(); 5867 Res = DAG.getNode( 5868 ISD::STACKSAVE, sdl, 5869 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5870 setValue(&I, Res); 5871 DAG.setRoot(Res.getValue(1)); 5872 return nullptr; 5873 } 5874 case Intrinsic::stackrestore: 5875 Res = getValue(I.getArgOperand(0)); 5876 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5877 return nullptr; 5878 case Intrinsic::get_dynamic_area_offset: { 5879 SDValue Op = getRoot(); 5880 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5881 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5882 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5883 // target. 5884 if (PtrTy != ResTy) 5885 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5886 " intrinsic!"); 5887 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5888 Op); 5889 DAG.setRoot(Op); 5890 setValue(&I, Res); 5891 return nullptr; 5892 } 5893 case Intrinsic::stackguard: { 5894 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5895 MachineFunction &MF = DAG.getMachineFunction(); 5896 const Module &M = *MF.getFunction().getParent(); 5897 SDValue Chain = getRoot(); 5898 if (TLI.useLoadStackGuardNode()) { 5899 Res = getLoadStackGuard(DAG, sdl, Chain); 5900 } else { 5901 const Value *Global = TLI.getSDagStackGuard(M); 5902 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5903 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5904 MachinePointerInfo(Global, 0), Align, 5905 MachineMemOperand::MOVolatile); 5906 } 5907 if (TLI.useStackGuardXorFP()) 5908 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 5909 DAG.setRoot(Chain); 5910 setValue(&I, Res); 5911 return nullptr; 5912 } 5913 case Intrinsic::stackprotector: { 5914 // Emit code into the DAG to store the stack guard onto the stack. 5915 MachineFunction &MF = DAG.getMachineFunction(); 5916 MachineFrameInfo &MFI = MF.getFrameInfo(); 5917 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5918 SDValue Src, Chain = getRoot(); 5919 5920 if (TLI.useLoadStackGuardNode()) 5921 Src = getLoadStackGuard(DAG, sdl, Chain); 5922 else 5923 Src = getValue(I.getArgOperand(0)); // The guard's value. 5924 5925 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5926 5927 int FI = FuncInfo.StaticAllocaMap[Slot]; 5928 MFI.setStackProtectorIndex(FI); 5929 5930 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5931 5932 // Store the stack protector onto the stack. 5933 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5934 DAG.getMachineFunction(), FI), 5935 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5936 setValue(&I, Res); 5937 DAG.setRoot(Res); 5938 return nullptr; 5939 } 5940 case Intrinsic::objectsize: { 5941 // If we don't know by now, we're never going to know. 5942 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5943 5944 assert(CI && "Non-constant type in __builtin_object_size?"); 5945 5946 SDValue Arg = getValue(I.getCalledValue()); 5947 EVT Ty = Arg.getValueType(); 5948 5949 if (CI->isZero()) 5950 Res = DAG.getConstant(-1ULL, sdl, Ty); 5951 else 5952 Res = DAG.getConstant(0, sdl, Ty); 5953 5954 setValue(&I, Res); 5955 return nullptr; 5956 } 5957 5958 case Intrinsic::is_constant: 5959 // If this wasn't constant-folded away by now, then it's not a 5960 // constant. 5961 setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); 5962 return nullptr; 5963 5964 case Intrinsic::annotation: 5965 case Intrinsic::ptr_annotation: 5966 case Intrinsic::launder_invariant_group: 5967 case Intrinsic::strip_invariant_group: 5968 // Drop the intrinsic, but forward the value 5969 setValue(&I, getValue(I.getOperand(0))); 5970 return nullptr; 5971 case Intrinsic::assume: 5972 case Intrinsic::var_annotation: 5973 case Intrinsic::sideeffect: 5974 // Discard annotate attributes, assumptions, and artificial side-effects. 5975 return nullptr; 5976 5977 case Intrinsic::codeview_annotation: { 5978 // Emit a label associated with this metadata. 5979 MachineFunction &MF = DAG.getMachineFunction(); 5980 MCSymbol *Label = 5981 MF.getMMI().getContext().createTempSymbol("annotation", true); 5982 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 5983 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 5984 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 5985 DAG.setRoot(Res); 5986 return nullptr; 5987 } 5988 5989 case Intrinsic::init_trampoline: { 5990 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5991 5992 SDValue Ops[6]; 5993 Ops[0] = getRoot(); 5994 Ops[1] = getValue(I.getArgOperand(0)); 5995 Ops[2] = getValue(I.getArgOperand(1)); 5996 Ops[3] = getValue(I.getArgOperand(2)); 5997 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5998 Ops[5] = DAG.getSrcValue(F); 5999 6000 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6001 6002 DAG.setRoot(Res); 6003 return nullptr; 6004 } 6005 case Intrinsic::adjust_trampoline: 6006 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6007 TLI.getPointerTy(DAG.getDataLayout()), 6008 getValue(I.getArgOperand(0)))); 6009 return nullptr; 6010 case Intrinsic::gcroot: { 6011 assert(DAG.getMachineFunction().getFunction().hasGC() && 6012 "only valid in functions with gc specified, enforced by Verifier"); 6013 assert(GFI && "implied by previous"); 6014 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6015 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6016 6017 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6018 GFI->addStackRoot(FI->getIndex(), TypeMap); 6019 return nullptr; 6020 } 6021 case Intrinsic::gcread: 6022 case Intrinsic::gcwrite: 6023 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6024 case Intrinsic::flt_rounds: 6025 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6026 return nullptr; 6027 6028 case Intrinsic::expect: 6029 // Just replace __builtin_expect(exp, c) with EXP. 6030 setValue(&I, getValue(I.getArgOperand(0))); 6031 return nullptr; 6032 6033 case Intrinsic::debugtrap: 6034 case Intrinsic::trap: { 6035 StringRef TrapFuncName = 6036 I.getAttributes() 6037 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6038 .getValueAsString(); 6039 if (TrapFuncName.empty()) { 6040 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6041 ISD::TRAP : ISD::DEBUGTRAP; 6042 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6043 return nullptr; 6044 } 6045 TargetLowering::ArgListTy Args; 6046 6047 TargetLowering::CallLoweringInfo CLI(DAG); 6048 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6049 CallingConv::C, I.getType(), 6050 DAG.getExternalSymbol(TrapFuncName.data(), 6051 TLI.getPointerTy(DAG.getDataLayout())), 6052 std::move(Args)); 6053 6054 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6055 DAG.setRoot(Result.second); 6056 return nullptr; 6057 } 6058 6059 case Intrinsic::uadd_with_overflow: 6060 case Intrinsic::sadd_with_overflow: 6061 case Intrinsic::usub_with_overflow: 6062 case Intrinsic::ssub_with_overflow: 6063 case Intrinsic::umul_with_overflow: 6064 case Intrinsic::smul_with_overflow: { 6065 ISD::NodeType Op; 6066 switch (Intrinsic) { 6067 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6068 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6069 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6070 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6071 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6072 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6073 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6074 } 6075 SDValue Op1 = getValue(I.getArgOperand(0)); 6076 SDValue Op2 = getValue(I.getArgOperand(1)); 6077 6078 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 6079 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6080 return nullptr; 6081 } 6082 case Intrinsic::prefetch: { 6083 SDValue Ops[5]; 6084 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6085 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6086 Ops[0] = DAG.getRoot(); 6087 Ops[1] = getValue(I.getArgOperand(0)); 6088 Ops[2] = getValue(I.getArgOperand(1)); 6089 Ops[3] = getValue(I.getArgOperand(2)); 6090 Ops[4] = getValue(I.getArgOperand(3)); 6091 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6092 DAG.getVTList(MVT::Other), Ops, 6093 EVT::getIntegerVT(*Context, 8), 6094 MachinePointerInfo(I.getArgOperand(0)), 6095 0, /* align */ 6096 Flags); 6097 6098 // Chain the prefetch in parallell with any pending loads, to stay out of 6099 // the way of later optimizations. 6100 PendingLoads.push_back(Result); 6101 Result = getRoot(); 6102 DAG.setRoot(Result); 6103 return nullptr; 6104 } 6105 case Intrinsic::lifetime_start: 6106 case Intrinsic::lifetime_end: { 6107 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6108 // Stack coloring is not enabled in O0, discard region information. 6109 if (TM.getOptLevel() == CodeGenOpt::None) 6110 return nullptr; 6111 6112 SmallVector<Value *, 4> Allocas; 6113 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 6114 6115 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 6116 E = Allocas.end(); Object != E; ++Object) { 6117 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6118 6119 // Could not find an Alloca. 6120 if (!LifetimeObject) 6121 continue; 6122 6123 // First check that the Alloca is static, otherwise it won't have a 6124 // valid frame index. 6125 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6126 if (SI == FuncInfo.StaticAllocaMap.end()) 6127 return nullptr; 6128 6129 int FI = SI->second; 6130 6131 SDValue Ops[2]; 6132 Ops[0] = getRoot(); 6133 Ops[1] = 6134 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 6135 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 6136 6137 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 6138 DAG.setRoot(Res); 6139 } 6140 return nullptr; 6141 } 6142 case Intrinsic::invariant_start: 6143 // Discard region information. 6144 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6145 return nullptr; 6146 case Intrinsic::invariant_end: 6147 // Discard region information. 6148 return nullptr; 6149 case Intrinsic::clear_cache: 6150 return TLI.getClearCacheBuiltinName(); 6151 case Intrinsic::donothing: 6152 // ignore 6153 return nullptr; 6154 case Intrinsic::experimental_stackmap: 6155 visitStackmap(I); 6156 return nullptr; 6157 case Intrinsic::experimental_patchpoint_void: 6158 case Intrinsic::experimental_patchpoint_i64: 6159 visitPatchpoint(&I); 6160 return nullptr; 6161 case Intrinsic::experimental_gc_statepoint: 6162 LowerStatepoint(ImmutableStatepoint(&I)); 6163 return nullptr; 6164 case Intrinsic::experimental_gc_result: 6165 visitGCResult(cast<GCResultInst>(I)); 6166 return nullptr; 6167 case Intrinsic::experimental_gc_relocate: 6168 visitGCRelocate(cast<GCRelocateInst>(I)); 6169 return nullptr; 6170 case Intrinsic::instrprof_increment: 6171 llvm_unreachable("instrprof failed to lower an increment"); 6172 case Intrinsic::instrprof_value_profile: 6173 llvm_unreachable("instrprof failed to lower a value profiling call"); 6174 case Intrinsic::localescape: { 6175 MachineFunction &MF = DAG.getMachineFunction(); 6176 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6177 6178 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6179 // is the same on all targets. 6180 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6181 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6182 if (isa<ConstantPointerNull>(Arg)) 6183 continue; // Skip null pointers. They represent a hole in index space. 6184 AllocaInst *Slot = cast<AllocaInst>(Arg); 6185 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6186 "can only escape static allocas"); 6187 int FI = FuncInfo.StaticAllocaMap[Slot]; 6188 MCSymbol *FrameAllocSym = 6189 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6190 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6191 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6192 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6193 .addSym(FrameAllocSym) 6194 .addFrameIndex(FI); 6195 } 6196 6197 MF.setHasLocalEscape(true); 6198 6199 return nullptr; 6200 } 6201 6202 case Intrinsic::localrecover: { 6203 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6204 MachineFunction &MF = DAG.getMachineFunction(); 6205 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6206 6207 // Get the symbol that defines the frame offset. 6208 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6209 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6210 unsigned IdxVal = 6211 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6212 MCSymbol *FrameAllocSym = 6213 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6214 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6215 6216 // Create a MCSymbol for the label to avoid any target lowering 6217 // that would make this PC relative. 6218 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6219 SDValue OffsetVal = 6220 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6221 6222 // Add the offset to the FP. 6223 Value *FP = I.getArgOperand(1); 6224 SDValue FPVal = getValue(FP); 6225 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6226 setValue(&I, Add); 6227 6228 return nullptr; 6229 } 6230 6231 case Intrinsic::eh_exceptionpointer: 6232 case Intrinsic::eh_exceptioncode: { 6233 // Get the exception pointer vreg, copy from it, and resize it to fit. 6234 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6235 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6236 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6237 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6238 SDValue N = 6239 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6240 if (Intrinsic == Intrinsic::eh_exceptioncode) 6241 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6242 setValue(&I, N); 6243 return nullptr; 6244 } 6245 case Intrinsic::xray_customevent: { 6246 // Here we want to make sure that the intrinsic behaves as if it has a 6247 // specific calling convention, and only for x86_64. 6248 // FIXME: Support other platforms later. 6249 const auto &Triple = DAG.getTarget().getTargetTriple(); 6250 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6251 return nullptr; 6252 6253 SDLoc DL = getCurSDLoc(); 6254 SmallVector<SDValue, 8> Ops; 6255 6256 // We want to say that we always want the arguments in registers. 6257 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6258 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6259 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6260 SDValue Chain = getRoot(); 6261 Ops.push_back(LogEntryVal); 6262 Ops.push_back(StrSizeVal); 6263 Ops.push_back(Chain); 6264 6265 // We need to enforce the calling convention for the callsite, so that 6266 // argument ordering is enforced correctly, and that register allocation can 6267 // see that some registers may be assumed clobbered and have to preserve 6268 // them across calls to the intrinsic. 6269 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6270 DL, NodeTys, Ops); 6271 SDValue patchableNode = SDValue(MN, 0); 6272 DAG.setRoot(patchableNode); 6273 setValue(&I, patchableNode); 6274 return nullptr; 6275 } 6276 case Intrinsic::xray_typedevent: { 6277 // Here we want to make sure that the intrinsic behaves as if it has a 6278 // specific calling convention, and only for x86_64. 6279 // FIXME: Support other platforms later. 6280 const auto &Triple = DAG.getTarget().getTargetTriple(); 6281 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6282 return nullptr; 6283 6284 SDLoc DL = getCurSDLoc(); 6285 SmallVector<SDValue, 8> Ops; 6286 6287 // We want to say that we always want the arguments in registers. 6288 // It's unclear to me how manipulating the selection DAG here forces callers 6289 // to provide arguments in registers instead of on the stack. 6290 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6291 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6292 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6293 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6294 SDValue Chain = getRoot(); 6295 Ops.push_back(LogTypeId); 6296 Ops.push_back(LogEntryVal); 6297 Ops.push_back(StrSizeVal); 6298 Ops.push_back(Chain); 6299 6300 // We need to enforce the calling convention for the callsite, so that 6301 // argument ordering is enforced correctly, and that register allocation can 6302 // see that some registers may be assumed clobbered and have to preserve 6303 // them across calls to the intrinsic. 6304 MachineSDNode *MN = DAG.getMachineNode( 6305 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6306 SDValue patchableNode = SDValue(MN, 0); 6307 DAG.setRoot(patchableNode); 6308 setValue(&I, patchableNode); 6309 return nullptr; 6310 } 6311 case Intrinsic::experimental_deoptimize: 6312 LowerDeoptimizeCall(&I); 6313 return nullptr; 6314 6315 case Intrinsic::experimental_vector_reduce_fadd: 6316 case Intrinsic::experimental_vector_reduce_fmul: 6317 case Intrinsic::experimental_vector_reduce_add: 6318 case Intrinsic::experimental_vector_reduce_mul: 6319 case Intrinsic::experimental_vector_reduce_and: 6320 case Intrinsic::experimental_vector_reduce_or: 6321 case Intrinsic::experimental_vector_reduce_xor: 6322 case Intrinsic::experimental_vector_reduce_smax: 6323 case Intrinsic::experimental_vector_reduce_smin: 6324 case Intrinsic::experimental_vector_reduce_umax: 6325 case Intrinsic::experimental_vector_reduce_umin: 6326 case Intrinsic::experimental_vector_reduce_fmax: 6327 case Intrinsic::experimental_vector_reduce_fmin: 6328 visitVectorReduce(I, Intrinsic); 6329 return nullptr; 6330 6331 case Intrinsic::icall_branch_funnel: { 6332 SmallVector<SDValue, 16> Ops; 6333 Ops.push_back(DAG.getRoot()); 6334 Ops.push_back(getValue(I.getArgOperand(0))); 6335 6336 int64_t Offset; 6337 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6338 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6339 if (!Base) 6340 report_fatal_error( 6341 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6342 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6343 6344 struct BranchFunnelTarget { 6345 int64_t Offset; 6346 SDValue Target; 6347 }; 6348 SmallVector<BranchFunnelTarget, 8> Targets; 6349 6350 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6351 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6352 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6353 if (ElemBase != Base) 6354 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6355 "to the same GlobalValue"); 6356 6357 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6358 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6359 if (!GA) 6360 report_fatal_error( 6361 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6362 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6363 GA->getGlobal(), getCurSDLoc(), 6364 Val.getValueType(), GA->getOffset())}); 6365 } 6366 llvm::sort(Targets, 6367 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6368 return T1.Offset < T2.Offset; 6369 }); 6370 6371 for (auto &T : Targets) { 6372 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6373 Ops.push_back(T.Target); 6374 } 6375 6376 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6377 getCurSDLoc(), MVT::Other, Ops), 6378 0); 6379 DAG.setRoot(N); 6380 setValue(&I, N); 6381 HasTailCall = true; 6382 return nullptr; 6383 } 6384 6385 case Intrinsic::wasm_landingpad_index: 6386 // Information this intrinsic contained has been transferred to 6387 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6388 // delete it now. 6389 return nullptr; 6390 } 6391 } 6392 6393 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6394 const ConstrainedFPIntrinsic &FPI) { 6395 SDLoc sdl = getCurSDLoc(); 6396 unsigned Opcode; 6397 switch (FPI.getIntrinsicID()) { 6398 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6399 case Intrinsic::experimental_constrained_fadd: 6400 Opcode = ISD::STRICT_FADD; 6401 break; 6402 case Intrinsic::experimental_constrained_fsub: 6403 Opcode = ISD::STRICT_FSUB; 6404 break; 6405 case Intrinsic::experimental_constrained_fmul: 6406 Opcode = ISD::STRICT_FMUL; 6407 break; 6408 case Intrinsic::experimental_constrained_fdiv: 6409 Opcode = ISD::STRICT_FDIV; 6410 break; 6411 case Intrinsic::experimental_constrained_frem: 6412 Opcode = ISD::STRICT_FREM; 6413 break; 6414 case Intrinsic::experimental_constrained_fma: 6415 Opcode = ISD::STRICT_FMA; 6416 break; 6417 case Intrinsic::experimental_constrained_sqrt: 6418 Opcode = ISD::STRICT_FSQRT; 6419 break; 6420 case Intrinsic::experimental_constrained_pow: 6421 Opcode = ISD::STRICT_FPOW; 6422 break; 6423 case Intrinsic::experimental_constrained_powi: 6424 Opcode = ISD::STRICT_FPOWI; 6425 break; 6426 case Intrinsic::experimental_constrained_sin: 6427 Opcode = ISD::STRICT_FSIN; 6428 break; 6429 case Intrinsic::experimental_constrained_cos: 6430 Opcode = ISD::STRICT_FCOS; 6431 break; 6432 case Intrinsic::experimental_constrained_exp: 6433 Opcode = ISD::STRICT_FEXP; 6434 break; 6435 case Intrinsic::experimental_constrained_exp2: 6436 Opcode = ISD::STRICT_FEXP2; 6437 break; 6438 case Intrinsic::experimental_constrained_log: 6439 Opcode = ISD::STRICT_FLOG; 6440 break; 6441 case Intrinsic::experimental_constrained_log10: 6442 Opcode = ISD::STRICT_FLOG10; 6443 break; 6444 case Intrinsic::experimental_constrained_log2: 6445 Opcode = ISD::STRICT_FLOG2; 6446 break; 6447 case Intrinsic::experimental_constrained_rint: 6448 Opcode = ISD::STRICT_FRINT; 6449 break; 6450 case Intrinsic::experimental_constrained_nearbyint: 6451 Opcode = ISD::STRICT_FNEARBYINT; 6452 break; 6453 case Intrinsic::experimental_constrained_maxnum: 6454 Opcode = ISD::STRICT_FMAXNUM; 6455 break; 6456 case Intrinsic::experimental_constrained_minnum: 6457 Opcode = ISD::STRICT_FMINNUM; 6458 break; 6459 case Intrinsic::experimental_constrained_ceil: 6460 Opcode = ISD::STRICT_FCEIL; 6461 break; 6462 case Intrinsic::experimental_constrained_floor: 6463 Opcode = ISD::STRICT_FFLOOR; 6464 break; 6465 case Intrinsic::experimental_constrained_round: 6466 Opcode = ISD::STRICT_FROUND; 6467 break; 6468 case Intrinsic::experimental_constrained_trunc: 6469 Opcode = ISD::STRICT_FTRUNC; 6470 break; 6471 } 6472 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6473 SDValue Chain = getRoot(); 6474 SmallVector<EVT, 4> ValueVTs; 6475 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6476 ValueVTs.push_back(MVT::Other); // Out chain 6477 6478 SDVTList VTs = DAG.getVTList(ValueVTs); 6479 SDValue Result; 6480 if (FPI.isUnaryOp()) 6481 Result = DAG.getNode(Opcode, sdl, VTs, 6482 { Chain, getValue(FPI.getArgOperand(0)) }); 6483 else if (FPI.isTernaryOp()) 6484 Result = DAG.getNode(Opcode, sdl, VTs, 6485 { Chain, getValue(FPI.getArgOperand(0)), 6486 getValue(FPI.getArgOperand(1)), 6487 getValue(FPI.getArgOperand(2)) }); 6488 else 6489 Result = DAG.getNode(Opcode, sdl, VTs, 6490 { Chain, getValue(FPI.getArgOperand(0)), 6491 getValue(FPI.getArgOperand(1)) }); 6492 6493 assert(Result.getNode()->getNumValues() == 2); 6494 SDValue OutChain = Result.getValue(1); 6495 DAG.setRoot(OutChain); 6496 SDValue FPResult = Result.getValue(0); 6497 setValue(&FPI, FPResult); 6498 } 6499 6500 std::pair<SDValue, SDValue> 6501 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6502 const BasicBlock *EHPadBB) { 6503 MachineFunction &MF = DAG.getMachineFunction(); 6504 MachineModuleInfo &MMI = MF.getMMI(); 6505 MCSymbol *BeginLabel = nullptr; 6506 6507 if (EHPadBB) { 6508 // Insert a label before the invoke call to mark the try range. This can be 6509 // used to detect deletion of the invoke via the MachineModuleInfo. 6510 BeginLabel = MMI.getContext().createTempSymbol(); 6511 6512 // For SjLj, keep track of which landing pads go with which invokes 6513 // so as to maintain the ordering of pads in the LSDA. 6514 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6515 if (CallSiteIndex) { 6516 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6517 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6518 6519 // Now that the call site is handled, stop tracking it. 6520 MMI.setCurrentCallSite(0); 6521 } 6522 6523 // Both PendingLoads and PendingExports must be flushed here; 6524 // this call might not return. 6525 (void)getRoot(); 6526 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6527 6528 CLI.setChain(getRoot()); 6529 } 6530 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6531 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6532 6533 assert((CLI.IsTailCall || Result.second.getNode()) && 6534 "Non-null chain expected with non-tail call!"); 6535 assert((Result.second.getNode() || !Result.first.getNode()) && 6536 "Null value expected with tail call!"); 6537 6538 if (!Result.second.getNode()) { 6539 // As a special case, a null chain means that a tail call has been emitted 6540 // and the DAG root is already updated. 6541 HasTailCall = true; 6542 6543 // Since there's no actual continuation from this block, nothing can be 6544 // relying on us setting vregs for them. 6545 PendingExports.clear(); 6546 } else { 6547 DAG.setRoot(Result.second); 6548 } 6549 6550 if (EHPadBB) { 6551 // Insert a label at the end of the invoke call to mark the try range. This 6552 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6553 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6554 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6555 6556 // Inform MachineModuleInfo of range. 6557 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6558 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6559 // actually use outlined funclets and their LSDA info style. 6560 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6561 assert(CLI.CS); 6562 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6563 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6564 BeginLabel, EndLabel); 6565 } else if (!isScopedEHPersonality(Pers)) { 6566 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6567 } 6568 } 6569 6570 return Result; 6571 } 6572 6573 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6574 bool isTailCall, 6575 const BasicBlock *EHPadBB) { 6576 auto &DL = DAG.getDataLayout(); 6577 FunctionType *FTy = CS.getFunctionType(); 6578 Type *RetTy = CS.getType(); 6579 6580 TargetLowering::ArgListTy Args; 6581 Args.reserve(CS.arg_size()); 6582 6583 const Value *SwiftErrorVal = nullptr; 6584 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6585 6586 // We can't tail call inside a function with a swifterror argument. Lowering 6587 // does not support this yet. It would have to move into the swifterror 6588 // register before the call. 6589 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6590 if (TLI.supportSwiftError() && 6591 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6592 isTailCall = false; 6593 6594 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6595 i != e; ++i) { 6596 TargetLowering::ArgListEntry Entry; 6597 const Value *V = *i; 6598 6599 // Skip empty types 6600 if (V->getType()->isEmptyTy()) 6601 continue; 6602 6603 SDValue ArgNode = getValue(V); 6604 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6605 6606 Entry.setAttributes(&CS, i - CS.arg_begin()); 6607 6608 // Use swifterror virtual register as input to the call. 6609 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6610 SwiftErrorVal = V; 6611 // We find the virtual register for the actual swifterror argument. 6612 // Instead of using the Value, we use the virtual register instead. 6613 Entry.Node = DAG.getRegister(FuncInfo 6614 .getOrCreateSwiftErrorVRegUseAt( 6615 CS.getInstruction(), FuncInfo.MBB, V) 6616 .first, 6617 EVT(TLI.getPointerTy(DL))); 6618 } 6619 6620 Args.push_back(Entry); 6621 6622 // If we have an explicit sret argument that is an Instruction, (i.e., it 6623 // might point to function-local memory), we can't meaningfully tail-call. 6624 if (Entry.IsSRet && isa<Instruction>(V)) 6625 isTailCall = false; 6626 } 6627 6628 // Check if target-independent constraints permit a tail call here. 6629 // Target-dependent constraints are checked within TLI->LowerCallTo. 6630 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6631 isTailCall = false; 6632 6633 // Disable tail calls if there is an swifterror argument. Targets have not 6634 // been updated to support tail calls. 6635 if (TLI.supportSwiftError() && SwiftErrorVal) 6636 isTailCall = false; 6637 6638 TargetLowering::CallLoweringInfo CLI(DAG); 6639 CLI.setDebugLoc(getCurSDLoc()) 6640 .setChain(getRoot()) 6641 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6642 .setTailCall(isTailCall) 6643 .setConvergent(CS.isConvergent()); 6644 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6645 6646 if (Result.first.getNode()) { 6647 const Instruction *Inst = CS.getInstruction(); 6648 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6649 setValue(Inst, Result.first); 6650 } 6651 6652 // The last element of CLI.InVals has the SDValue for swifterror return. 6653 // Here we copy it to a virtual register and update SwiftErrorMap for 6654 // book-keeping. 6655 if (SwiftErrorVal && TLI.supportSwiftError()) { 6656 // Get the last element of InVals. 6657 SDValue Src = CLI.InVals.back(); 6658 unsigned VReg; bool CreatedVReg; 6659 std::tie(VReg, CreatedVReg) = 6660 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6661 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6662 // We update the virtual register for the actual swifterror argument. 6663 if (CreatedVReg) 6664 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6665 DAG.setRoot(CopyNode); 6666 } 6667 } 6668 6669 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6670 SelectionDAGBuilder &Builder) { 6671 // Check to see if this load can be trivially constant folded, e.g. if the 6672 // input is from a string literal. 6673 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6674 // Cast pointer to the type we really want to load. 6675 Type *LoadTy = 6676 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6677 if (LoadVT.isVector()) 6678 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6679 6680 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6681 PointerType::getUnqual(LoadTy)); 6682 6683 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6684 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6685 return Builder.getValue(LoadCst); 6686 } 6687 6688 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6689 // still constant memory, the input chain can be the entry node. 6690 SDValue Root; 6691 bool ConstantMemory = false; 6692 6693 // Do not serialize (non-volatile) loads of constant memory with anything. 6694 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6695 Root = Builder.DAG.getEntryNode(); 6696 ConstantMemory = true; 6697 } else { 6698 // Do not serialize non-volatile loads against each other. 6699 Root = Builder.DAG.getRoot(); 6700 } 6701 6702 SDValue Ptr = Builder.getValue(PtrVal); 6703 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6704 Ptr, MachinePointerInfo(PtrVal), 6705 /* Alignment = */ 1); 6706 6707 if (!ConstantMemory) 6708 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6709 return LoadVal; 6710 } 6711 6712 /// Record the value for an instruction that produces an integer result, 6713 /// converting the type where necessary. 6714 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6715 SDValue Value, 6716 bool IsSigned) { 6717 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6718 I.getType(), true); 6719 if (IsSigned) 6720 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6721 else 6722 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6723 setValue(&I, Value); 6724 } 6725 6726 /// See if we can lower a memcmp call into an optimized form. If so, return 6727 /// true and lower it. Otherwise return false, and it will be lowered like a 6728 /// normal call. 6729 /// The caller already checked that \p I calls the appropriate LibFunc with a 6730 /// correct prototype. 6731 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6732 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6733 const Value *Size = I.getArgOperand(2); 6734 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6735 if (CSize && CSize->getZExtValue() == 0) { 6736 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6737 I.getType(), true); 6738 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6739 return true; 6740 } 6741 6742 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6743 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6744 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6745 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6746 if (Res.first.getNode()) { 6747 processIntegerCallValue(I, Res.first, true); 6748 PendingLoads.push_back(Res.second); 6749 return true; 6750 } 6751 6752 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6753 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6754 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6755 return false; 6756 6757 // If the target has a fast compare for the given size, it will return a 6758 // preferred load type for that size. Require that the load VT is legal and 6759 // that the target supports unaligned loads of that type. Otherwise, return 6760 // INVALID. 6761 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6762 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6763 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6764 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6765 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6766 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6767 // TODO: Check alignment of src and dest ptrs. 6768 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6769 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6770 if (!TLI.isTypeLegal(LVT) || 6771 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6772 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6773 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6774 } 6775 6776 return LVT; 6777 }; 6778 6779 // This turns into unaligned loads. We only do this if the target natively 6780 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6781 // we'll only produce a small number of byte loads. 6782 MVT LoadVT; 6783 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6784 switch (NumBitsToCompare) { 6785 default: 6786 return false; 6787 case 16: 6788 LoadVT = MVT::i16; 6789 break; 6790 case 32: 6791 LoadVT = MVT::i32; 6792 break; 6793 case 64: 6794 case 128: 6795 case 256: 6796 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6797 break; 6798 } 6799 6800 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6801 return false; 6802 6803 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6804 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6805 6806 // Bitcast to a wide integer type if the loads are vectors. 6807 if (LoadVT.isVector()) { 6808 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6809 LoadL = DAG.getBitcast(CmpVT, LoadL); 6810 LoadR = DAG.getBitcast(CmpVT, LoadR); 6811 } 6812 6813 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6814 processIntegerCallValue(I, Cmp, false); 6815 return true; 6816 } 6817 6818 /// See if we can lower a memchr call into an optimized form. If so, return 6819 /// true and lower it. Otherwise return false, and it will be lowered like a 6820 /// normal call. 6821 /// The caller already checked that \p I calls the appropriate LibFunc with a 6822 /// correct prototype. 6823 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6824 const Value *Src = I.getArgOperand(0); 6825 const Value *Char = I.getArgOperand(1); 6826 const Value *Length = I.getArgOperand(2); 6827 6828 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6829 std::pair<SDValue, SDValue> Res = 6830 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6831 getValue(Src), getValue(Char), getValue(Length), 6832 MachinePointerInfo(Src)); 6833 if (Res.first.getNode()) { 6834 setValue(&I, Res.first); 6835 PendingLoads.push_back(Res.second); 6836 return true; 6837 } 6838 6839 return false; 6840 } 6841 6842 /// See if we can lower a mempcpy call into an optimized form. If so, return 6843 /// true and lower it. Otherwise return false, and it will be lowered like a 6844 /// normal call. 6845 /// The caller already checked that \p I calls the appropriate LibFunc with a 6846 /// correct prototype. 6847 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6848 SDValue Dst = getValue(I.getArgOperand(0)); 6849 SDValue Src = getValue(I.getArgOperand(1)); 6850 SDValue Size = getValue(I.getArgOperand(2)); 6851 6852 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6853 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6854 unsigned Align = std::min(DstAlign, SrcAlign); 6855 if (Align == 0) // Alignment of one or both could not be inferred. 6856 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6857 6858 bool isVol = false; 6859 SDLoc sdl = getCurSDLoc(); 6860 6861 // In the mempcpy context we need to pass in a false value for isTailCall 6862 // because the return pointer needs to be adjusted by the size of 6863 // the copied memory. 6864 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6865 false, /*isTailCall=*/false, 6866 MachinePointerInfo(I.getArgOperand(0)), 6867 MachinePointerInfo(I.getArgOperand(1))); 6868 assert(MC.getNode() != nullptr && 6869 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6870 DAG.setRoot(MC); 6871 6872 // Check if Size needs to be truncated or extended. 6873 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6874 6875 // Adjust return pointer to point just past the last dst byte. 6876 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6877 Dst, Size); 6878 setValue(&I, DstPlusSize); 6879 return true; 6880 } 6881 6882 /// See if we can lower a strcpy call into an optimized form. If so, return 6883 /// true and lower it, otherwise return false and it will be lowered like a 6884 /// normal call. 6885 /// The caller already checked that \p I calls the appropriate LibFunc with a 6886 /// correct prototype. 6887 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6888 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6889 6890 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6891 std::pair<SDValue, SDValue> Res = 6892 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6893 getValue(Arg0), getValue(Arg1), 6894 MachinePointerInfo(Arg0), 6895 MachinePointerInfo(Arg1), isStpcpy); 6896 if (Res.first.getNode()) { 6897 setValue(&I, Res.first); 6898 DAG.setRoot(Res.second); 6899 return true; 6900 } 6901 6902 return false; 6903 } 6904 6905 /// See if we can lower a strcmp call into an optimized form. If so, return 6906 /// true and lower it, otherwise return false and it will be lowered like a 6907 /// normal call. 6908 /// The caller already checked that \p I calls the appropriate LibFunc with a 6909 /// correct prototype. 6910 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6911 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6912 6913 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6914 std::pair<SDValue, SDValue> Res = 6915 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6916 getValue(Arg0), getValue(Arg1), 6917 MachinePointerInfo(Arg0), 6918 MachinePointerInfo(Arg1)); 6919 if (Res.first.getNode()) { 6920 processIntegerCallValue(I, Res.first, true); 6921 PendingLoads.push_back(Res.second); 6922 return true; 6923 } 6924 6925 return false; 6926 } 6927 6928 /// See if we can lower a strlen call into an optimized form. If so, return 6929 /// true and lower it, otherwise return false and it will be lowered like a 6930 /// normal call. 6931 /// The caller already checked that \p I calls the appropriate LibFunc with a 6932 /// correct prototype. 6933 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6934 const Value *Arg0 = I.getArgOperand(0); 6935 6936 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6937 std::pair<SDValue, SDValue> Res = 6938 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6939 getValue(Arg0), 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 strnlen call into an optimized form. If so, return 6950 /// true and lower it, otherwise return false and it will be lowered like a 6951 /// normal call. 6952 /// The caller already checked that \p I calls the appropriate LibFunc with a 6953 /// correct prototype. 6954 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6955 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6956 6957 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6958 std::pair<SDValue, SDValue> Res = 6959 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6960 getValue(Arg0), getValue(Arg1), 6961 MachinePointerInfo(Arg0)); 6962 if (Res.first.getNode()) { 6963 processIntegerCallValue(I, Res.first, false); 6964 PendingLoads.push_back(Res.second); 6965 return true; 6966 } 6967 6968 return false; 6969 } 6970 6971 /// See if we can lower a unary floating-point operation into an SDNode with 6972 /// the specified Opcode. If so, return true and lower it, otherwise return 6973 /// false and it will be lowered like a normal call. 6974 /// The caller already checked that \p I calls the appropriate LibFunc with a 6975 /// correct prototype. 6976 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6977 unsigned Opcode) { 6978 // We already checked this call's prototype; verify it doesn't modify errno. 6979 if (!I.onlyReadsMemory()) 6980 return false; 6981 6982 SDValue Tmp = getValue(I.getArgOperand(0)); 6983 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6984 return true; 6985 } 6986 6987 /// See if we can lower a binary floating-point operation into an SDNode with 6988 /// the specified Opcode. If so, return true and lower it. Otherwise return 6989 /// false, and it will be lowered like a normal call. 6990 /// The caller already checked that \p I calls the appropriate LibFunc with a 6991 /// correct prototype. 6992 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6993 unsigned Opcode) { 6994 // We already checked this call's prototype; verify it doesn't modify errno. 6995 if (!I.onlyReadsMemory()) 6996 return false; 6997 6998 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6999 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7000 EVT VT = Tmp0.getValueType(); 7001 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7002 return true; 7003 } 7004 7005 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7006 // Handle inline assembly differently. 7007 if (isa<InlineAsm>(I.getCalledValue())) { 7008 visitInlineAsm(&I); 7009 return; 7010 } 7011 7012 const char *RenameFn = nullptr; 7013 if (Function *F = I.getCalledFunction()) { 7014 if (F->isDeclaration()) { 7015 // Is this an LLVM intrinsic or a target-specific intrinsic? 7016 unsigned IID = F->getIntrinsicID(); 7017 if (!IID) 7018 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7019 IID = II->getIntrinsicID(F); 7020 7021 if (IID) { 7022 RenameFn = visitIntrinsicCall(I, IID); 7023 if (!RenameFn) 7024 return; 7025 } 7026 } 7027 7028 // Check for well-known libc/libm calls. If the function is internal, it 7029 // can't be a library call. Don't do the check if marked as nobuiltin for 7030 // some reason or the call site requires strict floating point semantics. 7031 LibFunc Func; 7032 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7033 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7034 LibInfo->hasOptimizedCodeGen(Func)) { 7035 switch (Func) { 7036 default: break; 7037 case LibFunc_copysign: 7038 case LibFunc_copysignf: 7039 case LibFunc_copysignl: 7040 // We already checked this call's prototype; verify it doesn't modify 7041 // errno. 7042 if (I.onlyReadsMemory()) { 7043 SDValue LHS = getValue(I.getArgOperand(0)); 7044 SDValue RHS = getValue(I.getArgOperand(1)); 7045 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7046 LHS.getValueType(), LHS, RHS)); 7047 return; 7048 } 7049 break; 7050 case LibFunc_fabs: 7051 case LibFunc_fabsf: 7052 case LibFunc_fabsl: 7053 if (visitUnaryFloatCall(I, ISD::FABS)) 7054 return; 7055 break; 7056 case LibFunc_fmin: 7057 case LibFunc_fminf: 7058 case LibFunc_fminl: 7059 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7060 return; 7061 break; 7062 case LibFunc_fmax: 7063 case LibFunc_fmaxf: 7064 case LibFunc_fmaxl: 7065 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7066 return; 7067 break; 7068 case LibFunc_sin: 7069 case LibFunc_sinf: 7070 case LibFunc_sinl: 7071 if (visitUnaryFloatCall(I, ISD::FSIN)) 7072 return; 7073 break; 7074 case LibFunc_cos: 7075 case LibFunc_cosf: 7076 case LibFunc_cosl: 7077 if (visitUnaryFloatCall(I, ISD::FCOS)) 7078 return; 7079 break; 7080 case LibFunc_sqrt: 7081 case LibFunc_sqrtf: 7082 case LibFunc_sqrtl: 7083 case LibFunc_sqrt_finite: 7084 case LibFunc_sqrtf_finite: 7085 case LibFunc_sqrtl_finite: 7086 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7087 return; 7088 break; 7089 case LibFunc_floor: 7090 case LibFunc_floorf: 7091 case LibFunc_floorl: 7092 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7093 return; 7094 break; 7095 case LibFunc_nearbyint: 7096 case LibFunc_nearbyintf: 7097 case LibFunc_nearbyintl: 7098 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7099 return; 7100 break; 7101 case LibFunc_ceil: 7102 case LibFunc_ceilf: 7103 case LibFunc_ceill: 7104 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7105 return; 7106 break; 7107 case LibFunc_rint: 7108 case LibFunc_rintf: 7109 case LibFunc_rintl: 7110 if (visitUnaryFloatCall(I, ISD::FRINT)) 7111 return; 7112 break; 7113 case LibFunc_round: 7114 case LibFunc_roundf: 7115 case LibFunc_roundl: 7116 if (visitUnaryFloatCall(I, ISD::FROUND)) 7117 return; 7118 break; 7119 case LibFunc_trunc: 7120 case LibFunc_truncf: 7121 case LibFunc_truncl: 7122 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7123 return; 7124 break; 7125 case LibFunc_log2: 7126 case LibFunc_log2f: 7127 case LibFunc_log2l: 7128 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7129 return; 7130 break; 7131 case LibFunc_exp2: 7132 case LibFunc_exp2f: 7133 case LibFunc_exp2l: 7134 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7135 return; 7136 break; 7137 case LibFunc_memcmp: 7138 if (visitMemCmpCall(I)) 7139 return; 7140 break; 7141 case LibFunc_mempcpy: 7142 if (visitMemPCpyCall(I)) 7143 return; 7144 break; 7145 case LibFunc_memchr: 7146 if (visitMemChrCall(I)) 7147 return; 7148 break; 7149 case LibFunc_strcpy: 7150 if (visitStrCpyCall(I, false)) 7151 return; 7152 break; 7153 case LibFunc_stpcpy: 7154 if (visitStrCpyCall(I, true)) 7155 return; 7156 break; 7157 case LibFunc_strcmp: 7158 if (visitStrCmpCall(I)) 7159 return; 7160 break; 7161 case LibFunc_strlen: 7162 if (visitStrLenCall(I)) 7163 return; 7164 break; 7165 case LibFunc_strnlen: 7166 if (visitStrNLenCall(I)) 7167 return; 7168 break; 7169 } 7170 } 7171 } 7172 7173 SDValue Callee; 7174 if (!RenameFn) 7175 Callee = getValue(I.getCalledValue()); 7176 else 7177 Callee = DAG.getExternalSymbol( 7178 RenameFn, 7179 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7180 7181 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7182 // have to do anything here to lower funclet bundles. 7183 assert(!I.hasOperandBundlesOtherThan( 7184 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7185 "Cannot lower calls with arbitrary operand bundles!"); 7186 7187 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7188 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7189 else 7190 // Check if we can potentially perform a tail call. More detailed checking 7191 // is be done within LowerCallTo, after more information about the call is 7192 // known. 7193 LowerCallTo(&I, Callee, I.isTailCall()); 7194 } 7195 7196 namespace { 7197 7198 /// AsmOperandInfo - This contains information for each constraint that we are 7199 /// lowering. 7200 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7201 public: 7202 /// CallOperand - If this is the result output operand or a clobber 7203 /// this is null, otherwise it is the incoming operand to the CallInst. 7204 /// This gets modified as the asm is processed. 7205 SDValue CallOperand; 7206 7207 /// AssignedRegs - If this is a register or register class operand, this 7208 /// contains the set of register corresponding to the operand. 7209 RegsForValue AssignedRegs; 7210 7211 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7212 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7213 } 7214 7215 /// Whether or not this operand accesses memory 7216 bool hasMemory(const TargetLowering &TLI) const { 7217 // Indirect operand accesses access memory. 7218 if (isIndirect) 7219 return true; 7220 7221 for (const auto &Code : Codes) 7222 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7223 return true; 7224 7225 return false; 7226 } 7227 7228 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7229 /// corresponds to. If there is no Value* for this operand, it returns 7230 /// MVT::Other. 7231 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7232 const DataLayout &DL) const { 7233 if (!CallOperandVal) return MVT::Other; 7234 7235 if (isa<BasicBlock>(CallOperandVal)) 7236 return TLI.getPointerTy(DL); 7237 7238 llvm::Type *OpTy = CallOperandVal->getType(); 7239 7240 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7241 // If this is an indirect operand, the operand is a pointer to the 7242 // accessed type. 7243 if (isIndirect) { 7244 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7245 if (!PtrTy) 7246 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7247 OpTy = PtrTy->getElementType(); 7248 } 7249 7250 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7251 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7252 if (STy->getNumElements() == 1) 7253 OpTy = STy->getElementType(0); 7254 7255 // If OpTy is not a single value, it may be a struct/union that we 7256 // can tile with integers. 7257 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7258 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7259 switch (BitSize) { 7260 default: break; 7261 case 1: 7262 case 8: 7263 case 16: 7264 case 32: 7265 case 64: 7266 case 128: 7267 OpTy = IntegerType::get(Context, BitSize); 7268 break; 7269 } 7270 } 7271 7272 return TLI.getValueType(DL, OpTy, true); 7273 } 7274 }; 7275 7276 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7277 7278 } // end anonymous namespace 7279 7280 /// Make sure that the output operand \p OpInfo and its corresponding input 7281 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7282 /// out). 7283 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7284 SDISelAsmOperandInfo &MatchingOpInfo, 7285 SelectionDAG &DAG) { 7286 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7287 return; 7288 7289 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7290 const auto &TLI = DAG.getTargetLoweringInfo(); 7291 7292 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7293 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7294 OpInfo.ConstraintVT); 7295 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7296 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7297 MatchingOpInfo.ConstraintVT); 7298 if ((OpInfo.ConstraintVT.isInteger() != 7299 MatchingOpInfo.ConstraintVT.isInteger()) || 7300 (MatchRC.second != InputRC.second)) { 7301 // FIXME: error out in a more elegant fashion 7302 report_fatal_error("Unsupported asm: input constraint" 7303 " with a matching output constraint of" 7304 " incompatible type!"); 7305 } 7306 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7307 } 7308 7309 /// Get a direct memory input to behave well as an indirect operand. 7310 /// This may introduce stores, hence the need for a \p Chain. 7311 /// \return The (possibly updated) chain. 7312 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7313 SDISelAsmOperandInfo &OpInfo, 7314 SelectionDAG &DAG) { 7315 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7316 7317 // If we don't have an indirect input, put it in the constpool if we can, 7318 // otherwise spill it to a stack slot. 7319 // TODO: This isn't quite right. We need to handle these according to 7320 // the addressing mode that the constraint wants. Also, this may take 7321 // an additional register for the computation and we don't want that 7322 // either. 7323 7324 // If the operand is a float, integer, or vector constant, spill to a 7325 // constant pool entry to get its address. 7326 const Value *OpVal = OpInfo.CallOperandVal; 7327 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7328 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7329 OpInfo.CallOperand = DAG.getConstantPool( 7330 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7331 return Chain; 7332 } 7333 7334 // Otherwise, create a stack slot and emit a store to it before the asm. 7335 Type *Ty = OpVal->getType(); 7336 auto &DL = DAG.getDataLayout(); 7337 uint64_t TySize = DL.getTypeAllocSize(Ty); 7338 unsigned Align = DL.getPrefTypeAlignment(Ty); 7339 MachineFunction &MF = DAG.getMachineFunction(); 7340 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7341 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7342 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7343 MachinePointerInfo::getFixedStack(MF, SSFI)); 7344 OpInfo.CallOperand = StackSlot; 7345 7346 return Chain; 7347 } 7348 7349 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7350 /// specified operand. We prefer to assign virtual registers, to allow the 7351 /// register allocator to handle the assignment process. However, if the asm 7352 /// uses features that we can't model on machineinstrs, we have SDISel do the 7353 /// allocation. This produces generally horrible, but correct, code. 7354 /// 7355 /// OpInfo describes the operand 7356 /// RefOpInfo describes the matching operand if any, the operand otherwise 7357 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7358 SDISelAsmOperandInfo &OpInfo, 7359 SDISelAsmOperandInfo &RefOpInfo) { 7360 LLVMContext &Context = *DAG.getContext(); 7361 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7362 7363 MachineFunction &MF = DAG.getMachineFunction(); 7364 SmallVector<unsigned, 4> Regs; 7365 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7366 7367 // No work to do for memory operations. 7368 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7369 return; 7370 7371 // If this is a constraint for a single physreg, or a constraint for a 7372 // register class, find it. 7373 unsigned AssignedReg; 7374 const TargetRegisterClass *RC; 7375 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7376 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7377 // RC is unset only on failure. Return immediately. 7378 if (!RC) 7379 return; 7380 7381 // Get the actual register value type. This is important, because the user 7382 // may have asked for (e.g.) the AX register in i32 type. We need to 7383 // remember that AX is actually i16 to get the right extension. 7384 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7385 7386 if (OpInfo.ConstraintVT != MVT::Other) { 7387 // If this is an FP operand in an integer register (or visa versa), or more 7388 // generally if the operand value disagrees with the register class we plan 7389 // to stick it in, fix the operand type. 7390 // 7391 // If this is an input value, the bitcast to the new type is done now. 7392 // Bitcast for output value is done at the end of visitInlineAsm(). 7393 if ((OpInfo.Type == InlineAsm::isOutput || 7394 OpInfo.Type == InlineAsm::isInput) && 7395 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7396 // Try to convert to the first EVT that the reg class contains. If the 7397 // types are identical size, use a bitcast to convert (e.g. two differing 7398 // vector types). Note: output bitcast is done at the end of 7399 // visitInlineAsm(). 7400 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7401 // Exclude indirect inputs while they are unsupported because the code 7402 // to perform the load is missing and thus OpInfo.CallOperand still 7403 // refers to the input address rather than the pointed-to value. 7404 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7405 OpInfo.CallOperand = 7406 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7407 OpInfo.ConstraintVT = RegVT; 7408 // If the operand is an FP value and we want it in integer registers, 7409 // use the corresponding integer type. This turns an f64 value into 7410 // i64, which can be passed with two i32 values on a 32-bit machine. 7411 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7412 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7413 if (OpInfo.Type == InlineAsm::isInput) 7414 OpInfo.CallOperand = 7415 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7416 OpInfo.ConstraintVT = VT; 7417 } 7418 } 7419 } 7420 7421 // No need to allocate a matching input constraint since the constraint it's 7422 // matching to has already been allocated. 7423 if (OpInfo.isMatchingInputConstraint()) 7424 return; 7425 7426 EVT ValueVT = OpInfo.ConstraintVT; 7427 if (OpInfo.ConstraintVT == MVT::Other) 7428 ValueVT = RegVT; 7429 7430 // Initialize NumRegs. 7431 unsigned NumRegs = 1; 7432 if (OpInfo.ConstraintVT != MVT::Other) 7433 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7434 7435 // If this is a constraint for a specific physical register, like {r17}, 7436 // assign it now. 7437 7438 // If this associated to a specific register, initialize iterator to correct 7439 // place. If virtual, make sure we have enough registers 7440 7441 // Initialize iterator if necessary 7442 TargetRegisterClass::iterator I = RC->begin(); 7443 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7444 7445 // Do not check for single registers. 7446 if (AssignedReg) { 7447 for (; *I != AssignedReg; ++I) 7448 assert(I != RC->end() && "AssignedReg should be member of RC"); 7449 } 7450 7451 for (; NumRegs; --NumRegs, ++I) { 7452 assert(I != RC->end() && "Ran out of registers to allocate!"); 7453 auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC); 7454 Regs.push_back(R); 7455 } 7456 7457 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7458 } 7459 7460 static unsigned 7461 findMatchingInlineAsmOperand(unsigned OperandNo, 7462 const std::vector<SDValue> &AsmNodeOperands) { 7463 // Scan until we find the definition we already emitted of this operand. 7464 unsigned CurOp = InlineAsm::Op_FirstOperand; 7465 for (; OperandNo; --OperandNo) { 7466 // Advance to the next operand. 7467 unsigned OpFlag = 7468 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7469 assert((InlineAsm::isRegDefKind(OpFlag) || 7470 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7471 InlineAsm::isMemKind(OpFlag)) && 7472 "Skipped past definitions?"); 7473 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7474 } 7475 return CurOp; 7476 } 7477 7478 namespace { 7479 7480 class ExtraFlags { 7481 unsigned Flags = 0; 7482 7483 public: 7484 explicit ExtraFlags(ImmutableCallSite CS) { 7485 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7486 if (IA->hasSideEffects()) 7487 Flags |= InlineAsm::Extra_HasSideEffects; 7488 if (IA->isAlignStack()) 7489 Flags |= InlineAsm::Extra_IsAlignStack; 7490 if (CS.isConvergent()) 7491 Flags |= InlineAsm::Extra_IsConvergent; 7492 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7493 } 7494 7495 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7496 // Ideally, we would only check against memory constraints. However, the 7497 // meaning of an Other constraint can be target-specific and we can't easily 7498 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7499 // for Other constraints as well. 7500 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7501 OpInfo.ConstraintType == TargetLowering::C_Other) { 7502 if (OpInfo.Type == InlineAsm::isInput) 7503 Flags |= InlineAsm::Extra_MayLoad; 7504 else if (OpInfo.Type == InlineAsm::isOutput) 7505 Flags |= InlineAsm::Extra_MayStore; 7506 else if (OpInfo.Type == InlineAsm::isClobber) 7507 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7508 } 7509 } 7510 7511 unsigned get() const { return Flags; } 7512 }; 7513 7514 } // end anonymous namespace 7515 7516 /// visitInlineAsm - Handle a call to an InlineAsm object. 7517 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7518 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7519 7520 /// ConstraintOperands - Information about all of the constraints. 7521 SDISelAsmOperandInfoVector ConstraintOperands; 7522 7523 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7524 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7525 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7526 7527 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7528 // AsmDialect, MayLoad, MayStore). 7529 bool HasSideEffect = IA->hasSideEffects(); 7530 ExtraFlags ExtraInfo(CS); 7531 7532 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7533 unsigned ResNo = 0; // ResNo - The result number of the next output. 7534 for (auto &T : TargetConstraints) { 7535 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7536 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7537 7538 // Compute the value type for each operand. 7539 if (OpInfo.Type == InlineAsm::isInput || 7540 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7541 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7542 7543 // Process the call argument. BasicBlocks are labels, currently appearing 7544 // only in asm's. 7545 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7546 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7547 } else { 7548 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7549 } 7550 7551 OpInfo.ConstraintVT = 7552 OpInfo 7553 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7554 .getSimpleVT(); 7555 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7556 // The return value of the call is this value. As such, there is no 7557 // corresponding argument. 7558 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7559 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7560 OpInfo.ConstraintVT = TLI.getSimpleValueType( 7561 DAG.getDataLayout(), STy->getElementType(ResNo)); 7562 } else { 7563 assert(ResNo == 0 && "Asm only has one result!"); 7564 OpInfo.ConstraintVT = 7565 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7566 } 7567 ++ResNo; 7568 } else { 7569 OpInfo.ConstraintVT = MVT::Other; 7570 } 7571 7572 if (!HasSideEffect) 7573 HasSideEffect = OpInfo.hasMemory(TLI); 7574 7575 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7576 // FIXME: Could we compute this on OpInfo rather than T? 7577 7578 // Compute the constraint code and ConstraintType to use. 7579 TLI.ComputeConstraintToUse(T, SDValue()); 7580 7581 ExtraInfo.update(T); 7582 } 7583 7584 // We won't need to flush pending loads if this asm doesn't touch 7585 // memory and is nonvolatile. 7586 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 7587 7588 // Second pass over the constraints: compute which constraint option to use. 7589 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7590 // If this is an output operand with a matching input operand, look up the 7591 // matching input. If their types mismatch, e.g. one is an integer, the 7592 // other is floating point, or their sizes are different, flag it as an 7593 // error. 7594 if (OpInfo.hasMatchingInput()) { 7595 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7596 patchMatchingInput(OpInfo, Input, DAG); 7597 } 7598 7599 // Compute the constraint code and ConstraintType to use. 7600 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7601 7602 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7603 OpInfo.Type == InlineAsm::isClobber) 7604 continue; 7605 7606 // If this is a memory input, and if the operand is not indirect, do what we 7607 // need to provide an address for the memory input. 7608 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7609 !OpInfo.isIndirect) { 7610 assert((OpInfo.isMultipleAlternative || 7611 (OpInfo.Type == InlineAsm::isInput)) && 7612 "Can only indirectify direct input operands!"); 7613 7614 // Memory operands really want the address of the value. 7615 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7616 7617 // There is no longer a Value* corresponding to this operand. 7618 OpInfo.CallOperandVal = nullptr; 7619 7620 // It is now an indirect operand. 7621 OpInfo.isIndirect = true; 7622 } 7623 7624 } 7625 7626 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7627 std::vector<SDValue> AsmNodeOperands; 7628 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7629 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7630 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7631 7632 // If we have a !srcloc metadata node associated with it, we want to attach 7633 // this to the ultimately generated inline asm machineinstr. To do this, we 7634 // pass in the third operand as this (potentially null) inline asm MDNode. 7635 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7636 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7637 7638 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7639 // bits as operand 3. 7640 AsmNodeOperands.push_back(DAG.getTargetConstant( 7641 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7642 7643 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 7644 // this, assign virtual and physical registers for inputs and otput. 7645 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7646 // Assign Registers. 7647 SDISelAsmOperandInfo &RefOpInfo = 7648 OpInfo.isMatchingInputConstraint() 7649 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7650 : OpInfo; 7651 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 7652 7653 switch (OpInfo.Type) { 7654 case InlineAsm::isOutput: 7655 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 7656 OpInfo.ConstraintType != TargetLowering::C_Register) { 7657 // Memory output, or 'other' output (e.g. 'X' constraint). 7658 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 7659 7660 unsigned ConstraintID = 7661 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7662 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7663 "Failed to convert memory constraint code to constraint id."); 7664 7665 // Add information to the INLINEASM node to know about this output. 7666 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7667 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7668 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7669 MVT::i32)); 7670 AsmNodeOperands.push_back(OpInfo.CallOperand); 7671 break; 7672 } else if (OpInfo.ConstraintType == TargetLowering::C_Register || 7673 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 7674 // Otherwise, this is a register or register class output. 7675 7676 // Copy the output from the appropriate register. Find a register that 7677 // we can use. 7678 if (OpInfo.AssignedRegs.Regs.empty()) { 7679 emitInlineAsmError( 7680 CS, "couldn't allocate output register for constraint '" + 7681 Twine(OpInfo.ConstraintCode) + "'"); 7682 return; 7683 } 7684 7685 // Add information to the INLINEASM node to know that this register is 7686 // set. 7687 OpInfo.AssignedRegs.AddInlineAsmOperands( 7688 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 7689 : InlineAsm::Kind_RegDef, 7690 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7691 } 7692 break; 7693 7694 case InlineAsm::isInput: { 7695 SDValue InOperandVal = OpInfo.CallOperand; 7696 7697 if (OpInfo.isMatchingInputConstraint()) { 7698 // If this is required to match an output register we have already set, 7699 // just use its register. 7700 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7701 AsmNodeOperands); 7702 unsigned OpFlag = 7703 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7704 if (InlineAsm::isRegDefKind(OpFlag) || 7705 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7706 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7707 if (OpInfo.isIndirect) { 7708 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7709 emitInlineAsmError(CS, "inline asm not supported yet:" 7710 " don't know how to handle tied " 7711 "indirect register inputs"); 7712 return; 7713 } 7714 7715 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7716 SmallVector<unsigned, 4> Regs; 7717 7718 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 7719 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 7720 MachineRegisterInfo &RegInfo = 7721 DAG.getMachineFunction().getRegInfo(); 7722 for (unsigned i = 0; i != NumRegs; ++i) 7723 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7724 } else { 7725 emitInlineAsmError(CS, "inline asm error: This value type register " 7726 "class is not natively supported!"); 7727 return; 7728 } 7729 7730 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7731 7732 SDLoc dl = getCurSDLoc(); 7733 // Use the produced MatchedRegs object to 7734 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7735 CS.getInstruction()); 7736 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7737 true, OpInfo.getMatchedOperand(), dl, 7738 DAG, AsmNodeOperands); 7739 break; 7740 } 7741 7742 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7743 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7744 "Unexpected number of operands"); 7745 // Add information to the INLINEASM node to know about this input. 7746 // See InlineAsm.h isUseOperandTiedToDef. 7747 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7748 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7749 OpInfo.getMatchedOperand()); 7750 AsmNodeOperands.push_back(DAG.getTargetConstant( 7751 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7752 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7753 break; 7754 } 7755 7756 // Treat indirect 'X' constraint as memory. 7757 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7758 OpInfo.isIndirect) 7759 OpInfo.ConstraintType = TargetLowering::C_Memory; 7760 7761 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7762 std::vector<SDValue> Ops; 7763 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7764 Ops, DAG); 7765 if (Ops.empty()) { 7766 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7767 Twine(OpInfo.ConstraintCode) + "'"); 7768 return; 7769 } 7770 7771 // Add information to the INLINEASM node to know about this input. 7772 unsigned ResOpType = 7773 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7774 AsmNodeOperands.push_back(DAG.getTargetConstant( 7775 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7776 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7777 break; 7778 } 7779 7780 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7781 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7782 assert(InOperandVal.getValueType() == 7783 TLI.getPointerTy(DAG.getDataLayout()) && 7784 "Memory operands expect pointer values"); 7785 7786 unsigned ConstraintID = 7787 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7788 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7789 "Failed to convert memory constraint code to constraint id."); 7790 7791 // Add information to the INLINEASM node to know about this input. 7792 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7793 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7794 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7795 getCurSDLoc(), 7796 MVT::i32)); 7797 AsmNodeOperands.push_back(InOperandVal); 7798 break; 7799 } 7800 7801 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7802 OpInfo.ConstraintType == TargetLowering::C_Register) && 7803 "Unknown constraint type!"); 7804 7805 // TODO: Support this. 7806 if (OpInfo.isIndirect) { 7807 emitInlineAsmError( 7808 CS, "Don't know how to handle indirect register inputs yet " 7809 "for constraint '" + 7810 Twine(OpInfo.ConstraintCode) + "'"); 7811 return; 7812 } 7813 7814 // Copy the input into the appropriate registers. 7815 if (OpInfo.AssignedRegs.Regs.empty()) { 7816 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7817 Twine(OpInfo.ConstraintCode) + "'"); 7818 return; 7819 } 7820 7821 SDLoc dl = getCurSDLoc(); 7822 7823 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7824 Chain, &Flag, CS.getInstruction()); 7825 7826 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7827 dl, DAG, AsmNodeOperands); 7828 break; 7829 } 7830 case InlineAsm::isClobber: 7831 // Add the clobbered value to the operand list, so that the register 7832 // allocator is aware that the physreg got clobbered. 7833 if (!OpInfo.AssignedRegs.Regs.empty()) 7834 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7835 false, 0, getCurSDLoc(), DAG, 7836 AsmNodeOperands); 7837 break; 7838 } 7839 } 7840 7841 // Finish up input operands. Set the input chain and add the flag last. 7842 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7843 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7844 7845 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7846 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7847 Flag = Chain.getValue(1); 7848 7849 // Do additional work to generate outputs. 7850 7851 SmallVector<EVT, 1> ResultVTs; 7852 SmallVector<SDValue, 1> ResultValues; 7853 SmallVector<SDValue, 8> OutChains; 7854 7855 llvm::Type *CSResultType = CS.getType(); 7856 unsigned NumReturns = 0; 7857 ArrayRef<Type *> ResultTypes; 7858 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) { 7859 NumReturns = StructResult->getNumElements(); 7860 ResultTypes = StructResult->elements(); 7861 } else if (!CSResultType->isVoidTy()) { 7862 NumReturns = 1; 7863 ResultTypes = makeArrayRef(CSResultType); 7864 } 7865 7866 auto CurResultType = ResultTypes.begin(); 7867 auto handleRegAssign = [&](SDValue V) { 7868 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 7869 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 7870 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 7871 ++CurResultType; 7872 // If the type of the inline asm call site return value is different but has 7873 // same size as the type of the asm output bitcast it. One example of this 7874 // is for vectors with different width / number of elements. This can 7875 // happen for register classes that can contain multiple different value 7876 // types. The preg or vreg allocated may not have the same VT as was 7877 // expected. 7878 // 7879 // This can also happen for a return value that disagrees with the register 7880 // class it is put in, eg. a double in a general-purpose register on a 7881 // 32-bit machine. 7882 if (ResultVT != V.getValueType() && 7883 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 7884 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 7885 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 7886 V.getValueType().isInteger()) { 7887 // If a result value was tied to an input value, the computed result 7888 // may have a wider width than the expected result. Extract the 7889 // relevant portion. 7890 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 7891 } 7892 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 7893 ResultVTs.push_back(ResultVT); 7894 ResultValues.push_back(V); 7895 }; 7896 7897 // Deal with assembly output fixups. 7898 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7899 if (OpInfo.Type == InlineAsm::isOutput && 7900 (OpInfo.ConstraintType == TargetLowering::C_Register || 7901 OpInfo.ConstraintType == TargetLowering::C_RegisterClass)) { 7902 if (OpInfo.isIndirect) { 7903 // Register indirect are manifest as stores. 7904 const RegsForValue &OutRegs = OpInfo.AssignedRegs; 7905 const Value *Ptr = OpInfo.CallOperandVal; 7906 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7907 Chain, &Flag, IA); 7908 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), OutVal, getValue(Ptr), 7909 MachinePointerInfo(Ptr)); 7910 OutChains.push_back(Val); 7911 } else { 7912 // generate CopyFromRegs to associated registers. 7913 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7914 SDValue Val = OpInfo.AssignedRegs.getCopyFromRegs( 7915 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 7916 if (Val.getOpcode() == ISD::MERGE_VALUES) { 7917 for (const SDValue &V : Val->op_values()) 7918 handleRegAssign(V); 7919 } else 7920 handleRegAssign(Val); 7921 } 7922 } 7923 } 7924 7925 // Set results. 7926 if (!ResultValues.empty()) { 7927 assert(CurResultType == ResultTypes.end() && 7928 "Mismatch in number of ResultTypes"); 7929 assert(ResultValues.size() == NumReturns && 7930 "Mismatch in number of output operands in asm result"); 7931 7932 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 7933 DAG.getVTList(ResultVTs), ResultValues); 7934 setValue(CS.getInstruction(), V); 7935 } 7936 7937 // Collect store chains. 7938 if (!OutChains.empty()) 7939 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7940 7941 // Only Update Root if inline assembly has a memory effect. 7942 if (ResultValues.empty() || HasSideEffect || !OutChains.empty()) 7943 DAG.setRoot(Chain); 7944 } 7945 7946 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 7947 const Twine &Message) { 7948 LLVMContext &Ctx = *DAG.getContext(); 7949 Ctx.emitError(CS.getInstruction(), Message); 7950 7951 // Make sure we leave the DAG in a valid state 7952 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7953 SmallVector<EVT, 1> ValueVTs; 7954 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 7955 7956 if (ValueVTs.empty()) 7957 return; 7958 7959 SmallVector<SDValue, 1> Ops; 7960 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 7961 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 7962 7963 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 7964 } 7965 7966 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 7967 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 7968 MVT::Other, getRoot(), 7969 getValue(I.getArgOperand(0)), 7970 DAG.getSrcValue(I.getArgOperand(0)))); 7971 } 7972 7973 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 7974 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7975 const DataLayout &DL = DAG.getDataLayout(); 7976 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7977 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 7978 DAG.getSrcValue(I.getOperand(0)), 7979 DL.getABITypeAlignment(I.getType())); 7980 setValue(&I, V); 7981 DAG.setRoot(V.getValue(1)); 7982 } 7983 7984 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 7985 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 7986 MVT::Other, getRoot(), 7987 getValue(I.getArgOperand(0)), 7988 DAG.getSrcValue(I.getArgOperand(0)))); 7989 } 7990 7991 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 7992 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 7993 MVT::Other, getRoot(), 7994 getValue(I.getArgOperand(0)), 7995 getValue(I.getArgOperand(1)), 7996 DAG.getSrcValue(I.getArgOperand(0)), 7997 DAG.getSrcValue(I.getArgOperand(1)))); 7998 } 7999 8000 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8001 const Instruction &I, 8002 SDValue Op) { 8003 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8004 if (!Range) 8005 return Op; 8006 8007 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8008 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 8009 return Op; 8010 8011 APInt Lo = CR.getUnsignedMin(); 8012 if (!Lo.isMinValue()) 8013 return Op; 8014 8015 APInt Hi = CR.getUnsignedMax(); 8016 unsigned Bits = std::max(Hi.getActiveBits(), 8017 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8018 8019 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8020 8021 SDLoc SL = getCurSDLoc(); 8022 8023 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8024 DAG.getValueType(SmallVT)); 8025 unsigned NumVals = Op.getNode()->getNumValues(); 8026 if (NumVals == 1) 8027 return ZExt; 8028 8029 SmallVector<SDValue, 4> Ops; 8030 8031 Ops.push_back(ZExt); 8032 for (unsigned I = 1; I != NumVals; ++I) 8033 Ops.push_back(Op.getValue(I)); 8034 8035 return DAG.getMergeValues(Ops, SL); 8036 } 8037 8038 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8039 /// the call being lowered. 8040 /// 8041 /// This is a helper for lowering intrinsics that follow a target calling 8042 /// convention or require stack pointer adjustment. Only a subset of the 8043 /// intrinsic's operands need to participate in the calling convention. 8044 void SelectionDAGBuilder::populateCallLoweringInfo( 8045 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 8046 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8047 bool IsPatchPoint) { 8048 TargetLowering::ArgListTy Args; 8049 Args.reserve(NumArgs); 8050 8051 // Populate the argument list. 8052 // Attributes for args start at offset 1, after the return attribute. 8053 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8054 ArgI != ArgE; ++ArgI) { 8055 const Value *V = CS->getOperand(ArgI); 8056 8057 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8058 8059 TargetLowering::ArgListEntry Entry; 8060 Entry.Node = getValue(V); 8061 Entry.Ty = V->getType(); 8062 Entry.setAttributes(&CS, ArgI); 8063 Args.push_back(Entry); 8064 } 8065 8066 CLI.setDebugLoc(getCurSDLoc()) 8067 .setChain(getRoot()) 8068 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 8069 .setDiscardResult(CS->use_empty()) 8070 .setIsPatchPoint(IsPatchPoint); 8071 } 8072 8073 /// Add a stack map intrinsic call's live variable operands to a stackmap 8074 /// or patchpoint target node's operand list. 8075 /// 8076 /// Constants are converted to TargetConstants purely as an optimization to 8077 /// avoid constant materialization and register allocation. 8078 /// 8079 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8080 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 8081 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8082 /// address materialization and register allocation, but may also be required 8083 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8084 /// alloca in the entry block, then the runtime may assume that the alloca's 8085 /// StackMap location can be read immediately after compilation and that the 8086 /// location is valid at any point during execution (this is similar to the 8087 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8088 /// only available in a register, then the runtime would need to trap when 8089 /// execution reaches the StackMap in order to read the alloca's location. 8090 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8091 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8092 SelectionDAGBuilder &Builder) { 8093 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8094 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8095 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8096 Ops.push_back( 8097 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8098 Ops.push_back( 8099 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8100 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8101 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8102 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8103 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8104 } else 8105 Ops.push_back(OpVal); 8106 } 8107 } 8108 8109 /// Lower llvm.experimental.stackmap directly to its target opcode. 8110 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8111 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8112 // [live variables...]) 8113 8114 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8115 8116 SDValue Chain, InFlag, Callee, NullPtr; 8117 SmallVector<SDValue, 32> Ops; 8118 8119 SDLoc DL = getCurSDLoc(); 8120 Callee = getValue(CI.getCalledValue()); 8121 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8122 8123 // The stackmap intrinsic only records the live variables (the arguemnts 8124 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8125 // intrinsic, this won't be lowered to a function call. This means we don't 8126 // have to worry about calling conventions and target specific lowering code. 8127 // Instead we perform the call lowering right here. 8128 // 8129 // chain, flag = CALLSEQ_START(chain, 0, 0) 8130 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8131 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8132 // 8133 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8134 InFlag = Chain.getValue(1); 8135 8136 // Add the <id> and <numBytes> constants. 8137 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8138 Ops.push_back(DAG.getTargetConstant( 8139 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8140 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8141 Ops.push_back(DAG.getTargetConstant( 8142 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8143 MVT::i32)); 8144 8145 // Push live variables for the stack map. 8146 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8147 8148 // We are not pushing any register mask info here on the operands list, 8149 // because the stackmap doesn't clobber anything. 8150 8151 // Push the chain and the glue flag. 8152 Ops.push_back(Chain); 8153 Ops.push_back(InFlag); 8154 8155 // Create the STACKMAP node. 8156 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8157 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8158 Chain = SDValue(SM, 0); 8159 InFlag = Chain.getValue(1); 8160 8161 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8162 8163 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8164 8165 // Set the root to the target-lowered call chain. 8166 DAG.setRoot(Chain); 8167 8168 // Inform the Frame Information that we have a stackmap in this function. 8169 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8170 } 8171 8172 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8173 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8174 const BasicBlock *EHPadBB) { 8175 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8176 // i32 <numBytes>, 8177 // i8* <target>, 8178 // i32 <numArgs>, 8179 // [Args...], 8180 // [live variables...]) 8181 8182 CallingConv::ID CC = CS.getCallingConv(); 8183 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8184 bool HasDef = !CS->getType()->isVoidTy(); 8185 SDLoc dl = getCurSDLoc(); 8186 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8187 8188 // Handle immediate and symbolic callees. 8189 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8190 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8191 /*isTarget=*/true); 8192 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8193 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8194 SDLoc(SymbolicCallee), 8195 SymbolicCallee->getValueType(0)); 8196 8197 // Get the real number of arguments participating in the call <numArgs> 8198 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8199 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8200 8201 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8202 // Intrinsics include all meta-operands up to but not including CC. 8203 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8204 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8205 "Not enough arguments provided to the patchpoint intrinsic"); 8206 8207 // For AnyRegCC the arguments are lowered later on manually. 8208 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8209 Type *ReturnTy = 8210 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8211 8212 TargetLowering::CallLoweringInfo CLI(DAG); 8213 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 8214 true); 8215 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8216 8217 SDNode *CallEnd = Result.second.getNode(); 8218 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8219 CallEnd = CallEnd->getOperand(0).getNode(); 8220 8221 /// Get a call instruction from the call sequence chain. 8222 /// Tail calls are not allowed. 8223 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8224 "Expected a callseq node."); 8225 SDNode *Call = CallEnd->getOperand(0).getNode(); 8226 bool HasGlue = Call->getGluedNode(); 8227 8228 // Replace the target specific call node with the patchable intrinsic. 8229 SmallVector<SDValue, 8> Ops; 8230 8231 // Add the <id> and <numBytes> constants. 8232 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8233 Ops.push_back(DAG.getTargetConstant( 8234 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8235 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8236 Ops.push_back(DAG.getTargetConstant( 8237 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8238 MVT::i32)); 8239 8240 // Add the callee. 8241 Ops.push_back(Callee); 8242 8243 // Adjust <numArgs> to account for any arguments that have been passed on the 8244 // stack instead. 8245 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8246 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8247 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8248 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8249 8250 // Add the calling convention 8251 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8252 8253 // Add the arguments we omitted previously. The register allocator should 8254 // place these in any free register. 8255 if (IsAnyRegCC) 8256 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8257 Ops.push_back(getValue(CS.getArgument(i))); 8258 8259 // Push the arguments from the call instruction up to the register mask. 8260 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8261 Ops.append(Call->op_begin() + 2, e); 8262 8263 // Push live variables for the stack map. 8264 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8265 8266 // Push the register mask info. 8267 if (HasGlue) 8268 Ops.push_back(*(Call->op_end()-2)); 8269 else 8270 Ops.push_back(*(Call->op_end()-1)); 8271 8272 // Push the chain (this is originally the first operand of the call, but 8273 // becomes now the last or second to last operand). 8274 Ops.push_back(*(Call->op_begin())); 8275 8276 // Push the glue flag (last operand). 8277 if (HasGlue) 8278 Ops.push_back(*(Call->op_end()-1)); 8279 8280 SDVTList NodeTys; 8281 if (IsAnyRegCC && HasDef) { 8282 // Create the return types based on the intrinsic definition 8283 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8284 SmallVector<EVT, 3> ValueVTs; 8285 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8286 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8287 8288 // There is always a chain and a glue type at the end 8289 ValueVTs.push_back(MVT::Other); 8290 ValueVTs.push_back(MVT::Glue); 8291 NodeTys = DAG.getVTList(ValueVTs); 8292 } else 8293 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8294 8295 // Replace the target specific call node with a PATCHPOINT node. 8296 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8297 dl, NodeTys, Ops); 8298 8299 // Update the NodeMap. 8300 if (HasDef) { 8301 if (IsAnyRegCC) 8302 setValue(CS.getInstruction(), SDValue(MN, 0)); 8303 else 8304 setValue(CS.getInstruction(), Result.first); 8305 } 8306 8307 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8308 // call sequence. Furthermore the location of the chain and glue can change 8309 // when the AnyReg calling convention is used and the intrinsic returns a 8310 // value. 8311 if (IsAnyRegCC && HasDef) { 8312 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8313 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8314 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8315 } else 8316 DAG.ReplaceAllUsesWith(Call, MN); 8317 DAG.DeleteNode(Call); 8318 8319 // Inform the Frame Information that we have a patchpoint in this function. 8320 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8321 } 8322 8323 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8324 unsigned Intrinsic) { 8325 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8326 SDValue Op1 = getValue(I.getArgOperand(0)); 8327 SDValue Op2; 8328 if (I.getNumArgOperands() > 1) 8329 Op2 = getValue(I.getArgOperand(1)); 8330 SDLoc dl = getCurSDLoc(); 8331 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8332 SDValue Res; 8333 FastMathFlags FMF; 8334 if (isa<FPMathOperator>(I)) 8335 FMF = I.getFastMathFlags(); 8336 8337 switch (Intrinsic) { 8338 case Intrinsic::experimental_vector_reduce_fadd: 8339 if (FMF.isFast()) 8340 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8341 else 8342 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8343 break; 8344 case Intrinsic::experimental_vector_reduce_fmul: 8345 if (FMF.isFast()) 8346 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8347 else 8348 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8349 break; 8350 case Intrinsic::experimental_vector_reduce_add: 8351 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8352 break; 8353 case Intrinsic::experimental_vector_reduce_mul: 8354 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8355 break; 8356 case Intrinsic::experimental_vector_reduce_and: 8357 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8358 break; 8359 case Intrinsic::experimental_vector_reduce_or: 8360 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8361 break; 8362 case Intrinsic::experimental_vector_reduce_xor: 8363 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8364 break; 8365 case Intrinsic::experimental_vector_reduce_smax: 8366 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8367 break; 8368 case Intrinsic::experimental_vector_reduce_smin: 8369 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8370 break; 8371 case Intrinsic::experimental_vector_reduce_umax: 8372 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8373 break; 8374 case Intrinsic::experimental_vector_reduce_umin: 8375 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8376 break; 8377 case Intrinsic::experimental_vector_reduce_fmax: 8378 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8379 break; 8380 case Intrinsic::experimental_vector_reduce_fmin: 8381 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8382 break; 8383 default: 8384 llvm_unreachable("Unhandled vector reduce intrinsic"); 8385 } 8386 setValue(&I, Res); 8387 } 8388 8389 /// Returns an AttributeList representing the attributes applied to the return 8390 /// value of the given call. 8391 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8392 SmallVector<Attribute::AttrKind, 2> Attrs; 8393 if (CLI.RetSExt) 8394 Attrs.push_back(Attribute::SExt); 8395 if (CLI.RetZExt) 8396 Attrs.push_back(Attribute::ZExt); 8397 if (CLI.IsInReg) 8398 Attrs.push_back(Attribute::InReg); 8399 8400 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8401 Attrs); 8402 } 8403 8404 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8405 /// implementation, which just calls LowerCall. 8406 /// FIXME: When all targets are 8407 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8408 std::pair<SDValue, SDValue> 8409 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8410 // Handle the incoming return values from the call. 8411 CLI.Ins.clear(); 8412 Type *OrigRetTy = CLI.RetTy; 8413 SmallVector<EVT, 4> RetTys; 8414 SmallVector<uint64_t, 4> Offsets; 8415 auto &DL = CLI.DAG.getDataLayout(); 8416 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8417 8418 if (CLI.IsPostTypeLegalization) { 8419 // If we are lowering a libcall after legalization, split the return type. 8420 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8421 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8422 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8423 EVT RetVT = OldRetTys[i]; 8424 uint64_t Offset = OldOffsets[i]; 8425 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8426 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8427 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8428 RetTys.append(NumRegs, RegisterVT); 8429 for (unsigned j = 0; j != NumRegs; ++j) 8430 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8431 } 8432 } 8433 8434 SmallVector<ISD::OutputArg, 4> Outs; 8435 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8436 8437 bool CanLowerReturn = 8438 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8439 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8440 8441 SDValue DemoteStackSlot; 8442 int DemoteStackIdx = -100; 8443 if (!CanLowerReturn) { 8444 // FIXME: equivalent assert? 8445 // assert(!CS.hasInAllocaArgument() && 8446 // "sret demotion is incompatible with inalloca"); 8447 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8448 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8449 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8450 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8451 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8452 DL.getAllocaAddrSpace()); 8453 8454 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8455 ArgListEntry Entry; 8456 Entry.Node = DemoteStackSlot; 8457 Entry.Ty = StackSlotPtrType; 8458 Entry.IsSExt = false; 8459 Entry.IsZExt = false; 8460 Entry.IsInReg = false; 8461 Entry.IsSRet = true; 8462 Entry.IsNest = false; 8463 Entry.IsByVal = false; 8464 Entry.IsReturned = false; 8465 Entry.IsSwiftSelf = false; 8466 Entry.IsSwiftError = false; 8467 Entry.Alignment = Align; 8468 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8469 CLI.NumFixedArgs += 1; 8470 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8471 8472 // sret demotion isn't compatible with tail-calls, since the sret argument 8473 // points into the callers stack frame. 8474 CLI.IsTailCall = false; 8475 } else { 8476 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8477 EVT VT = RetTys[I]; 8478 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8479 CLI.CallConv, VT); 8480 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8481 CLI.CallConv, VT); 8482 for (unsigned i = 0; i != NumRegs; ++i) { 8483 ISD::InputArg MyFlags; 8484 MyFlags.VT = RegisterVT; 8485 MyFlags.ArgVT = VT; 8486 MyFlags.Used = CLI.IsReturnValueUsed; 8487 if (CLI.RetSExt) 8488 MyFlags.Flags.setSExt(); 8489 if (CLI.RetZExt) 8490 MyFlags.Flags.setZExt(); 8491 if (CLI.IsInReg) 8492 MyFlags.Flags.setInReg(); 8493 CLI.Ins.push_back(MyFlags); 8494 } 8495 } 8496 } 8497 8498 // We push in swifterror return as the last element of CLI.Ins. 8499 ArgListTy &Args = CLI.getArgs(); 8500 if (supportSwiftError()) { 8501 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8502 if (Args[i].IsSwiftError) { 8503 ISD::InputArg MyFlags; 8504 MyFlags.VT = getPointerTy(DL); 8505 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8506 MyFlags.Flags.setSwiftError(); 8507 CLI.Ins.push_back(MyFlags); 8508 } 8509 } 8510 } 8511 8512 // Handle all of the outgoing arguments. 8513 CLI.Outs.clear(); 8514 CLI.OutVals.clear(); 8515 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8516 SmallVector<EVT, 4> ValueVTs; 8517 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8518 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8519 Type *FinalType = Args[i].Ty; 8520 if (Args[i].IsByVal) 8521 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8522 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8523 FinalType, CLI.CallConv, CLI.IsVarArg); 8524 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8525 ++Value) { 8526 EVT VT = ValueVTs[Value]; 8527 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8528 SDValue Op = SDValue(Args[i].Node.getNode(), 8529 Args[i].Node.getResNo() + Value); 8530 ISD::ArgFlagsTy Flags; 8531 8532 // Certain targets (such as MIPS), may have a different ABI alignment 8533 // for a type depending on the context. Give the target a chance to 8534 // specify the alignment it wants. 8535 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8536 8537 if (Args[i].IsZExt) 8538 Flags.setZExt(); 8539 if (Args[i].IsSExt) 8540 Flags.setSExt(); 8541 if (Args[i].IsInReg) { 8542 // If we are using vectorcall calling convention, a structure that is 8543 // passed InReg - is surely an HVA 8544 if (CLI.CallConv == CallingConv::X86_VectorCall && 8545 isa<StructType>(FinalType)) { 8546 // The first value of a structure is marked 8547 if (0 == Value) 8548 Flags.setHvaStart(); 8549 Flags.setHva(); 8550 } 8551 // Set InReg Flag 8552 Flags.setInReg(); 8553 } 8554 if (Args[i].IsSRet) 8555 Flags.setSRet(); 8556 if (Args[i].IsSwiftSelf) 8557 Flags.setSwiftSelf(); 8558 if (Args[i].IsSwiftError) 8559 Flags.setSwiftError(); 8560 if (Args[i].IsByVal) 8561 Flags.setByVal(); 8562 if (Args[i].IsInAlloca) { 8563 Flags.setInAlloca(); 8564 // Set the byval flag for CCAssignFn callbacks that don't know about 8565 // inalloca. This way we can know how many bytes we should've allocated 8566 // and how many bytes a callee cleanup function will pop. If we port 8567 // inalloca to more targets, we'll have to add custom inalloca handling 8568 // in the various CC lowering callbacks. 8569 Flags.setByVal(); 8570 } 8571 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8572 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8573 Type *ElementTy = Ty->getElementType(); 8574 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8575 // For ByVal, alignment should come from FE. BE will guess if this 8576 // info is not there but there are cases it cannot get right. 8577 unsigned FrameAlign; 8578 if (Args[i].Alignment) 8579 FrameAlign = Args[i].Alignment; 8580 else 8581 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8582 Flags.setByValAlign(FrameAlign); 8583 } 8584 if (Args[i].IsNest) 8585 Flags.setNest(); 8586 if (NeedsRegBlock) 8587 Flags.setInConsecutiveRegs(); 8588 Flags.setOrigAlign(OriginalAlignment); 8589 8590 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8591 CLI.CallConv, VT); 8592 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8593 CLI.CallConv, VT); 8594 SmallVector<SDValue, 4> Parts(NumParts); 8595 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8596 8597 if (Args[i].IsSExt) 8598 ExtendKind = ISD::SIGN_EXTEND; 8599 else if (Args[i].IsZExt) 8600 ExtendKind = ISD::ZERO_EXTEND; 8601 8602 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8603 // for now. 8604 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8605 CanLowerReturn) { 8606 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8607 "unexpected use of 'returned'"); 8608 // Before passing 'returned' to the target lowering code, ensure that 8609 // either the register MVT and the actual EVT are the same size or that 8610 // the return value and argument are extended in the same way; in these 8611 // cases it's safe to pass the argument register value unchanged as the 8612 // return register value (although it's at the target's option whether 8613 // to do so) 8614 // TODO: allow code generation to take advantage of partially preserved 8615 // registers rather than clobbering the entire register when the 8616 // parameter extension method is not compatible with the return 8617 // extension method 8618 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8619 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8620 CLI.RetZExt == Args[i].IsZExt)) 8621 Flags.setReturned(); 8622 } 8623 8624 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8625 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 8626 8627 for (unsigned j = 0; j != NumParts; ++j) { 8628 // if it isn't first piece, alignment must be 1 8629 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8630 i < CLI.NumFixedArgs, 8631 i, j*Parts[j].getValueType().getStoreSize()); 8632 if (NumParts > 1 && j == 0) 8633 MyFlags.Flags.setSplit(); 8634 else if (j != 0) { 8635 MyFlags.Flags.setOrigAlign(1); 8636 if (j == NumParts - 1) 8637 MyFlags.Flags.setSplitEnd(); 8638 } 8639 8640 CLI.Outs.push_back(MyFlags); 8641 CLI.OutVals.push_back(Parts[j]); 8642 } 8643 8644 if (NeedsRegBlock && Value == NumValues - 1) 8645 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8646 } 8647 } 8648 8649 SmallVector<SDValue, 4> InVals; 8650 CLI.Chain = LowerCall(CLI, InVals); 8651 8652 // Update CLI.InVals to use outside of this function. 8653 CLI.InVals = InVals; 8654 8655 // Verify that the target's LowerCall behaved as expected. 8656 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8657 "LowerCall didn't return a valid chain!"); 8658 assert((!CLI.IsTailCall || InVals.empty()) && 8659 "LowerCall emitted a return value for a tail call!"); 8660 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8661 "LowerCall didn't emit the correct number of values!"); 8662 8663 // For a tail call, the return value is merely live-out and there aren't 8664 // any nodes in the DAG representing it. Return a special value to 8665 // indicate that a tail call has been emitted and no more Instructions 8666 // should be processed in the current block. 8667 if (CLI.IsTailCall) { 8668 CLI.DAG.setRoot(CLI.Chain); 8669 return std::make_pair(SDValue(), SDValue()); 8670 } 8671 8672 #ifndef NDEBUG 8673 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8674 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8675 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8676 "LowerCall emitted a value with the wrong type!"); 8677 } 8678 #endif 8679 8680 SmallVector<SDValue, 4> ReturnValues; 8681 if (!CanLowerReturn) { 8682 // The instruction result is the result of loading from the 8683 // hidden sret parameter. 8684 SmallVector<EVT, 1> PVTs; 8685 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8686 8687 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8688 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8689 EVT PtrVT = PVTs[0]; 8690 8691 unsigned NumValues = RetTys.size(); 8692 ReturnValues.resize(NumValues); 8693 SmallVector<SDValue, 4> Chains(NumValues); 8694 8695 // An aggregate return value cannot wrap around the address space, so 8696 // offsets to its parts don't wrap either. 8697 SDNodeFlags Flags; 8698 Flags.setNoUnsignedWrap(true); 8699 8700 for (unsigned i = 0; i < NumValues; ++i) { 8701 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8702 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8703 PtrVT), Flags); 8704 SDValue L = CLI.DAG.getLoad( 8705 RetTys[i], CLI.DL, CLI.Chain, Add, 8706 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8707 DemoteStackIdx, Offsets[i]), 8708 /* Alignment = */ 1); 8709 ReturnValues[i] = L; 8710 Chains[i] = L.getValue(1); 8711 } 8712 8713 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8714 } else { 8715 // Collect the legal value parts into potentially illegal values 8716 // that correspond to the original function's return values. 8717 Optional<ISD::NodeType> AssertOp; 8718 if (CLI.RetSExt) 8719 AssertOp = ISD::AssertSext; 8720 else if (CLI.RetZExt) 8721 AssertOp = ISD::AssertZext; 8722 unsigned CurReg = 0; 8723 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8724 EVT VT = RetTys[I]; 8725 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8726 CLI.CallConv, VT); 8727 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8728 CLI.CallConv, VT); 8729 8730 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8731 NumRegs, RegisterVT, VT, nullptr, 8732 CLI.CallConv, AssertOp)); 8733 CurReg += NumRegs; 8734 } 8735 8736 // For a function returning void, there is no return value. We can't create 8737 // such a node, so we just return a null return value in that case. In 8738 // that case, nothing will actually look at the value. 8739 if (ReturnValues.empty()) 8740 return std::make_pair(SDValue(), CLI.Chain); 8741 } 8742 8743 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8744 CLI.DAG.getVTList(RetTys), ReturnValues); 8745 return std::make_pair(Res, CLI.Chain); 8746 } 8747 8748 void TargetLowering::LowerOperationWrapper(SDNode *N, 8749 SmallVectorImpl<SDValue> &Results, 8750 SelectionDAG &DAG) const { 8751 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8752 Results.push_back(Res); 8753 } 8754 8755 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8756 llvm_unreachable("LowerOperation not implemented for this target!"); 8757 } 8758 8759 void 8760 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8761 SDValue Op = getNonRegisterValue(V); 8762 assert((Op.getOpcode() != ISD::CopyFromReg || 8763 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8764 "Copy from a reg to the same reg!"); 8765 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8766 8767 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8768 // If this is an InlineAsm we have to match the registers required, not the 8769 // notional registers required by the type. 8770 8771 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 8772 None); // This is not an ABI copy. 8773 SDValue Chain = DAG.getEntryNode(); 8774 8775 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8776 FuncInfo.PreferredExtendType.end()) 8777 ? ISD::ANY_EXTEND 8778 : FuncInfo.PreferredExtendType[V]; 8779 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8780 PendingExports.push_back(Chain); 8781 } 8782 8783 #include "llvm/CodeGen/SelectionDAGISel.h" 8784 8785 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8786 /// entry block, return true. This includes arguments used by switches, since 8787 /// the switch may expand into multiple basic blocks. 8788 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8789 // With FastISel active, we may be splitting blocks, so force creation 8790 // of virtual registers for all non-dead arguments. 8791 if (FastISel) 8792 return A->use_empty(); 8793 8794 const BasicBlock &Entry = A->getParent()->front(); 8795 for (const User *U : A->users()) 8796 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8797 return false; // Use not in entry block. 8798 8799 return true; 8800 } 8801 8802 using ArgCopyElisionMapTy = 8803 DenseMap<const Argument *, 8804 std::pair<const AllocaInst *, const StoreInst *>>; 8805 8806 /// Scan the entry block of the function in FuncInfo for arguments that look 8807 /// like copies into a local alloca. Record any copied arguments in 8808 /// ArgCopyElisionCandidates. 8809 static void 8810 findArgumentCopyElisionCandidates(const DataLayout &DL, 8811 FunctionLoweringInfo *FuncInfo, 8812 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8813 // Record the state of every static alloca used in the entry block. Argument 8814 // allocas are all used in the entry block, so we need approximately as many 8815 // entries as we have arguments. 8816 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8817 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8818 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8819 StaticAllocas.reserve(NumArgs * 2); 8820 8821 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8822 if (!V) 8823 return nullptr; 8824 V = V->stripPointerCasts(); 8825 const auto *AI = dyn_cast<AllocaInst>(V); 8826 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8827 return nullptr; 8828 auto Iter = StaticAllocas.insert({AI, Unknown}); 8829 return &Iter.first->second; 8830 }; 8831 8832 // Look for stores of arguments to static allocas. Look through bitcasts and 8833 // GEPs to handle type coercions, as long as the alloca is fully initialized 8834 // by the store. Any non-store use of an alloca escapes it and any subsequent 8835 // unanalyzed store might write it. 8836 // FIXME: Handle structs initialized with multiple stores. 8837 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8838 // Look for stores, and handle non-store uses conservatively. 8839 const auto *SI = dyn_cast<StoreInst>(&I); 8840 if (!SI) { 8841 // We will look through cast uses, so ignore them completely. 8842 if (I.isCast()) 8843 continue; 8844 // Ignore debug info intrinsics, they don't escape or store to allocas. 8845 if (isa<DbgInfoIntrinsic>(I)) 8846 continue; 8847 // This is an unknown instruction. Assume it escapes or writes to all 8848 // static alloca operands. 8849 for (const Use &U : I.operands()) { 8850 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8851 *Info = StaticAllocaInfo::Clobbered; 8852 } 8853 continue; 8854 } 8855 8856 // If the stored value is a static alloca, mark it as escaped. 8857 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8858 *Info = StaticAllocaInfo::Clobbered; 8859 8860 // Check if the destination is a static alloca. 8861 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8862 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8863 if (!Info) 8864 continue; 8865 const AllocaInst *AI = cast<AllocaInst>(Dst); 8866 8867 // Skip allocas that have been initialized or clobbered. 8868 if (*Info != StaticAllocaInfo::Unknown) 8869 continue; 8870 8871 // Check if the stored value is an argument, and that this store fully 8872 // initializes the alloca. Don't elide copies from the same argument twice. 8873 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8874 const auto *Arg = dyn_cast<Argument>(Val); 8875 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8876 Arg->getType()->isEmptyTy() || 8877 DL.getTypeStoreSize(Arg->getType()) != 8878 DL.getTypeAllocSize(AI->getAllocatedType()) || 8879 ArgCopyElisionCandidates.count(Arg)) { 8880 *Info = StaticAllocaInfo::Clobbered; 8881 continue; 8882 } 8883 8884 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 8885 << '\n'); 8886 8887 // Mark this alloca and store for argument copy elision. 8888 *Info = StaticAllocaInfo::Elidable; 8889 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8890 8891 // Stop scanning if we've seen all arguments. This will happen early in -O0 8892 // builds, which is useful, because -O0 builds have large entry blocks and 8893 // many allocas. 8894 if (ArgCopyElisionCandidates.size() == NumArgs) 8895 break; 8896 } 8897 } 8898 8899 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8900 /// ArgVal is a load from a suitable fixed stack object. 8901 static void tryToElideArgumentCopy( 8902 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8903 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8904 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8905 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8906 SDValue ArgVal, bool &ArgHasUses) { 8907 // Check if this is a load from a fixed stack object. 8908 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8909 if (!LNode) 8910 return; 8911 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 8912 if (!FINode) 8913 return; 8914 8915 // Check that the fixed stack object is the right size and alignment. 8916 // Look at the alignment that the user wrote on the alloca instead of looking 8917 // at the stack object. 8918 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 8919 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 8920 const AllocaInst *AI = ArgCopyIter->second.first; 8921 int FixedIndex = FINode->getIndex(); 8922 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 8923 int OldIndex = AllocaIndex; 8924 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 8925 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 8926 LLVM_DEBUG( 8927 dbgs() << " argument copy elision failed due to bad fixed stack " 8928 "object size\n"); 8929 return; 8930 } 8931 unsigned RequiredAlignment = AI->getAlignment(); 8932 if (!RequiredAlignment) { 8933 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 8934 AI->getAllocatedType()); 8935 } 8936 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 8937 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 8938 "greater than stack argument alignment (" 8939 << RequiredAlignment << " vs " 8940 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 8941 return; 8942 } 8943 8944 // Perform the elision. Delete the old stack object and replace its only use 8945 // in the variable info map. Mark the stack object as mutable. 8946 LLVM_DEBUG({ 8947 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 8948 << " Replacing frame index " << OldIndex << " with " << FixedIndex 8949 << '\n'; 8950 }); 8951 MFI.RemoveStackObject(OldIndex); 8952 MFI.setIsImmutableObjectIndex(FixedIndex, false); 8953 AllocaIndex = FixedIndex; 8954 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 8955 Chains.push_back(ArgVal.getValue(1)); 8956 8957 // Avoid emitting code for the store implementing the copy. 8958 const StoreInst *SI = ArgCopyIter->second.second; 8959 ElidedArgCopyInstrs.insert(SI); 8960 8961 // Check for uses of the argument again so that we can avoid exporting ArgVal 8962 // if it is't used by anything other than the store. 8963 for (const Value *U : Arg.users()) { 8964 if (U != SI) { 8965 ArgHasUses = true; 8966 break; 8967 } 8968 } 8969 } 8970 8971 void SelectionDAGISel::LowerArguments(const Function &F) { 8972 SelectionDAG &DAG = SDB->DAG; 8973 SDLoc dl = SDB->getCurSDLoc(); 8974 const DataLayout &DL = DAG.getDataLayout(); 8975 SmallVector<ISD::InputArg, 16> Ins; 8976 8977 if (!FuncInfo->CanLowerReturn) { 8978 // Put in an sret pointer parameter before all the other parameters. 8979 SmallVector<EVT, 1> ValueVTs; 8980 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8981 F.getReturnType()->getPointerTo( 8982 DAG.getDataLayout().getAllocaAddrSpace()), 8983 ValueVTs); 8984 8985 // NOTE: Assuming that a pointer will never break down to more than one VT 8986 // or one register. 8987 ISD::ArgFlagsTy Flags; 8988 Flags.setSRet(); 8989 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 8990 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 8991 ISD::InputArg::NoArgIndex, 0); 8992 Ins.push_back(RetArg); 8993 } 8994 8995 // Look for stores of arguments to static allocas. Mark such arguments with a 8996 // flag to ask the target to give us the memory location of that argument if 8997 // available. 8998 ArgCopyElisionMapTy ArgCopyElisionCandidates; 8999 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9000 9001 // Set up the incoming argument description vector. 9002 for (const Argument &Arg : F.args()) { 9003 unsigned ArgNo = Arg.getArgNo(); 9004 SmallVector<EVT, 4> ValueVTs; 9005 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9006 bool isArgValueUsed = !Arg.use_empty(); 9007 unsigned PartBase = 0; 9008 Type *FinalType = Arg.getType(); 9009 if (Arg.hasAttribute(Attribute::ByVal)) 9010 FinalType = cast<PointerType>(FinalType)->getElementType(); 9011 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9012 FinalType, F.getCallingConv(), F.isVarArg()); 9013 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9014 Value != NumValues; ++Value) { 9015 EVT VT = ValueVTs[Value]; 9016 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9017 ISD::ArgFlagsTy Flags; 9018 9019 // Certain targets (such as MIPS), may have a different ABI alignment 9020 // for a type depending on the context. Give the target a chance to 9021 // specify the alignment it wants. 9022 unsigned OriginalAlignment = 9023 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 9024 9025 if (Arg.hasAttribute(Attribute::ZExt)) 9026 Flags.setZExt(); 9027 if (Arg.hasAttribute(Attribute::SExt)) 9028 Flags.setSExt(); 9029 if (Arg.hasAttribute(Attribute::InReg)) { 9030 // If we are using vectorcall calling convention, a structure that is 9031 // passed InReg - is surely an HVA 9032 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9033 isa<StructType>(Arg.getType())) { 9034 // The first value of a structure is marked 9035 if (0 == Value) 9036 Flags.setHvaStart(); 9037 Flags.setHva(); 9038 } 9039 // Set InReg Flag 9040 Flags.setInReg(); 9041 } 9042 if (Arg.hasAttribute(Attribute::StructRet)) 9043 Flags.setSRet(); 9044 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9045 Flags.setSwiftSelf(); 9046 if (Arg.hasAttribute(Attribute::SwiftError)) 9047 Flags.setSwiftError(); 9048 if (Arg.hasAttribute(Attribute::ByVal)) 9049 Flags.setByVal(); 9050 if (Arg.hasAttribute(Attribute::InAlloca)) { 9051 Flags.setInAlloca(); 9052 // Set the byval flag for CCAssignFn callbacks that don't know about 9053 // inalloca. This way we can know how many bytes we should've allocated 9054 // and how many bytes a callee cleanup function will pop. If we port 9055 // inalloca to more targets, we'll have to add custom inalloca handling 9056 // in the various CC lowering callbacks. 9057 Flags.setByVal(); 9058 } 9059 if (F.getCallingConv() == CallingConv::X86_INTR) { 9060 // IA Interrupt passes frame (1st parameter) by value in the stack. 9061 if (ArgNo == 0) 9062 Flags.setByVal(); 9063 } 9064 if (Flags.isByVal() || Flags.isInAlloca()) { 9065 PointerType *Ty = cast<PointerType>(Arg.getType()); 9066 Type *ElementTy = Ty->getElementType(); 9067 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9068 // For ByVal, alignment should be passed from FE. BE will guess if 9069 // this info is not there but there are cases it cannot get right. 9070 unsigned FrameAlign; 9071 if (Arg.getParamAlignment()) 9072 FrameAlign = Arg.getParamAlignment(); 9073 else 9074 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9075 Flags.setByValAlign(FrameAlign); 9076 } 9077 if (Arg.hasAttribute(Attribute::Nest)) 9078 Flags.setNest(); 9079 if (NeedsRegBlock) 9080 Flags.setInConsecutiveRegs(); 9081 Flags.setOrigAlign(OriginalAlignment); 9082 if (ArgCopyElisionCandidates.count(&Arg)) 9083 Flags.setCopyElisionCandidate(); 9084 9085 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9086 *CurDAG->getContext(), F.getCallingConv(), VT); 9087 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9088 *CurDAG->getContext(), F.getCallingConv(), VT); 9089 for (unsigned i = 0; i != NumRegs; ++i) { 9090 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9091 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9092 if (NumRegs > 1 && i == 0) 9093 MyFlags.Flags.setSplit(); 9094 // if it isn't first piece, alignment must be 1 9095 else if (i > 0) { 9096 MyFlags.Flags.setOrigAlign(1); 9097 if (i == NumRegs - 1) 9098 MyFlags.Flags.setSplitEnd(); 9099 } 9100 Ins.push_back(MyFlags); 9101 } 9102 if (NeedsRegBlock && Value == NumValues - 1) 9103 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9104 PartBase += VT.getStoreSize(); 9105 } 9106 } 9107 9108 // Call the target to set up the argument values. 9109 SmallVector<SDValue, 8> InVals; 9110 SDValue NewRoot = TLI->LowerFormalArguments( 9111 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9112 9113 // Verify that the target's LowerFormalArguments behaved as expected. 9114 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9115 "LowerFormalArguments didn't return a valid chain!"); 9116 assert(InVals.size() == Ins.size() && 9117 "LowerFormalArguments didn't emit the correct number of values!"); 9118 LLVM_DEBUG({ 9119 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9120 assert(InVals[i].getNode() && 9121 "LowerFormalArguments emitted a null value!"); 9122 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9123 "LowerFormalArguments emitted a value with the wrong type!"); 9124 } 9125 }); 9126 9127 // Update the DAG with the new chain value resulting from argument lowering. 9128 DAG.setRoot(NewRoot); 9129 9130 // Set up the argument values. 9131 unsigned i = 0; 9132 if (!FuncInfo->CanLowerReturn) { 9133 // Create a virtual register for the sret pointer, and put in a copy 9134 // from the sret argument into it. 9135 SmallVector<EVT, 1> ValueVTs; 9136 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9137 F.getReturnType()->getPointerTo( 9138 DAG.getDataLayout().getAllocaAddrSpace()), 9139 ValueVTs); 9140 MVT VT = ValueVTs[0].getSimpleVT(); 9141 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9142 Optional<ISD::NodeType> AssertOp = None; 9143 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9144 nullptr, F.getCallingConv(), AssertOp); 9145 9146 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9147 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9148 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9149 FuncInfo->DemoteRegister = SRetReg; 9150 NewRoot = 9151 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9152 DAG.setRoot(NewRoot); 9153 9154 // i indexes lowered arguments. Bump it past the hidden sret argument. 9155 ++i; 9156 } 9157 9158 SmallVector<SDValue, 4> Chains; 9159 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9160 for (const Argument &Arg : F.args()) { 9161 SmallVector<SDValue, 4> ArgValues; 9162 SmallVector<EVT, 4> ValueVTs; 9163 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9164 unsigned NumValues = ValueVTs.size(); 9165 if (NumValues == 0) 9166 continue; 9167 9168 bool ArgHasUses = !Arg.use_empty(); 9169 9170 // Elide the copying store if the target loaded this argument from a 9171 // suitable fixed stack object. 9172 if (Ins[i].Flags.isCopyElisionCandidate()) { 9173 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9174 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9175 InVals[i], ArgHasUses); 9176 } 9177 9178 // If this argument is unused then remember its value. It is used to generate 9179 // debugging information. 9180 bool isSwiftErrorArg = 9181 TLI->supportSwiftError() && 9182 Arg.hasAttribute(Attribute::SwiftError); 9183 if (!ArgHasUses && !isSwiftErrorArg) { 9184 SDB->setUnusedArgValue(&Arg, InVals[i]); 9185 9186 // Also remember any frame index for use in FastISel. 9187 if (FrameIndexSDNode *FI = 9188 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9189 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9190 } 9191 9192 for (unsigned Val = 0; Val != NumValues; ++Val) { 9193 EVT VT = ValueVTs[Val]; 9194 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9195 F.getCallingConv(), VT); 9196 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9197 *CurDAG->getContext(), F.getCallingConv(), VT); 9198 9199 // Even an apparant 'unused' swifterror argument needs to be returned. So 9200 // we do generate a copy for it that can be used on return from the 9201 // function. 9202 if (ArgHasUses || isSwiftErrorArg) { 9203 Optional<ISD::NodeType> AssertOp; 9204 if (Arg.hasAttribute(Attribute::SExt)) 9205 AssertOp = ISD::AssertSext; 9206 else if (Arg.hasAttribute(Attribute::ZExt)) 9207 AssertOp = ISD::AssertZext; 9208 9209 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9210 PartVT, VT, nullptr, 9211 F.getCallingConv(), AssertOp)); 9212 } 9213 9214 i += NumParts; 9215 } 9216 9217 // We don't need to do anything else for unused arguments. 9218 if (ArgValues.empty()) 9219 continue; 9220 9221 // Note down frame index. 9222 if (FrameIndexSDNode *FI = 9223 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9224 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9225 9226 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9227 SDB->getCurSDLoc()); 9228 9229 SDB->setValue(&Arg, Res); 9230 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9231 // We want to associate the argument with the frame index, among 9232 // involved operands, that correspond to the lowest address. The 9233 // getCopyFromParts function, called earlier, is swapping the order of 9234 // the operands to BUILD_PAIR depending on endianness. The result of 9235 // that swapping is that the least significant bits of the argument will 9236 // be in the first operand of the BUILD_PAIR node, and the most 9237 // significant bits will be in the second operand. 9238 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9239 if (LoadSDNode *LNode = 9240 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9241 if (FrameIndexSDNode *FI = 9242 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9243 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9244 } 9245 9246 // Update the SwiftErrorVRegDefMap. 9247 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9248 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9249 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9250 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9251 FuncInfo->SwiftErrorArg, Reg); 9252 } 9253 9254 // If this argument is live outside of the entry block, insert a copy from 9255 // wherever we got it to the vreg that other BB's will reference it as. 9256 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9257 // If we can, though, try to skip creating an unnecessary vreg. 9258 // FIXME: This isn't very clean... it would be nice to make this more 9259 // general. It's also subtly incompatible with the hacks FastISel 9260 // uses with vregs. 9261 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9262 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9263 FuncInfo->ValueMap[&Arg] = Reg; 9264 continue; 9265 } 9266 } 9267 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9268 FuncInfo->InitializeRegForValue(&Arg); 9269 SDB->CopyToExportRegsIfNeeded(&Arg); 9270 } 9271 } 9272 9273 if (!Chains.empty()) { 9274 Chains.push_back(NewRoot); 9275 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9276 } 9277 9278 DAG.setRoot(NewRoot); 9279 9280 assert(i == InVals.size() && "Argument register count mismatch!"); 9281 9282 // If any argument copy elisions occurred and we have debug info, update the 9283 // stale frame indices used in the dbg.declare variable info table. 9284 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9285 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9286 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9287 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9288 if (I != ArgCopyElisionFrameIndexMap.end()) 9289 VI.Slot = I->second; 9290 } 9291 } 9292 9293 // Finally, if the target has anything special to do, allow it to do so. 9294 EmitFunctionEntryCode(); 9295 } 9296 9297 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9298 /// ensure constants are generated when needed. Remember the virtual registers 9299 /// that need to be added to the Machine PHI nodes as input. We cannot just 9300 /// directly add them, because expansion might result in multiple MBB's for one 9301 /// BB. As such, the start of the BB might correspond to a different MBB than 9302 /// the end. 9303 void 9304 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9305 const Instruction *TI = LLVMBB->getTerminator(); 9306 9307 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9308 9309 // Check PHI nodes in successors that expect a value to be available from this 9310 // block. 9311 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9312 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9313 if (!isa<PHINode>(SuccBB->begin())) continue; 9314 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9315 9316 // If this terminator has multiple identical successors (common for 9317 // switches), only handle each succ once. 9318 if (!SuccsHandled.insert(SuccMBB).second) 9319 continue; 9320 9321 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9322 9323 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9324 // nodes and Machine PHI nodes, but the incoming operands have not been 9325 // emitted yet. 9326 for (const PHINode &PN : SuccBB->phis()) { 9327 // Ignore dead phi's. 9328 if (PN.use_empty()) 9329 continue; 9330 9331 // Skip empty types 9332 if (PN.getType()->isEmptyTy()) 9333 continue; 9334 9335 unsigned Reg; 9336 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9337 9338 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9339 unsigned &RegOut = ConstantsOut[C]; 9340 if (RegOut == 0) { 9341 RegOut = FuncInfo.CreateRegs(C->getType()); 9342 CopyValueToVirtualRegister(C, RegOut); 9343 } 9344 Reg = RegOut; 9345 } else { 9346 DenseMap<const Value *, unsigned>::iterator I = 9347 FuncInfo.ValueMap.find(PHIOp); 9348 if (I != FuncInfo.ValueMap.end()) 9349 Reg = I->second; 9350 else { 9351 assert(isa<AllocaInst>(PHIOp) && 9352 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9353 "Didn't codegen value into a register!??"); 9354 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9355 CopyValueToVirtualRegister(PHIOp, Reg); 9356 } 9357 } 9358 9359 // Remember that this register needs to added to the machine PHI node as 9360 // the input for this MBB. 9361 SmallVector<EVT, 4> ValueVTs; 9362 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9363 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9364 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9365 EVT VT = ValueVTs[vti]; 9366 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9367 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9368 FuncInfo.PHINodesToUpdate.push_back( 9369 std::make_pair(&*MBBI++, Reg + i)); 9370 Reg += NumRegisters; 9371 } 9372 } 9373 } 9374 9375 ConstantsOut.clear(); 9376 } 9377 9378 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9379 /// is 0. 9380 MachineBasicBlock * 9381 SelectionDAGBuilder::StackProtectorDescriptor:: 9382 AddSuccessorMBB(const BasicBlock *BB, 9383 MachineBasicBlock *ParentMBB, 9384 bool IsLikely, 9385 MachineBasicBlock *SuccMBB) { 9386 // If SuccBB has not been created yet, create it. 9387 if (!SuccMBB) { 9388 MachineFunction *MF = ParentMBB->getParent(); 9389 MachineFunction::iterator BBI(ParentMBB); 9390 SuccMBB = MF->CreateMachineBasicBlock(BB); 9391 MF->insert(++BBI, SuccMBB); 9392 } 9393 // Add it as a successor of ParentMBB. 9394 ParentMBB->addSuccessor( 9395 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9396 return SuccMBB; 9397 } 9398 9399 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9400 MachineFunction::iterator I(MBB); 9401 if (++I == FuncInfo.MF->end()) 9402 return nullptr; 9403 return &*I; 9404 } 9405 9406 /// During lowering new call nodes can be created (such as memset, etc.). 9407 /// Those will become new roots of the current DAG, but complications arise 9408 /// when they are tail calls. In such cases, the call lowering will update 9409 /// the root, but the builder still needs to know that a tail call has been 9410 /// lowered in order to avoid generating an additional return. 9411 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9412 // If the node is null, we do have a tail call. 9413 if (MaybeTC.getNode() != nullptr) 9414 DAG.setRoot(MaybeTC); 9415 else 9416 HasTailCall = true; 9417 } 9418 9419 uint64_t 9420 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9421 unsigned First, unsigned Last) const { 9422 assert(Last >= First); 9423 const APInt &LowCase = Clusters[First].Low->getValue(); 9424 const APInt &HighCase = Clusters[Last].High->getValue(); 9425 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9426 9427 // FIXME: A range of consecutive cases has 100% density, but only requires one 9428 // comparison to lower. We should discriminate against such consecutive ranges 9429 // in jump tables. 9430 9431 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9432 } 9433 9434 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9435 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9436 unsigned Last) const { 9437 assert(Last >= First); 9438 assert(TotalCases[Last] >= TotalCases[First]); 9439 uint64_t NumCases = 9440 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9441 return NumCases; 9442 } 9443 9444 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9445 unsigned First, unsigned Last, 9446 const SwitchInst *SI, 9447 MachineBasicBlock *DefaultMBB, 9448 CaseCluster &JTCluster) { 9449 assert(First <= Last); 9450 9451 auto Prob = BranchProbability::getZero(); 9452 unsigned NumCmps = 0; 9453 std::vector<MachineBasicBlock*> Table; 9454 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9455 9456 // Initialize probabilities in JTProbs. 9457 for (unsigned I = First; I <= Last; ++I) 9458 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9459 9460 for (unsigned I = First; I <= Last; ++I) { 9461 assert(Clusters[I].Kind == CC_Range); 9462 Prob += Clusters[I].Prob; 9463 const APInt &Low = Clusters[I].Low->getValue(); 9464 const APInt &High = Clusters[I].High->getValue(); 9465 NumCmps += (Low == High) ? 1 : 2; 9466 if (I != First) { 9467 // Fill the gap between this and the previous cluster. 9468 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9469 assert(PreviousHigh.slt(Low)); 9470 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9471 for (uint64_t J = 0; J < Gap; J++) 9472 Table.push_back(DefaultMBB); 9473 } 9474 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9475 for (uint64_t J = 0; J < ClusterSize; ++J) 9476 Table.push_back(Clusters[I].MBB); 9477 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9478 } 9479 9480 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9481 unsigned NumDests = JTProbs.size(); 9482 if (TLI.isSuitableForBitTests( 9483 NumDests, NumCmps, Clusters[First].Low->getValue(), 9484 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9485 // Clusters[First..Last] should be lowered as bit tests instead. 9486 return false; 9487 } 9488 9489 // Create the MBB that will load from and jump through the table. 9490 // Note: We create it here, but it's not inserted into the function yet. 9491 MachineFunction *CurMF = FuncInfo.MF; 9492 MachineBasicBlock *JumpTableMBB = 9493 CurMF->CreateMachineBasicBlock(SI->getParent()); 9494 9495 // Add successors. Note: use table order for determinism. 9496 SmallPtrSet<MachineBasicBlock *, 8> Done; 9497 for (MachineBasicBlock *Succ : Table) { 9498 if (Done.count(Succ)) 9499 continue; 9500 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9501 Done.insert(Succ); 9502 } 9503 JumpTableMBB->normalizeSuccProbs(); 9504 9505 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9506 ->createJumpTableIndex(Table); 9507 9508 // Set up the jump table info. 9509 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9510 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9511 Clusters[Last].High->getValue(), SI->getCondition(), 9512 nullptr, false); 9513 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9514 9515 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9516 JTCases.size() - 1, Prob); 9517 return true; 9518 } 9519 9520 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9521 const SwitchInst *SI, 9522 MachineBasicBlock *DefaultMBB) { 9523 #ifndef NDEBUG 9524 // Clusters must be non-empty, sorted, and only contain Range clusters. 9525 assert(!Clusters.empty()); 9526 for (CaseCluster &C : Clusters) 9527 assert(C.Kind == CC_Range); 9528 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9529 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9530 #endif 9531 9532 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9533 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9534 return; 9535 9536 const int64_t N = Clusters.size(); 9537 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9538 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9539 9540 if (N < 2 || N < MinJumpTableEntries) 9541 return; 9542 9543 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9544 SmallVector<unsigned, 8> TotalCases(N); 9545 for (unsigned i = 0; i < N; ++i) { 9546 const APInt &Hi = Clusters[i].High->getValue(); 9547 const APInt &Lo = Clusters[i].Low->getValue(); 9548 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9549 if (i != 0) 9550 TotalCases[i] += TotalCases[i - 1]; 9551 } 9552 9553 // Cheap case: the whole range may be suitable for jump table. 9554 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9555 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9556 assert(NumCases < UINT64_MAX / 100); 9557 assert(Range >= NumCases); 9558 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9559 CaseCluster JTCluster; 9560 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9561 Clusters[0] = JTCluster; 9562 Clusters.resize(1); 9563 return; 9564 } 9565 } 9566 9567 // The algorithm below is not suitable for -O0. 9568 if (TM.getOptLevel() == CodeGenOpt::None) 9569 return; 9570 9571 // Split Clusters into minimum number of dense partitions. The algorithm uses 9572 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9573 // for the Case Statement'" (1994), but builds the MinPartitions array in 9574 // reverse order to make it easier to reconstruct the partitions in ascending 9575 // order. In the choice between two optimal partitionings, it picks the one 9576 // which yields more jump tables. 9577 9578 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9579 SmallVector<unsigned, 8> MinPartitions(N); 9580 // LastElement[i] is the last element of the partition starting at i. 9581 SmallVector<unsigned, 8> LastElement(N); 9582 // PartitionsScore[i] is used to break ties when choosing between two 9583 // partitionings resulting in the same number of partitions. 9584 SmallVector<unsigned, 8> PartitionsScore(N); 9585 // For PartitionsScore, a small number of comparisons is considered as good as 9586 // a jump table and a single comparison is considered better than a jump 9587 // table. 9588 enum PartitionScores : unsigned { 9589 NoTable = 0, 9590 Table = 1, 9591 FewCases = 1, 9592 SingleCase = 2 9593 }; 9594 9595 // Base case: There is only one way to partition Clusters[N-1]. 9596 MinPartitions[N - 1] = 1; 9597 LastElement[N - 1] = N - 1; 9598 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9599 9600 // Note: loop indexes are signed to avoid underflow. 9601 for (int64_t i = N - 2; i >= 0; i--) { 9602 // Find optimal partitioning of Clusters[i..N-1]. 9603 // Baseline: Put Clusters[i] into a partition on its own. 9604 MinPartitions[i] = MinPartitions[i + 1] + 1; 9605 LastElement[i] = i; 9606 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9607 9608 // Search for a solution that results in fewer partitions. 9609 for (int64_t j = N - 1; j > i; j--) { 9610 // Try building a partition from Clusters[i..j]. 9611 uint64_t Range = getJumpTableRange(Clusters, i, j); 9612 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9613 assert(NumCases < UINT64_MAX / 100); 9614 assert(Range >= NumCases); 9615 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9616 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9617 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9618 int64_t NumEntries = j - i + 1; 9619 9620 if (NumEntries == 1) 9621 Score += PartitionScores::SingleCase; 9622 else if (NumEntries <= SmallNumberOfEntries) 9623 Score += PartitionScores::FewCases; 9624 else if (NumEntries >= MinJumpTableEntries) 9625 Score += PartitionScores::Table; 9626 9627 // If this leads to fewer partitions, or to the same number of 9628 // partitions with better score, it is a better partitioning. 9629 if (NumPartitions < MinPartitions[i] || 9630 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9631 MinPartitions[i] = NumPartitions; 9632 LastElement[i] = j; 9633 PartitionsScore[i] = Score; 9634 } 9635 } 9636 } 9637 } 9638 9639 // Iterate over the partitions, replacing some with jump tables in-place. 9640 unsigned DstIndex = 0; 9641 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9642 Last = LastElement[First]; 9643 assert(Last >= First); 9644 assert(DstIndex <= First); 9645 unsigned NumClusters = Last - First + 1; 9646 9647 CaseCluster JTCluster; 9648 if (NumClusters >= MinJumpTableEntries && 9649 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9650 Clusters[DstIndex++] = JTCluster; 9651 } else { 9652 for (unsigned I = First; I <= Last; ++I) 9653 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9654 } 9655 } 9656 Clusters.resize(DstIndex); 9657 } 9658 9659 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9660 unsigned First, unsigned Last, 9661 const SwitchInst *SI, 9662 CaseCluster &BTCluster) { 9663 assert(First <= Last); 9664 if (First == Last) 9665 return false; 9666 9667 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9668 unsigned NumCmps = 0; 9669 for (int64_t I = First; I <= Last; ++I) { 9670 assert(Clusters[I].Kind == CC_Range); 9671 Dests.set(Clusters[I].MBB->getNumber()); 9672 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9673 } 9674 unsigned NumDests = Dests.count(); 9675 9676 APInt Low = Clusters[First].Low->getValue(); 9677 APInt High = Clusters[Last].High->getValue(); 9678 assert(Low.slt(High)); 9679 9680 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9681 const DataLayout &DL = DAG.getDataLayout(); 9682 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9683 return false; 9684 9685 APInt LowBound; 9686 APInt CmpRange; 9687 9688 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9689 assert(TLI.rangeFitsInWord(Low, High, DL) && 9690 "Case range must fit in bit mask!"); 9691 9692 // Check if the clusters cover a contiguous range such that no value in the 9693 // range will jump to the default statement. 9694 bool ContiguousRange = true; 9695 for (int64_t I = First + 1; I <= Last; ++I) { 9696 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9697 ContiguousRange = false; 9698 break; 9699 } 9700 } 9701 9702 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9703 // Optimize the case where all the case values fit in a word without having 9704 // to subtract minValue. In this case, we can optimize away the subtraction. 9705 LowBound = APInt::getNullValue(Low.getBitWidth()); 9706 CmpRange = High; 9707 ContiguousRange = false; 9708 } else { 9709 LowBound = Low; 9710 CmpRange = High - Low; 9711 } 9712 9713 CaseBitsVector CBV; 9714 auto TotalProb = BranchProbability::getZero(); 9715 for (unsigned i = First; i <= Last; ++i) { 9716 // Find the CaseBits for this destination. 9717 unsigned j; 9718 for (j = 0; j < CBV.size(); ++j) 9719 if (CBV[j].BB == Clusters[i].MBB) 9720 break; 9721 if (j == CBV.size()) 9722 CBV.push_back( 9723 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9724 CaseBits *CB = &CBV[j]; 9725 9726 // Update Mask, Bits and ExtraProb. 9727 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9728 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9729 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9730 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9731 CB->Bits += Hi - Lo + 1; 9732 CB->ExtraProb += Clusters[i].Prob; 9733 TotalProb += Clusters[i].Prob; 9734 } 9735 9736 BitTestInfo BTI; 9737 llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) { 9738 // Sort by probability first, number of bits second, bit mask third. 9739 if (a.ExtraProb != b.ExtraProb) 9740 return a.ExtraProb > b.ExtraProb; 9741 if (a.Bits != b.Bits) 9742 return a.Bits > b.Bits; 9743 return a.Mask < b.Mask; 9744 }); 9745 9746 for (auto &CB : CBV) { 9747 MachineBasicBlock *BitTestBB = 9748 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9749 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9750 } 9751 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9752 SI->getCondition(), -1U, MVT::Other, false, 9753 ContiguousRange, nullptr, nullptr, std::move(BTI), 9754 TotalProb); 9755 9756 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9757 BitTestCases.size() - 1, TotalProb); 9758 return true; 9759 } 9760 9761 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9762 const SwitchInst *SI) { 9763 // Partition Clusters into as few subsets as possible, where each subset has a 9764 // range that fits in a machine word and has <= 3 unique destinations. 9765 9766 #ifndef NDEBUG 9767 // Clusters must be sorted and contain Range or JumpTable clusters. 9768 assert(!Clusters.empty()); 9769 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9770 for (const CaseCluster &C : Clusters) 9771 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9772 for (unsigned i = 1; i < Clusters.size(); ++i) 9773 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9774 #endif 9775 9776 // The algorithm below is not suitable for -O0. 9777 if (TM.getOptLevel() == CodeGenOpt::None) 9778 return; 9779 9780 // If target does not have legal shift left, do not emit bit tests at all. 9781 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9782 const DataLayout &DL = DAG.getDataLayout(); 9783 9784 EVT PTy = TLI.getPointerTy(DL); 9785 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9786 return; 9787 9788 int BitWidth = PTy.getSizeInBits(); 9789 const int64_t N = Clusters.size(); 9790 9791 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9792 SmallVector<unsigned, 8> MinPartitions(N); 9793 // LastElement[i] is the last element of the partition starting at i. 9794 SmallVector<unsigned, 8> LastElement(N); 9795 9796 // FIXME: This might not be the best algorithm for finding bit test clusters. 9797 9798 // Base case: There is only one way to partition Clusters[N-1]. 9799 MinPartitions[N - 1] = 1; 9800 LastElement[N - 1] = N - 1; 9801 9802 // Note: loop indexes are signed to avoid underflow. 9803 for (int64_t i = N - 2; i >= 0; --i) { 9804 // Find optimal partitioning of Clusters[i..N-1]. 9805 // Baseline: Put Clusters[i] into a partition on its own. 9806 MinPartitions[i] = MinPartitions[i + 1] + 1; 9807 LastElement[i] = i; 9808 9809 // Search for a solution that results in fewer partitions. 9810 // Note: the search is limited by BitWidth, reducing time complexity. 9811 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9812 // Try building a partition from Clusters[i..j]. 9813 9814 // Check the range. 9815 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9816 Clusters[j].High->getValue(), DL)) 9817 continue; 9818 9819 // Check nbr of destinations and cluster types. 9820 // FIXME: This works, but doesn't seem very efficient. 9821 bool RangesOnly = true; 9822 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9823 for (int64_t k = i; k <= j; k++) { 9824 if (Clusters[k].Kind != CC_Range) { 9825 RangesOnly = false; 9826 break; 9827 } 9828 Dests.set(Clusters[k].MBB->getNumber()); 9829 } 9830 if (!RangesOnly || Dests.count() > 3) 9831 break; 9832 9833 // Check if it's a better partition. 9834 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9835 if (NumPartitions < MinPartitions[i]) { 9836 // Found a better partition. 9837 MinPartitions[i] = NumPartitions; 9838 LastElement[i] = j; 9839 } 9840 } 9841 } 9842 9843 // Iterate over the partitions, replacing with bit-test clusters in-place. 9844 unsigned DstIndex = 0; 9845 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9846 Last = LastElement[First]; 9847 assert(First <= Last); 9848 assert(DstIndex <= First); 9849 9850 CaseCluster BitTestCluster; 9851 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9852 Clusters[DstIndex++] = BitTestCluster; 9853 } else { 9854 size_t NumClusters = Last - First + 1; 9855 std::memmove(&Clusters[DstIndex], &Clusters[First], 9856 sizeof(Clusters[0]) * NumClusters); 9857 DstIndex += NumClusters; 9858 } 9859 } 9860 Clusters.resize(DstIndex); 9861 } 9862 9863 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9864 MachineBasicBlock *SwitchMBB, 9865 MachineBasicBlock *DefaultMBB) { 9866 MachineFunction *CurMF = FuncInfo.MF; 9867 MachineBasicBlock *NextMBB = nullptr; 9868 MachineFunction::iterator BBI(W.MBB); 9869 if (++BBI != FuncInfo.MF->end()) 9870 NextMBB = &*BBI; 9871 9872 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9873 9874 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9875 9876 if (Size == 2 && W.MBB == SwitchMBB) { 9877 // If any two of the cases has the same destination, and if one value 9878 // is the same as the other, but has one bit unset that the other has set, 9879 // use bit manipulation to do two compares at once. For example: 9880 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9881 // TODO: This could be extended to merge any 2 cases in switches with 3 9882 // cases. 9883 // TODO: Handle cases where W.CaseBB != SwitchBB. 9884 CaseCluster &Small = *W.FirstCluster; 9885 CaseCluster &Big = *W.LastCluster; 9886 9887 if (Small.Low == Small.High && Big.Low == Big.High && 9888 Small.MBB == Big.MBB) { 9889 const APInt &SmallValue = Small.Low->getValue(); 9890 const APInt &BigValue = Big.Low->getValue(); 9891 9892 // Check that there is only one bit different. 9893 APInt CommonBit = BigValue ^ SmallValue; 9894 if (CommonBit.isPowerOf2()) { 9895 SDValue CondLHS = getValue(Cond); 9896 EVT VT = CondLHS.getValueType(); 9897 SDLoc DL = getCurSDLoc(); 9898 9899 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9900 DAG.getConstant(CommonBit, DL, VT)); 9901 SDValue Cond = DAG.getSetCC( 9902 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9903 ISD::SETEQ); 9904 9905 // Update successor info. 9906 // Both Small and Big will jump to Small.BB, so we sum up the 9907 // probabilities. 9908 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9909 if (BPI) 9910 addSuccessorWithProb( 9911 SwitchMBB, DefaultMBB, 9912 // The default destination is the first successor in IR. 9913 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 9914 else 9915 addSuccessorWithProb(SwitchMBB, DefaultMBB); 9916 9917 // Insert the true branch. 9918 SDValue BrCond = 9919 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 9920 DAG.getBasicBlock(Small.MBB)); 9921 // Insert the false branch. 9922 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 9923 DAG.getBasicBlock(DefaultMBB)); 9924 9925 DAG.setRoot(BrCond); 9926 return; 9927 } 9928 } 9929 } 9930 9931 if (TM.getOptLevel() != CodeGenOpt::None) { 9932 // Here, we order cases by probability so the most likely case will be 9933 // checked first. However, two clusters can have the same probability in 9934 // which case their relative ordering is non-deterministic. So we use Low 9935 // as a tie-breaker as clusters are guaranteed to never overlap. 9936 llvm::sort(W.FirstCluster, W.LastCluster + 1, 9937 [](const CaseCluster &a, const CaseCluster &b) { 9938 return a.Prob != b.Prob ? 9939 a.Prob > b.Prob : 9940 a.Low->getValue().slt(b.Low->getValue()); 9941 }); 9942 9943 // Rearrange the case blocks so that the last one falls through if possible 9944 // without changing the order of probabilities. 9945 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 9946 --I; 9947 if (I->Prob > W.LastCluster->Prob) 9948 break; 9949 if (I->Kind == CC_Range && I->MBB == NextMBB) { 9950 std::swap(*I, *W.LastCluster); 9951 break; 9952 } 9953 } 9954 } 9955 9956 // Compute total probability. 9957 BranchProbability DefaultProb = W.DefaultProb; 9958 BranchProbability UnhandledProbs = DefaultProb; 9959 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 9960 UnhandledProbs += I->Prob; 9961 9962 MachineBasicBlock *CurMBB = W.MBB; 9963 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 9964 MachineBasicBlock *Fallthrough; 9965 if (I == W.LastCluster) { 9966 // For the last cluster, fall through to the default destination. 9967 Fallthrough = DefaultMBB; 9968 } else { 9969 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 9970 CurMF->insert(BBI, Fallthrough); 9971 // Put Cond in a virtual register to make it available from the new blocks. 9972 ExportFromCurrentBlock(Cond); 9973 } 9974 UnhandledProbs -= I->Prob; 9975 9976 switch (I->Kind) { 9977 case CC_JumpTable: { 9978 // FIXME: Optimize away range check based on pivot comparisons. 9979 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 9980 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 9981 9982 // The jump block hasn't been inserted yet; insert it here. 9983 MachineBasicBlock *JumpMBB = JT->MBB; 9984 CurMF->insert(BBI, JumpMBB); 9985 9986 auto JumpProb = I->Prob; 9987 auto FallthroughProb = UnhandledProbs; 9988 9989 // If the default statement is a target of the jump table, we evenly 9990 // distribute the default probability to successors of CurMBB. Also 9991 // update the probability on the edge from JumpMBB to Fallthrough. 9992 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 9993 SE = JumpMBB->succ_end(); 9994 SI != SE; ++SI) { 9995 if (*SI == DefaultMBB) { 9996 JumpProb += DefaultProb / 2; 9997 FallthroughProb -= DefaultProb / 2; 9998 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 9999 JumpMBB->normalizeSuccProbs(); 10000 break; 10001 } 10002 } 10003 10004 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10005 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10006 CurMBB->normalizeSuccProbs(); 10007 10008 // The jump table header will be inserted in our current block, do the 10009 // range check, and fall through to our fallthrough block. 10010 JTH->HeaderBB = CurMBB; 10011 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10012 10013 // If we're in the right place, emit the jump table header right now. 10014 if (CurMBB == SwitchMBB) { 10015 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10016 JTH->Emitted = true; 10017 } 10018 break; 10019 } 10020 case CC_BitTests: { 10021 // FIXME: Optimize away range check based on pivot comparisons. 10022 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 10023 10024 // The bit test blocks haven't been inserted yet; insert them here. 10025 for (BitTestCase &BTC : BTB->Cases) 10026 CurMF->insert(BBI, BTC.ThisBB); 10027 10028 // Fill in fields of the BitTestBlock. 10029 BTB->Parent = CurMBB; 10030 BTB->Default = Fallthrough; 10031 10032 BTB->DefaultProb = UnhandledProbs; 10033 // If the cases in bit test don't form a contiguous range, we evenly 10034 // distribute the probability on the edge to Fallthrough to two 10035 // successors of CurMBB. 10036 if (!BTB->ContiguousRange) { 10037 BTB->Prob += DefaultProb / 2; 10038 BTB->DefaultProb -= DefaultProb / 2; 10039 } 10040 10041 // If we're in the right place, emit the bit test header right now. 10042 if (CurMBB == SwitchMBB) { 10043 visitBitTestHeader(*BTB, SwitchMBB); 10044 BTB->Emitted = true; 10045 } 10046 break; 10047 } 10048 case CC_Range: { 10049 const Value *RHS, *LHS, *MHS; 10050 ISD::CondCode CC; 10051 if (I->Low == I->High) { 10052 // Check Cond == I->Low. 10053 CC = ISD::SETEQ; 10054 LHS = Cond; 10055 RHS=I->Low; 10056 MHS = nullptr; 10057 } else { 10058 // Check I->Low <= Cond <= I->High. 10059 CC = ISD::SETLE; 10060 LHS = I->Low; 10061 MHS = Cond; 10062 RHS = I->High; 10063 } 10064 10065 // The false probability is the sum of all unhandled cases. 10066 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10067 getCurSDLoc(), I->Prob, UnhandledProbs); 10068 10069 if (CurMBB == SwitchMBB) 10070 visitSwitchCase(CB, SwitchMBB); 10071 else 10072 SwitchCases.push_back(CB); 10073 10074 break; 10075 } 10076 } 10077 CurMBB = Fallthrough; 10078 } 10079 } 10080 10081 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10082 CaseClusterIt First, 10083 CaseClusterIt Last) { 10084 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10085 if (X.Prob != CC.Prob) 10086 return X.Prob > CC.Prob; 10087 10088 // Ties are broken by comparing the case value. 10089 return X.Low->getValue().slt(CC.Low->getValue()); 10090 }); 10091 } 10092 10093 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10094 const SwitchWorkListItem &W, 10095 Value *Cond, 10096 MachineBasicBlock *SwitchMBB) { 10097 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10098 "Clusters not sorted?"); 10099 10100 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10101 10102 // Balance the tree based on branch probabilities to create a near-optimal (in 10103 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10104 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10105 CaseClusterIt LastLeft = W.FirstCluster; 10106 CaseClusterIt FirstRight = W.LastCluster; 10107 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10108 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10109 10110 // Move LastLeft and FirstRight towards each other from opposite directions to 10111 // find a partitioning of the clusters which balances the probability on both 10112 // sides. If LeftProb and RightProb are equal, alternate which side is 10113 // taken to ensure 0-probability nodes are distributed evenly. 10114 unsigned I = 0; 10115 while (LastLeft + 1 < FirstRight) { 10116 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10117 LeftProb += (++LastLeft)->Prob; 10118 else 10119 RightProb += (--FirstRight)->Prob; 10120 I++; 10121 } 10122 10123 while (true) { 10124 // Our binary search tree differs from a typical BST in that ours can have up 10125 // to three values in each leaf. The pivot selection above doesn't take that 10126 // into account, which means the tree might require more nodes and be less 10127 // efficient. We compensate for this here. 10128 10129 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10130 unsigned NumRight = W.LastCluster - FirstRight + 1; 10131 10132 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10133 // If one side has less than 3 clusters, and the other has more than 3, 10134 // consider taking a cluster from the other side. 10135 10136 if (NumLeft < NumRight) { 10137 // Consider moving the first cluster on the right to the left side. 10138 CaseCluster &CC = *FirstRight; 10139 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10140 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10141 if (LeftSideRank <= RightSideRank) { 10142 // Moving the cluster to the left does not demote it. 10143 ++LastLeft; 10144 ++FirstRight; 10145 continue; 10146 } 10147 } else { 10148 assert(NumRight < NumLeft); 10149 // Consider moving the last element on the left to the right side. 10150 CaseCluster &CC = *LastLeft; 10151 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10152 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10153 if (RightSideRank <= LeftSideRank) { 10154 // Moving the cluster to the right does not demot it. 10155 --LastLeft; 10156 --FirstRight; 10157 continue; 10158 } 10159 } 10160 } 10161 break; 10162 } 10163 10164 assert(LastLeft + 1 == FirstRight); 10165 assert(LastLeft >= W.FirstCluster); 10166 assert(FirstRight <= W.LastCluster); 10167 10168 // Use the first element on the right as pivot since we will make less-than 10169 // comparisons against it. 10170 CaseClusterIt PivotCluster = FirstRight; 10171 assert(PivotCluster > W.FirstCluster); 10172 assert(PivotCluster <= W.LastCluster); 10173 10174 CaseClusterIt FirstLeft = W.FirstCluster; 10175 CaseClusterIt LastRight = W.LastCluster; 10176 10177 const ConstantInt *Pivot = PivotCluster->Low; 10178 10179 // New blocks will be inserted immediately after the current one. 10180 MachineFunction::iterator BBI(W.MBB); 10181 ++BBI; 10182 10183 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10184 // we can branch to its destination directly if it's squeezed exactly in 10185 // between the known lower bound and Pivot - 1. 10186 MachineBasicBlock *LeftMBB; 10187 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10188 FirstLeft->Low == W.GE && 10189 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10190 LeftMBB = FirstLeft->MBB; 10191 } else { 10192 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10193 FuncInfo.MF->insert(BBI, LeftMBB); 10194 WorkList.push_back( 10195 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10196 // Put Cond in a virtual register to make it available from the new blocks. 10197 ExportFromCurrentBlock(Cond); 10198 } 10199 10200 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10201 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10202 // directly if RHS.High equals the current upper bound. 10203 MachineBasicBlock *RightMBB; 10204 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10205 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10206 RightMBB = FirstRight->MBB; 10207 } else { 10208 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10209 FuncInfo.MF->insert(BBI, RightMBB); 10210 WorkList.push_back( 10211 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10212 // Put Cond in a virtual register to make it available from the new blocks. 10213 ExportFromCurrentBlock(Cond); 10214 } 10215 10216 // Create the CaseBlock record that will be used to lower the branch. 10217 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10218 getCurSDLoc(), LeftProb, RightProb); 10219 10220 if (W.MBB == SwitchMBB) 10221 visitSwitchCase(CB, SwitchMBB); 10222 else 10223 SwitchCases.push_back(CB); 10224 } 10225 10226 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10227 // from the swith statement. 10228 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10229 BranchProbability PeeledCaseProb) { 10230 if (PeeledCaseProb == BranchProbability::getOne()) 10231 return BranchProbability::getZero(); 10232 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10233 10234 uint32_t Numerator = CaseProb.getNumerator(); 10235 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10236 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10237 } 10238 10239 // Try to peel the top probability case if it exceeds the threshold. 10240 // Return current MachineBasicBlock for the switch statement if the peeling 10241 // does not occur. 10242 // If the peeling is performed, return the newly created MachineBasicBlock 10243 // for the peeled switch statement. Also update Clusters to remove the peeled 10244 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10245 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10246 const SwitchInst &SI, CaseClusterVector &Clusters, 10247 BranchProbability &PeeledCaseProb) { 10248 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10249 // Don't perform if there is only one cluster or optimizing for size. 10250 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10251 TM.getOptLevel() == CodeGenOpt::None || 10252 SwitchMBB->getParent()->getFunction().optForMinSize()) 10253 return SwitchMBB; 10254 10255 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10256 unsigned PeeledCaseIndex = 0; 10257 bool SwitchPeeled = false; 10258 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10259 CaseCluster &CC = Clusters[Index]; 10260 if (CC.Prob < TopCaseProb) 10261 continue; 10262 TopCaseProb = CC.Prob; 10263 PeeledCaseIndex = Index; 10264 SwitchPeeled = true; 10265 } 10266 if (!SwitchPeeled) 10267 return SwitchMBB; 10268 10269 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10270 << TopCaseProb << "\n"); 10271 10272 // Record the MBB for the peeled switch statement. 10273 MachineFunction::iterator BBI(SwitchMBB); 10274 ++BBI; 10275 MachineBasicBlock *PeeledSwitchMBB = 10276 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10277 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10278 10279 ExportFromCurrentBlock(SI.getCondition()); 10280 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10281 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10282 nullptr, nullptr, TopCaseProb.getCompl()}; 10283 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10284 10285 Clusters.erase(PeeledCaseIt); 10286 for (CaseCluster &CC : Clusters) { 10287 LLVM_DEBUG( 10288 dbgs() << "Scale the probablity for one cluster, before scaling: " 10289 << CC.Prob << "\n"); 10290 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10291 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10292 } 10293 PeeledCaseProb = TopCaseProb; 10294 return PeeledSwitchMBB; 10295 } 10296 10297 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10298 // Extract cases from the switch. 10299 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10300 CaseClusterVector Clusters; 10301 Clusters.reserve(SI.getNumCases()); 10302 for (auto I : SI.cases()) { 10303 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10304 const ConstantInt *CaseVal = I.getCaseValue(); 10305 BranchProbability Prob = 10306 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10307 : BranchProbability(1, SI.getNumCases() + 1); 10308 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10309 } 10310 10311 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10312 10313 // Cluster adjacent cases with the same destination. We do this at all 10314 // optimization levels because it's cheap to do and will make codegen faster 10315 // if there are many clusters. 10316 sortAndRangeify(Clusters); 10317 10318 // The branch probablity of the peeled case. 10319 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10320 MachineBasicBlock *PeeledSwitchMBB = 10321 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10322 10323 // If there is only the default destination, jump there directly. 10324 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10325 if (Clusters.empty()) { 10326 assert(PeeledSwitchMBB == SwitchMBB); 10327 SwitchMBB->addSuccessor(DefaultMBB); 10328 if (DefaultMBB != NextBlock(SwitchMBB)) { 10329 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10330 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10331 } 10332 return; 10333 } 10334 10335 findJumpTables(Clusters, &SI, DefaultMBB); 10336 findBitTestClusters(Clusters, &SI); 10337 10338 LLVM_DEBUG({ 10339 dbgs() << "Case clusters: "; 10340 for (const CaseCluster &C : Clusters) { 10341 if (C.Kind == CC_JumpTable) 10342 dbgs() << "JT:"; 10343 if (C.Kind == CC_BitTests) 10344 dbgs() << "BT:"; 10345 10346 C.Low->getValue().print(dbgs(), true); 10347 if (C.Low != C.High) { 10348 dbgs() << '-'; 10349 C.High->getValue().print(dbgs(), true); 10350 } 10351 dbgs() << ' '; 10352 } 10353 dbgs() << '\n'; 10354 }); 10355 10356 assert(!Clusters.empty()); 10357 SwitchWorkList WorkList; 10358 CaseClusterIt First = Clusters.begin(); 10359 CaseClusterIt Last = Clusters.end() - 1; 10360 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10361 // Scale the branchprobability for DefaultMBB if the peel occurs and 10362 // DefaultMBB is not replaced. 10363 if (PeeledCaseProb != BranchProbability::getZero() && 10364 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10365 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10366 WorkList.push_back( 10367 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10368 10369 while (!WorkList.empty()) { 10370 SwitchWorkListItem W = WorkList.back(); 10371 WorkList.pop_back(); 10372 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10373 10374 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10375 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10376 // For optimized builds, lower large range as a balanced binary tree. 10377 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10378 continue; 10379 } 10380 10381 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10382 } 10383 } 10384