1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Triple.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Analysis/AliasAnalysis.h" 30 #include "llvm/Analysis/BranchProbabilityInfo.h" 31 #include "llvm/Analysis/ConstantFolding.h" 32 #include "llvm/Analysis/EHPersonalities.h" 33 #include "llvm/Analysis/Loads.h" 34 #include "llvm/Analysis/MemoryLocation.h" 35 #include "llvm/Analysis/TargetLibraryInfo.h" 36 #include "llvm/Analysis/ValueTracking.h" 37 #include "llvm/Analysis/VectorUtils.h" 38 #include "llvm/CodeGen/Analysis.h" 39 #include "llvm/CodeGen/FunctionLoweringInfo.h" 40 #include "llvm/CodeGen/GCMetadata.h" 41 #include "llvm/CodeGen/ISDOpcodes.h" 42 #include "llvm/CodeGen/MachineBasicBlock.h" 43 #include "llvm/CodeGen/MachineFrameInfo.h" 44 #include "llvm/CodeGen/MachineFunction.h" 45 #include "llvm/CodeGen/MachineInstr.h" 46 #include "llvm/CodeGen/MachineInstrBuilder.h" 47 #include "llvm/CodeGen/MachineJumpTableInfo.h" 48 #include "llvm/CodeGen/MachineMemOperand.h" 49 #include "llvm/CodeGen/MachineModuleInfo.h" 50 #include "llvm/CodeGen/MachineOperand.h" 51 #include "llvm/CodeGen/MachineRegisterInfo.h" 52 #include "llvm/CodeGen/RuntimeLibcalls.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 56 #include "llvm/CodeGen/StackMaps.h" 57 #include "llvm/CodeGen/TargetFrameLowering.h" 58 #include "llvm/CodeGen/TargetInstrInfo.h" 59 #include "llvm/CodeGen/TargetLowering.h" 60 #include "llvm/CodeGen/TargetOpcodes.h" 61 #include "llvm/CodeGen/TargetRegisterInfo.h" 62 #include "llvm/CodeGen/TargetSubtargetInfo.h" 63 #include "llvm/CodeGen/ValueTypes.h" 64 #include "llvm/CodeGen/WinEHFuncInfo.h" 65 #include "llvm/IR/Argument.h" 66 #include "llvm/IR/Attributes.h" 67 #include "llvm/IR/BasicBlock.h" 68 #include "llvm/IR/CFG.h" 69 #include "llvm/IR/CallSite.h" 70 #include "llvm/IR/CallingConv.h" 71 #include "llvm/IR/Constant.h" 72 #include "llvm/IR/ConstantRange.h" 73 #include "llvm/IR/Constants.h" 74 #include "llvm/IR/DataLayout.h" 75 #include "llvm/IR/DebugInfoMetadata.h" 76 #include "llvm/IR/DebugLoc.h" 77 #include "llvm/IR/DerivedTypes.h" 78 #include "llvm/IR/Function.h" 79 #include "llvm/IR/GetElementPtrTypeIterator.h" 80 #include "llvm/IR/InlineAsm.h" 81 #include "llvm/IR/InstrTypes.h" 82 #include "llvm/IR/Instruction.h" 83 #include "llvm/IR/Instructions.h" 84 #include "llvm/IR/IntrinsicInst.h" 85 #include "llvm/IR/Intrinsics.h" 86 #include "llvm/IR/LLVMContext.h" 87 #include "llvm/IR/Metadata.h" 88 #include "llvm/IR/Module.h" 89 #include "llvm/IR/Operator.h" 90 #include "llvm/IR/PatternMatch.h" 91 #include "llvm/IR/Statepoint.h" 92 #include "llvm/IR/Type.h" 93 #include "llvm/IR/User.h" 94 #include "llvm/IR/Value.h" 95 #include "llvm/MC/MCContext.h" 96 #include "llvm/MC/MCSymbol.h" 97 #include "llvm/Support/AtomicOrdering.h" 98 #include "llvm/Support/BranchProbability.h" 99 #include "llvm/Support/Casting.h" 100 #include "llvm/Support/CodeGen.h" 101 #include "llvm/Support/CommandLine.h" 102 #include "llvm/Support/Compiler.h" 103 #include "llvm/Support/Debug.h" 104 #include "llvm/Support/ErrorHandling.h" 105 #include "llvm/Support/MachineValueType.h" 106 #include "llvm/Support/MathExtras.h" 107 #include "llvm/Support/raw_ostream.h" 108 #include "llvm/Target/TargetIntrinsicInfo.h" 109 #include "llvm/Target/TargetMachine.h" 110 #include "llvm/Target/TargetOptions.h" 111 #include <algorithm> 112 #include <cassert> 113 #include <cstddef> 114 #include <cstdint> 115 #include <cstring> 116 #include <iterator> 117 #include <limits> 118 #include <numeric> 119 #include <tuple> 120 #include <utility> 121 #include <vector> 122 123 using namespace llvm; 124 using namespace PatternMatch; 125 126 #define DEBUG_TYPE "isel" 127 128 /// LimitFloatPrecision - Generate low-precision inline sequences for 129 /// some float libcalls (6, 8 or 12 bits). 130 static unsigned LimitFloatPrecision; 131 132 static cl::opt<unsigned, true> 133 LimitFPPrecision("limit-float-precision", 134 cl::desc("Generate low-precision inline sequences " 135 "for some float libcalls"), 136 cl::location(LimitFloatPrecision), cl::Hidden, 137 cl::init(0)); 138 139 static cl::opt<unsigned> SwitchPeelThreshold( 140 "switch-peel-threshold", cl::Hidden, cl::init(66), 141 cl::desc("Set the case probability threshold for peeling the case from a " 142 "switch statement. A value greater than 100 will void this " 143 "optimization")); 144 145 // Limit the width of DAG chains. This is important in general to prevent 146 // DAG-based analysis from blowing up. For example, alias analysis and 147 // load clustering may not complete in reasonable time. It is difficult to 148 // recognize and avoid this situation within each individual analysis, and 149 // future analyses are likely to have the same behavior. Limiting DAG width is 150 // the safe approach and will be especially important with global DAGs. 151 // 152 // MaxParallelChains default is arbitrarily high to avoid affecting 153 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 154 // sequence over this should have been converted to llvm.memcpy by the 155 // frontend. It is easy to induce this behavior with .ll code such as: 156 // %buffer = alloca [4096 x i8] 157 // %data = load [4096 x i8]* %argPtr 158 // store [4096 x i8] %data, [4096 x i8]* %buffer 159 static const unsigned MaxParallelChains = 64; 160 161 // Return the calling convention if the Value passed requires ABI mangling as it 162 // is a parameter to a function or a return value from a function which is not 163 // an intrinsic. 164 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 165 if (auto *R = dyn_cast<ReturnInst>(V)) 166 return R->getParent()->getParent()->getCallingConv(); 167 168 if (auto *CI = dyn_cast<CallInst>(V)) { 169 const bool IsInlineAsm = CI->isInlineAsm(); 170 const bool IsIndirectFunctionCall = 171 !IsInlineAsm && !CI->getCalledFunction(); 172 173 // It is possible that the call instruction is an inline asm statement or an 174 // indirect function call in which case the return value of 175 // getCalledFunction() would be nullptr. 176 const bool IsInstrinsicCall = 177 !IsInlineAsm && !IsIndirectFunctionCall && 178 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 179 180 if (!IsInlineAsm && !IsInstrinsicCall) 181 return CI->getCallingConv(); 182 } 183 184 return None; 185 } 186 187 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 188 const SDValue *Parts, unsigned NumParts, 189 MVT PartVT, EVT ValueVT, const Value *V, 190 Optional<CallingConv::ID> CC); 191 192 /// getCopyFromParts - Create a value that contains the specified legal parts 193 /// combined into the value they represent. If the parts combine to a type 194 /// larger than ValueVT then AssertOp can be used to specify whether the extra 195 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 196 /// (ISD::AssertSext). 197 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 198 const SDValue *Parts, unsigned NumParts, 199 MVT PartVT, EVT ValueVT, const Value *V, 200 Optional<CallingConv::ID> CC = None, 201 Optional<ISD::NodeType> AssertOp = None) { 202 if (ValueVT.isVector()) 203 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 204 CC); 205 206 assert(NumParts > 0 && "No parts to assemble!"); 207 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 208 SDValue Val = Parts[0]; 209 210 if (NumParts > 1) { 211 // Assemble the value from multiple parts. 212 if (ValueVT.isInteger()) { 213 unsigned PartBits = PartVT.getSizeInBits(); 214 unsigned ValueBits = ValueVT.getSizeInBits(); 215 216 // Assemble the power of 2 part. 217 unsigned RoundParts = NumParts & (NumParts - 1) ? 218 1 << Log2_32(NumParts) : NumParts; 219 unsigned RoundBits = PartBits * RoundParts; 220 EVT RoundVT = RoundBits == ValueBits ? 221 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 222 SDValue Lo, Hi; 223 224 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 225 226 if (RoundParts > 2) { 227 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 228 PartVT, HalfVT, V); 229 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 230 RoundParts / 2, PartVT, HalfVT, V); 231 } else { 232 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 233 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 234 } 235 236 if (DAG.getDataLayout().isBigEndian()) 237 std::swap(Lo, Hi); 238 239 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 240 241 if (RoundParts < NumParts) { 242 // Assemble the trailing non-power-of-2 part. 243 unsigned OddParts = NumParts - RoundParts; 244 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 245 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 246 OddVT, V, CC); 247 248 // Combine the round and odd parts. 249 Lo = Val; 250 if (DAG.getDataLayout().isBigEndian()) 251 std::swap(Lo, Hi); 252 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 253 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 254 Hi = 255 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 256 DAG.getConstant(Lo.getValueSizeInBits(), DL, 257 TLI.getPointerTy(DAG.getDataLayout()))); 258 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 259 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 260 } 261 } else if (PartVT.isFloatingPoint()) { 262 // FP split into multiple FP parts (for ppcf128) 263 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 264 "Unexpected split"); 265 SDValue Lo, Hi; 266 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 267 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 268 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 269 std::swap(Lo, Hi); 270 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 271 } else { 272 // FP split into integer parts (soft fp) 273 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 274 !PartVT.isVector() && "Unexpected split"); 275 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 276 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 277 } 278 } 279 280 // There is now one part, held in Val. Correct it to match ValueVT. 281 // PartEVT is the type of the register class that holds the value. 282 // ValueVT is the type of the inline asm operation. 283 EVT PartEVT = Val.getValueType(); 284 285 if (PartEVT == ValueVT) 286 return Val; 287 288 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 289 ValueVT.bitsLT(PartEVT)) { 290 // For an FP value in an integer part, we need to truncate to the right 291 // width first. 292 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 293 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 294 } 295 296 // Handle types that have the same size. 297 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 298 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 299 300 // Handle types with different sizes. 301 if (PartEVT.isInteger() && ValueVT.isInteger()) { 302 if (ValueVT.bitsLT(PartEVT)) { 303 // For a truncate, see if we have any information to 304 // indicate whether the truncated bits will always be 305 // zero or sign-extension. 306 if (AssertOp.hasValue()) 307 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 308 DAG.getValueType(ValueVT)); 309 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 310 } 311 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 312 } 313 314 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 315 // FP_ROUND's are always exact here. 316 if (ValueVT.bitsLT(Val.getValueType())) 317 return DAG.getNode( 318 ISD::FP_ROUND, DL, ValueVT, Val, 319 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 320 321 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 322 } 323 324 llvm_unreachable("Unknown mismatch!"); 325 } 326 327 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 328 const Twine &ErrMsg) { 329 const Instruction *I = dyn_cast_or_null<Instruction>(V); 330 if (!V) 331 return Ctx.emitError(ErrMsg); 332 333 const char *AsmError = ", possible invalid constraint for vector type"; 334 if (const CallInst *CI = dyn_cast<CallInst>(I)) 335 if (isa<InlineAsm>(CI->getCalledValue())) 336 return Ctx.emitError(I, ErrMsg + AsmError); 337 338 return Ctx.emitError(I, ErrMsg); 339 } 340 341 /// getCopyFromPartsVector - Create a value that contains the specified legal 342 /// parts combined into the value they represent. If the parts combine to a 343 /// type larger than ValueVT then AssertOp can be used to specify whether the 344 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 345 /// ValueVT (ISD::AssertSext). 346 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 347 const SDValue *Parts, unsigned NumParts, 348 MVT PartVT, EVT ValueVT, const Value *V, 349 Optional<CallingConv::ID> CallConv) { 350 assert(ValueVT.isVector() && "Not a vector value"); 351 assert(NumParts > 0 && "No parts to assemble!"); 352 const bool IsABIRegCopy = CallConv.hasValue(); 353 354 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 355 SDValue Val = Parts[0]; 356 357 // Handle a multi-element vector. 358 if (NumParts > 1) { 359 EVT IntermediateVT; 360 MVT RegisterVT; 361 unsigned NumIntermediates; 362 unsigned NumRegs; 363 364 if (IsABIRegCopy) { 365 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 366 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 367 NumIntermediates, RegisterVT); 368 } else { 369 NumRegs = 370 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 371 NumIntermediates, RegisterVT); 372 } 373 374 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 375 NumParts = NumRegs; // Silence a compiler warning. 376 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 377 assert(RegisterVT.getSizeInBits() == 378 Parts[0].getSimpleValueType().getSizeInBits() && 379 "Part type sizes don't match!"); 380 381 // Assemble the parts into intermediate operands. 382 SmallVector<SDValue, 8> Ops(NumIntermediates); 383 if (NumIntermediates == NumParts) { 384 // If the register was not expanded, truncate or copy the value, 385 // as appropriate. 386 for (unsigned i = 0; i != NumParts; ++i) 387 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 388 PartVT, IntermediateVT, V); 389 } else if (NumParts > 0) { 390 // If the intermediate type was expanded, build the intermediate 391 // operands from the parts. 392 assert(NumParts % NumIntermediates == 0 && 393 "Must expand into a divisible number of parts!"); 394 unsigned Factor = NumParts / NumIntermediates; 395 for (unsigned i = 0; i != NumIntermediates; ++i) 396 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 397 PartVT, IntermediateVT, V); 398 } 399 400 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 401 // intermediate operands. 402 EVT BuiltVectorTy = 403 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 404 (IntermediateVT.isVector() 405 ? IntermediateVT.getVectorNumElements() * NumParts 406 : NumIntermediates)); 407 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 408 : ISD::BUILD_VECTOR, 409 DL, BuiltVectorTy, Ops); 410 } 411 412 // There is now one part, held in Val. Correct it to match ValueVT. 413 EVT PartEVT = Val.getValueType(); 414 415 if (PartEVT == ValueVT) 416 return Val; 417 418 if (PartEVT.isVector()) { 419 // If the element type of the source/dest vectors are the same, but the 420 // parts vector has more elements than the value vector, then we have a 421 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 422 // elements we want. 423 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 424 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 425 "Cannot narrow, it would be a lossy transformation"); 426 return DAG.getNode( 427 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 428 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 429 } 430 431 // Vector/Vector bitcast. 432 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 433 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 434 435 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 436 "Cannot handle this kind of promotion"); 437 // Promoted vector extract 438 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 439 440 } 441 442 // Trivial bitcast if the types are the same size and the destination 443 // vector type is legal. 444 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 445 TLI.isTypeLegal(ValueVT)) 446 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 447 448 if (ValueVT.getVectorNumElements() != 1) { 449 // Certain ABIs require that vectors are passed as integers. For vectors 450 // are the same size, this is an obvious bitcast. 451 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 452 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 453 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 454 // Bitcast Val back the original type and extract the corresponding 455 // vector we want. 456 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 457 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 458 ValueVT.getVectorElementType(), Elts); 459 Val = DAG.getBitcast(WiderVecType, Val); 460 return DAG.getNode( 461 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 462 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 463 } 464 465 diagnosePossiblyInvalidConstraint( 466 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 467 return DAG.getUNDEF(ValueVT); 468 } 469 470 // Handle cases such as i8 -> <1 x i1> 471 EVT ValueSVT = ValueVT.getVectorElementType(); 472 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 473 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 474 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 475 476 return DAG.getBuildVector(ValueVT, DL, Val); 477 } 478 479 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 480 SDValue Val, SDValue *Parts, unsigned NumParts, 481 MVT PartVT, const Value *V, 482 Optional<CallingConv::ID> CallConv); 483 484 /// getCopyToParts - Create a series of nodes that contain the specified value 485 /// split into legal parts. If the parts contain more bits than Val, then, for 486 /// integers, ExtendKind can be used to specify how to generate the extra bits. 487 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 488 SDValue *Parts, unsigned NumParts, MVT PartVT, 489 const Value *V, 490 Optional<CallingConv::ID> CallConv = None, 491 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 492 EVT ValueVT = Val.getValueType(); 493 494 // Handle the vector case separately. 495 if (ValueVT.isVector()) 496 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 497 CallConv); 498 499 unsigned PartBits = PartVT.getSizeInBits(); 500 unsigned OrigNumParts = NumParts; 501 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 502 "Copying to an illegal type!"); 503 504 if (NumParts == 0) 505 return; 506 507 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 508 EVT PartEVT = PartVT; 509 if (PartEVT == ValueVT) { 510 assert(NumParts == 1 && "No-op copy with multiple parts!"); 511 Parts[0] = Val; 512 return; 513 } 514 515 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 516 // If the parts cover more bits than the value has, promote the value. 517 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 518 assert(NumParts == 1 && "Do not know what to promote to!"); 519 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 520 } else { 521 if (ValueVT.isFloatingPoint()) { 522 // FP values need to be bitcast, then extended if they are being put 523 // into a larger container. 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 525 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 526 } 527 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 528 ValueVT.isInteger() && 529 "Unknown mismatch!"); 530 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 531 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 532 if (PartVT == MVT::x86mmx) 533 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 534 } 535 } else if (PartBits == ValueVT.getSizeInBits()) { 536 // Different types of the same size. 537 assert(NumParts == 1 && PartEVT != ValueVT); 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 540 // If the parts cover less bits than value has, truncate the value. 541 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 542 ValueVT.isInteger() && 543 "Unknown mismatch!"); 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 545 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 546 if (PartVT == MVT::x86mmx) 547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 548 } 549 550 // The value may have changed - recompute ValueVT. 551 ValueVT = Val.getValueType(); 552 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 553 "Failed to tile the value with PartVT!"); 554 555 if (NumParts == 1) { 556 if (PartEVT != ValueVT) { 557 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 558 "scalar-to-vector conversion failed"); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } 561 562 Parts[0] = Val; 563 return; 564 } 565 566 // Expand the value into multiple parts. 567 if (NumParts & (NumParts - 1)) { 568 // The number of parts is not a power of 2. Split off and copy the tail. 569 assert(PartVT.isInteger() && ValueVT.isInteger() && 570 "Do not know what to expand to!"); 571 unsigned RoundParts = 1 << Log2_32(NumParts); 572 unsigned RoundBits = RoundParts * PartBits; 573 unsigned OddParts = NumParts - RoundParts; 574 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 575 DAG.getIntPtrConstant(RoundBits, DL)); 576 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 577 CallConv); 578 579 if (DAG.getDataLayout().isBigEndian()) 580 // The odd parts were reversed by getCopyToParts - unreverse them. 581 std::reverse(Parts + RoundParts, Parts + NumParts); 582 583 NumParts = RoundParts; 584 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 585 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 586 } 587 588 // The number of parts is a power of 2. Repeatedly bisect the value using 589 // EXTRACT_ELEMENT. 590 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 591 EVT::getIntegerVT(*DAG.getContext(), 592 ValueVT.getSizeInBits()), 593 Val); 594 595 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 596 for (unsigned i = 0; i < NumParts; i += StepSize) { 597 unsigned ThisBits = StepSize * PartBits / 2; 598 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 599 SDValue &Part0 = Parts[i]; 600 SDValue &Part1 = Parts[i+StepSize/2]; 601 602 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 603 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 604 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 605 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 606 607 if (ThisBits == PartBits && ThisVT != PartVT) { 608 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 609 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 610 } 611 } 612 } 613 614 if (DAG.getDataLayout().isBigEndian()) 615 std::reverse(Parts, Parts + OrigNumParts); 616 } 617 618 static SDValue widenVectorToPartType(SelectionDAG &DAG, 619 SDValue Val, const SDLoc &DL, EVT PartVT) { 620 if (!PartVT.isVector()) 621 return SDValue(); 622 623 EVT ValueVT = Val.getValueType(); 624 unsigned PartNumElts = PartVT.getVectorNumElements(); 625 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 626 if (PartNumElts > ValueNumElts && 627 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 628 EVT ElementVT = PartVT.getVectorElementType(); 629 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 630 // undef elements. 631 SmallVector<SDValue, 16> Ops; 632 DAG.ExtractVectorElements(Val, Ops); 633 SDValue EltUndef = DAG.getUNDEF(ElementVT); 634 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 635 Ops.push_back(EltUndef); 636 637 // FIXME: Use CONCAT for 2x -> 4x. 638 return DAG.getBuildVector(PartVT, DL, Ops); 639 } 640 641 return SDValue(); 642 } 643 644 /// getCopyToPartsVector - Create a series of nodes that contain the specified 645 /// value split into legal parts. 646 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 647 SDValue Val, SDValue *Parts, unsigned NumParts, 648 MVT PartVT, const Value *V, 649 Optional<CallingConv::ID> CallConv) { 650 EVT ValueVT = Val.getValueType(); 651 assert(ValueVT.isVector() && "Not a vector"); 652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 653 const bool IsABIRegCopy = CallConv.hasValue(); 654 655 if (NumParts == 1) { 656 EVT PartEVT = PartVT; 657 if (PartEVT == ValueVT) { 658 // Nothing to do. 659 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 660 // Bitconvert vector->vector case. 661 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 662 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 663 Val = Widened; 664 } else if (PartVT.isVector() && 665 PartEVT.getVectorElementType().bitsGE( 666 ValueVT.getVectorElementType()) && 667 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 668 669 // Promoted vector extract 670 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 671 } else { 672 if (ValueVT.getVectorNumElements() == 1) { 673 Val = DAG.getNode( 674 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 675 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 676 } else { 677 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 678 "lossy conversion of vector to scalar type"); 679 EVT IntermediateType = 680 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 681 Val = DAG.getBitcast(IntermediateType, Val); 682 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 683 } 684 } 685 686 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 687 Parts[0] = Val; 688 return; 689 } 690 691 // Handle a multi-element vector. 692 EVT IntermediateVT; 693 MVT RegisterVT; 694 unsigned NumIntermediates; 695 unsigned NumRegs; 696 if (IsABIRegCopy) { 697 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 698 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 699 NumIntermediates, RegisterVT); 700 } else { 701 NumRegs = 702 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 703 NumIntermediates, RegisterVT); 704 } 705 706 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 707 NumParts = NumRegs; // Silence a compiler warning. 708 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 709 710 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 711 IntermediateVT.getVectorNumElements() : 1; 712 713 // Convert the vector to the appropiate type if necessary. 714 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 715 716 EVT BuiltVectorTy = EVT::getVectorVT( 717 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 718 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 719 if (ValueVT != BuiltVectorTy) { 720 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 721 Val = Widened; 722 723 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 724 } 725 726 // Split the vector into intermediate operands. 727 SmallVector<SDValue, 8> Ops(NumIntermediates); 728 for (unsigned i = 0; i != NumIntermediates; ++i) { 729 if (IntermediateVT.isVector()) { 730 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 731 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 732 } else { 733 Ops[i] = DAG.getNode( 734 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 735 DAG.getConstant(i, DL, IdxVT)); 736 } 737 } 738 739 // Split the intermediate operands into legal parts. 740 if (NumParts == NumIntermediates) { 741 // If the register was not expanded, promote or copy the value, 742 // as appropriate. 743 for (unsigned i = 0; i != NumParts; ++i) 744 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 745 } else if (NumParts > 0) { 746 // If the intermediate type was expanded, split each the value into 747 // legal parts. 748 assert(NumIntermediates != 0 && "division by zero"); 749 assert(NumParts % NumIntermediates == 0 && 750 "Must expand into a divisible number of parts!"); 751 unsigned Factor = NumParts / NumIntermediates; 752 for (unsigned i = 0; i != NumIntermediates; ++i) 753 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 754 CallConv); 755 } 756 } 757 758 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 759 EVT valuevt, Optional<CallingConv::ID> CC) 760 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 761 RegCount(1, regs.size()), CallConv(CC) {} 762 763 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 764 const DataLayout &DL, unsigned Reg, Type *Ty, 765 Optional<CallingConv::ID> CC) { 766 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 767 768 CallConv = CC; 769 770 for (EVT ValueVT : ValueVTs) { 771 unsigned NumRegs = 772 isABIMangled() 773 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 774 : TLI.getNumRegisters(Context, ValueVT); 775 MVT RegisterVT = 776 isABIMangled() 777 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 778 : TLI.getRegisterType(Context, ValueVT); 779 for (unsigned i = 0; i != NumRegs; ++i) 780 Regs.push_back(Reg + i); 781 RegVTs.push_back(RegisterVT); 782 RegCount.push_back(NumRegs); 783 Reg += NumRegs; 784 } 785 } 786 787 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 788 FunctionLoweringInfo &FuncInfo, 789 const SDLoc &dl, SDValue &Chain, 790 SDValue *Flag, const Value *V) const { 791 // A Value with type {} or [0 x %t] needs no registers. 792 if (ValueVTs.empty()) 793 return SDValue(); 794 795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 796 797 // Assemble the legal parts into the final values. 798 SmallVector<SDValue, 4> Values(ValueVTs.size()); 799 SmallVector<SDValue, 8> Parts; 800 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 801 // Copy the legal parts from the registers. 802 EVT ValueVT = ValueVTs[Value]; 803 unsigned NumRegs = RegCount[Value]; 804 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 805 *DAG.getContext(), 806 CallConv.getValue(), RegVTs[Value]) 807 : RegVTs[Value]; 808 809 Parts.resize(NumRegs); 810 for (unsigned i = 0; i != NumRegs; ++i) { 811 SDValue P; 812 if (!Flag) { 813 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 814 } else { 815 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 816 *Flag = P.getValue(2); 817 } 818 819 Chain = P.getValue(1); 820 Parts[i] = P; 821 822 // If the source register was virtual and if we know something about it, 823 // add an assert node. 824 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 825 !RegisterVT.isInteger()) 826 continue; 827 828 const FunctionLoweringInfo::LiveOutInfo *LOI = 829 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 830 if (!LOI) 831 continue; 832 833 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 834 unsigned NumSignBits = LOI->NumSignBits; 835 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 836 837 if (NumZeroBits == RegSize) { 838 // The current value is a zero. 839 // Explicitly express that as it would be easier for 840 // optimizations to kick in. 841 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 842 continue; 843 } 844 845 // FIXME: We capture more information than the dag can represent. For 846 // now, just use the tightest assertzext/assertsext possible. 847 bool isSExt; 848 EVT FromVT(MVT::Other); 849 if (NumZeroBits) { 850 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 851 isSExt = false; 852 } else if (NumSignBits > 1) { 853 FromVT = 854 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 855 isSExt = true; 856 } else { 857 continue; 858 } 859 // Add an assertion node. 860 assert(FromVT != MVT::Other); 861 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 862 RegisterVT, P, DAG.getValueType(FromVT)); 863 } 864 865 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 866 RegisterVT, ValueVT, V, CallConv); 867 Part += NumRegs; 868 Parts.clear(); 869 } 870 871 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 872 } 873 874 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 875 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 876 const Value *V, 877 ISD::NodeType PreferredExtendType) const { 878 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 879 ISD::NodeType ExtendKind = PreferredExtendType; 880 881 // Get the list of the values's legal parts. 882 unsigned NumRegs = Regs.size(); 883 SmallVector<SDValue, 8> Parts(NumRegs); 884 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 885 unsigned NumParts = RegCount[Value]; 886 887 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 888 *DAG.getContext(), 889 CallConv.getValue(), RegVTs[Value]) 890 : RegVTs[Value]; 891 892 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 893 ExtendKind = ISD::ZERO_EXTEND; 894 895 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 896 NumParts, RegisterVT, V, CallConv, ExtendKind); 897 Part += NumParts; 898 } 899 900 // Copy the parts into the registers. 901 SmallVector<SDValue, 8> Chains(NumRegs); 902 for (unsigned i = 0; i != NumRegs; ++i) { 903 SDValue Part; 904 if (!Flag) { 905 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 906 } else { 907 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 908 *Flag = Part.getValue(1); 909 } 910 911 Chains[i] = Part.getValue(0); 912 } 913 914 if (NumRegs == 1 || Flag) 915 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 916 // flagged to it. That is the CopyToReg nodes and the user are considered 917 // a single scheduling unit. If we create a TokenFactor and return it as 918 // chain, then the TokenFactor is both a predecessor (operand) of the 919 // user as well as a successor (the TF operands are flagged to the user). 920 // c1, f1 = CopyToReg 921 // c2, f2 = CopyToReg 922 // c3 = TokenFactor c1, c2 923 // ... 924 // = op c3, ..., f2 925 Chain = Chains[NumRegs-1]; 926 else 927 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 928 } 929 930 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 931 unsigned MatchingIdx, const SDLoc &dl, 932 SelectionDAG &DAG, 933 std::vector<SDValue> &Ops) const { 934 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 935 936 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 937 if (HasMatching) 938 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 939 else if (!Regs.empty() && 940 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 941 // Put the register class of the virtual registers in the flag word. That 942 // way, later passes can recompute register class constraints for inline 943 // assembly as well as normal instructions. 944 // Don't do this for tied operands that can use the regclass information 945 // from the def. 946 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 947 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 948 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 949 } 950 951 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 952 Ops.push_back(Res); 953 954 if (Code == InlineAsm::Kind_Clobber) { 955 // Clobbers should always have a 1:1 mapping with registers, and may 956 // reference registers that have illegal (e.g. vector) types. Hence, we 957 // shouldn't try to apply any sort of splitting logic to them. 958 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 959 "No 1:1 mapping from clobbers to regs?"); 960 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 961 (void)SP; 962 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 963 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 964 assert( 965 (Regs[I] != SP || 966 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 967 "If we clobbered the stack pointer, MFI should know about it."); 968 } 969 return; 970 } 971 972 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 973 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 974 MVT RegisterVT = RegVTs[Value]; 975 for (unsigned i = 0; i != NumRegs; ++i) { 976 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 977 unsigned TheReg = Regs[Reg++]; 978 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 979 } 980 } 981 } 982 983 SmallVector<std::pair<unsigned, unsigned>, 4> 984 RegsForValue::getRegsAndSizes() const { 985 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 986 unsigned I = 0; 987 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 988 unsigned RegCount = std::get<0>(CountAndVT); 989 MVT RegisterVT = std::get<1>(CountAndVT); 990 unsigned RegisterSize = RegisterVT.getSizeInBits(); 991 for (unsigned E = I + RegCount; I != E; ++I) 992 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 993 } 994 return OutVec; 995 } 996 997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 998 const TargetLibraryInfo *li) { 999 AA = aa; 1000 GFI = gfi; 1001 LibInfo = li; 1002 DL = &DAG.getDataLayout(); 1003 Context = DAG.getContext(); 1004 LPadToCallSiteMap.clear(); 1005 } 1006 1007 void SelectionDAGBuilder::clear() { 1008 NodeMap.clear(); 1009 UnusedArgNodeMap.clear(); 1010 PendingLoads.clear(); 1011 PendingExports.clear(); 1012 CurInst = nullptr; 1013 HasTailCall = false; 1014 SDNodeOrder = LowestSDNodeOrder; 1015 StatepointLowering.clear(); 1016 } 1017 1018 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1019 DanglingDebugInfoMap.clear(); 1020 } 1021 1022 SDValue SelectionDAGBuilder::getRoot() { 1023 if (PendingLoads.empty()) 1024 return DAG.getRoot(); 1025 1026 if (PendingLoads.size() == 1) { 1027 SDValue Root = PendingLoads[0]; 1028 DAG.setRoot(Root); 1029 PendingLoads.clear(); 1030 return Root; 1031 } 1032 1033 // Otherwise, we have to make a token factor node. 1034 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); 1035 PendingLoads.clear(); 1036 DAG.setRoot(Root); 1037 return Root; 1038 } 1039 1040 SDValue SelectionDAGBuilder::getControlRoot() { 1041 SDValue Root = DAG.getRoot(); 1042 1043 if (PendingExports.empty()) 1044 return Root; 1045 1046 // Turn all of the CopyToReg chains into one factored node. 1047 if (Root.getOpcode() != ISD::EntryToken) { 1048 unsigned i = 0, e = PendingExports.size(); 1049 for (; i != e; ++i) { 1050 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1051 if (PendingExports[i].getNode()->getOperand(0) == Root) 1052 break; // Don't add the root if we already indirectly depend on it. 1053 } 1054 1055 if (i == e) 1056 PendingExports.push_back(Root); 1057 } 1058 1059 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1060 PendingExports); 1061 PendingExports.clear(); 1062 DAG.setRoot(Root); 1063 return Root; 1064 } 1065 1066 void SelectionDAGBuilder::visit(const Instruction &I) { 1067 // Set up outgoing PHI node register values before emitting the terminator. 1068 if (I.isTerminator()) { 1069 HandlePHINodesInSuccessorBlocks(I.getParent()); 1070 } 1071 1072 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1073 if (!isa<DbgInfoIntrinsic>(I)) 1074 ++SDNodeOrder; 1075 1076 CurInst = &I; 1077 1078 visit(I.getOpcode(), I); 1079 1080 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1081 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1082 // maps to this instruction. 1083 // TODO: We could handle all flags (nsw, etc) here. 1084 // TODO: If an IR instruction maps to >1 node, only the final node will have 1085 // flags set. 1086 if (SDNode *Node = getNodeForIRValue(&I)) { 1087 SDNodeFlags IncomingFlags; 1088 IncomingFlags.copyFMF(*FPMO); 1089 if (!Node->getFlags().isDefined()) 1090 Node->setFlags(IncomingFlags); 1091 else 1092 Node->intersectFlagsWith(IncomingFlags); 1093 } 1094 } 1095 1096 if (!I.isTerminator() && !HasTailCall && 1097 !isStatepoint(&I)) // statepoints handle their exports internally 1098 CopyToExportRegsIfNeeded(&I); 1099 1100 CurInst = nullptr; 1101 } 1102 1103 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1104 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1105 } 1106 1107 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1108 // Note: this doesn't use InstVisitor, because it has to work with 1109 // ConstantExpr's in addition to instructions. 1110 switch (Opcode) { 1111 default: llvm_unreachable("Unknown instruction type encountered!"); 1112 // Build the switch statement using the Instruction.def file. 1113 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1114 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1115 #include "llvm/IR/Instruction.def" 1116 } 1117 } 1118 1119 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1120 const DIExpression *Expr) { 1121 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1122 const DbgValueInst *DI = DDI.getDI(); 1123 DIVariable *DanglingVariable = DI->getVariable(); 1124 DIExpression *DanglingExpr = DI->getExpression(); 1125 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1126 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1127 return true; 1128 } 1129 return false; 1130 }; 1131 1132 for (auto &DDIMI : DanglingDebugInfoMap) { 1133 DanglingDebugInfoVector &DDIV = DDIMI.second; 1134 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1135 } 1136 } 1137 1138 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1139 // generate the debug data structures now that we've seen its definition. 1140 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1141 SDValue Val) { 1142 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1143 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1144 return; 1145 1146 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1147 for (auto &DDI : DDIV) { 1148 const DbgValueInst *DI = DDI.getDI(); 1149 assert(DI && "Ill-formed DanglingDebugInfo"); 1150 DebugLoc dl = DDI.getdl(); 1151 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1152 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1153 DILocalVariable *Variable = DI->getVariable(); 1154 DIExpression *Expr = DI->getExpression(); 1155 assert(Variable->isValidLocationForIntrinsic(dl) && 1156 "Expected inlined-at fields to agree"); 1157 SDDbgValue *SDV; 1158 if (Val.getNode()) { 1159 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1160 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1161 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1162 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1163 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1164 // inserted after the definition of Val when emitting the instructions 1165 // after ISel. An alternative could be to teach 1166 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1167 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1168 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1169 << ValSDNodeOrder << "\n"); 1170 SDV = getDbgValue(Val, Variable, Expr, dl, 1171 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1172 DAG.AddDbgValue(SDV, Val.getNode(), false); 1173 } else 1174 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1175 << "in EmitFuncArgumentDbgValue\n"); 1176 } else 1177 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1178 } 1179 DDIV.clear(); 1180 } 1181 1182 /// getCopyFromRegs - If there was virtual register allocated for the value V 1183 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1184 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1185 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1186 SDValue Result; 1187 1188 if (It != FuncInfo.ValueMap.end()) { 1189 unsigned InReg = It->second; 1190 1191 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1192 DAG.getDataLayout(), InReg, Ty, 1193 None); // This is not an ABI copy. 1194 SDValue Chain = DAG.getEntryNode(); 1195 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1196 V); 1197 resolveDanglingDebugInfo(V, Result); 1198 } 1199 1200 return Result; 1201 } 1202 1203 /// getValue - Return an SDValue for the given Value. 1204 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1205 // If we already have an SDValue for this value, use it. It's important 1206 // to do this first, so that we don't create a CopyFromReg if we already 1207 // have a regular SDValue. 1208 SDValue &N = NodeMap[V]; 1209 if (N.getNode()) return N; 1210 1211 // If there's a virtual register allocated and initialized for this 1212 // value, use it. 1213 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1214 return copyFromReg; 1215 1216 // Otherwise create a new SDValue and remember it. 1217 SDValue Val = getValueImpl(V); 1218 NodeMap[V] = Val; 1219 resolveDanglingDebugInfo(V, Val); 1220 return Val; 1221 } 1222 1223 // Return true if SDValue exists for the given Value 1224 bool SelectionDAGBuilder::findValue(const Value *V) const { 1225 return (NodeMap.find(V) != NodeMap.end()) || 1226 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1227 } 1228 1229 /// getNonRegisterValue - Return an SDValue for the given Value, but 1230 /// don't look in FuncInfo.ValueMap for a virtual register. 1231 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1232 // If we already have an SDValue for this value, use it. 1233 SDValue &N = NodeMap[V]; 1234 if (N.getNode()) { 1235 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1236 // Remove the debug location from the node as the node is about to be used 1237 // in a location which may differ from the original debug location. This 1238 // is relevant to Constant and ConstantFP nodes because they can appear 1239 // as constant expressions inside PHI nodes. 1240 N->setDebugLoc(DebugLoc()); 1241 } 1242 return N; 1243 } 1244 1245 // Otherwise create a new SDValue and remember it. 1246 SDValue Val = getValueImpl(V); 1247 NodeMap[V] = Val; 1248 resolveDanglingDebugInfo(V, Val); 1249 return Val; 1250 } 1251 1252 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1253 /// Create an SDValue for the given value. 1254 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1255 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1256 1257 if (const Constant *C = dyn_cast<Constant>(V)) { 1258 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1259 1260 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1261 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1262 1263 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1264 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1265 1266 if (isa<ConstantPointerNull>(C)) { 1267 unsigned AS = V->getType()->getPointerAddressSpace(); 1268 return DAG.getConstant(0, getCurSDLoc(), 1269 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1270 } 1271 1272 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1273 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1274 1275 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1276 return DAG.getUNDEF(VT); 1277 1278 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1279 visit(CE->getOpcode(), *CE); 1280 SDValue N1 = NodeMap[V]; 1281 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1282 return N1; 1283 } 1284 1285 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1286 SmallVector<SDValue, 4> Constants; 1287 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1288 OI != OE; ++OI) { 1289 SDNode *Val = getValue(*OI).getNode(); 1290 // If the operand is an empty aggregate, there are no values. 1291 if (!Val) continue; 1292 // Add each leaf value from the operand to the Constants list 1293 // to form a flattened list of all the values. 1294 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1295 Constants.push_back(SDValue(Val, i)); 1296 } 1297 1298 return DAG.getMergeValues(Constants, getCurSDLoc()); 1299 } 1300 1301 if (const ConstantDataSequential *CDS = 1302 dyn_cast<ConstantDataSequential>(C)) { 1303 SmallVector<SDValue, 4> Ops; 1304 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1305 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1306 // Add each leaf value from the operand to the Constants list 1307 // to form a flattened list of all the values. 1308 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1309 Ops.push_back(SDValue(Val, i)); 1310 } 1311 1312 if (isa<ArrayType>(CDS->getType())) 1313 return DAG.getMergeValues(Ops, getCurSDLoc()); 1314 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1315 } 1316 1317 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1318 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1319 "Unknown struct or array constant!"); 1320 1321 SmallVector<EVT, 4> ValueVTs; 1322 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1323 unsigned NumElts = ValueVTs.size(); 1324 if (NumElts == 0) 1325 return SDValue(); // empty struct 1326 SmallVector<SDValue, 4> Constants(NumElts); 1327 for (unsigned i = 0; i != NumElts; ++i) { 1328 EVT EltVT = ValueVTs[i]; 1329 if (isa<UndefValue>(C)) 1330 Constants[i] = DAG.getUNDEF(EltVT); 1331 else if (EltVT.isFloatingPoint()) 1332 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1333 else 1334 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1335 } 1336 1337 return DAG.getMergeValues(Constants, getCurSDLoc()); 1338 } 1339 1340 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1341 return DAG.getBlockAddress(BA, VT); 1342 1343 VectorType *VecTy = cast<VectorType>(V->getType()); 1344 unsigned NumElements = VecTy->getNumElements(); 1345 1346 // Now that we know the number and type of the elements, get that number of 1347 // elements into the Ops array based on what kind of constant it is. 1348 SmallVector<SDValue, 16> Ops; 1349 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1350 for (unsigned i = 0; i != NumElements; ++i) 1351 Ops.push_back(getValue(CV->getOperand(i))); 1352 } else { 1353 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1354 EVT EltVT = 1355 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1356 1357 SDValue Op; 1358 if (EltVT.isFloatingPoint()) 1359 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1360 else 1361 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1362 Ops.assign(NumElements, Op); 1363 } 1364 1365 // Create a BUILD_VECTOR node. 1366 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1367 } 1368 1369 // If this is a static alloca, generate it as the frameindex instead of 1370 // computation. 1371 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1372 DenseMap<const AllocaInst*, int>::iterator SI = 1373 FuncInfo.StaticAllocaMap.find(AI); 1374 if (SI != FuncInfo.StaticAllocaMap.end()) 1375 return DAG.getFrameIndex(SI->second, 1376 TLI.getFrameIndexTy(DAG.getDataLayout())); 1377 } 1378 1379 // If this is an instruction which fast-isel has deferred, select it now. 1380 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1381 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1382 1383 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1384 Inst->getType(), getABIRegCopyCC(V)); 1385 SDValue Chain = DAG.getEntryNode(); 1386 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1387 } 1388 1389 llvm_unreachable("Can't get register for value!"); 1390 } 1391 1392 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1393 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1394 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1395 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1396 bool IsSEH = isAsynchronousEHPersonality(Pers); 1397 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1398 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1399 if (!IsSEH) 1400 CatchPadMBB->setIsEHScopeEntry(); 1401 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1402 if (IsMSVCCXX || IsCoreCLR) 1403 CatchPadMBB->setIsEHFuncletEntry(); 1404 // Wasm does not need catchpads anymore 1405 if (!IsWasmCXX) 1406 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1407 getControlRoot())); 1408 } 1409 1410 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1411 // Update machine-CFG edge. 1412 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1413 FuncInfo.MBB->addSuccessor(TargetMBB); 1414 1415 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1416 bool IsSEH = isAsynchronousEHPersonality(Pers); 1417 if (IsSEH) { 1418 // If this is not a fall-through branch or optimizations are switched off, 1419 // emit the branch. 1420 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1421 TM.getOptLevel() == CodeGenOpt::None) 1422 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1423 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1424 return; 1425 } 1426 1427 // Figure out the funclet membership for the catchret's successor. 1428 // This will be used by the FuncletLayout pass to determine how to order the 1429 // BB's. 1430 // A 'catchret' returns to the outer scope's color. 1431 Value *ParentPad = I.getCatchSwitchParentPad(); 1432 const BasicBlock *SuccessorColor; 1433 if (isa<ConstantTokenNone>(ParentPad)) 1434 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1435 else 1436 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1437 assert(SuccessorColor && "No parent funclet for catchret!"); 1438 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1439 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1440 1441 // Create the terminator node. 1442 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1443 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1444 DAG.getBasicBlock(SuccessorColorMBB)); 1445 DAG.setRoot(Ret); 1446 } 1447 1448 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1449 // Don't emit any special code for the cleanuppad instruction. It just marks 1450 // the start of an EH scope/funclet. 1451 FuncInfo.MBB->setIsEHScopeEntry(); 1452 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1453 if (Pers != EHPersonality::Wasm_CXX) { 1454 FuncInfo.MBB->setIsEHFuncletEntry(); 1455 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1456 } 1457 } 1458 1459 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1460 /// many places it could ultimately go. In the IR, we have a single unwind 1461 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1462 /// This function skips over imaginary basic blocks that hold catchswitch 1463 /// instructions, and finds all the "real" machine 1464 /// basic block destinations. As those destinations may not be successors of 1465 /// EHPadBB, here we also calculate the edge probability to those destinations. 1466 /// The passed-in Prob is the edge probability to EHPadBB. 1467 static void findUnwindDestinations( 1468 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1469 BranchProbability Prob, 1470 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1471 &UnwindDests) { 1472 EHPersonality Personality = 1473 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1474 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1475 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1476 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1477 bool IsSEH = isAsynchronousEHPersonality(Personality); 1478 1479 while (EHPadBB) { 1480 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1481 BasicBlock *NewEHPadBB = nullptr; 1482 if (isa<LandingPadInst>(Pad)) { 1483 // Stop on landingpads. They are not funclets. 1484 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1485 break; 1486 } else if (isa<CleanupPadInst>(Pad)) { 1487 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1488 // personalities. 1489 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1490 UnwindDests.back().first->setIsEHScopeEntry(); 1491 if (!IsWasmCXX) 1492 UnwindDests.back().first->setIsEHFuncletEntry(); 1493 break; 1494 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1495 // Add the catchpad handlers to the possible destinations. 1496 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1497 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1498 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1499 if (IsMSVCCXX || IsCoreCLR) 1500 UnwindDests.back().first->setIsEHFuncletEntry(); 1501 if (!IsSEH) 1502 UnwindDests.back().first->setIsEHScopeEntry(); 1503 } 1504 NewEHPadBB = CatchSwitch->getUnwindDest(); 1505 } else { 1506 continue; 1507 } 1508 1509 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1510 if (BPI && NewEHPadBB) 1511 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1512 EHPadBB = NewEHPadBB; 1513 } 1514 } 1515 1516 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1517 // Update successor info. 1518 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1519 auto UnwindDest = I.getUnwindDest(); 1520 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1521 BranchProbability UnwindDestProb = 1522 (BPI && UnwindDest) 1523 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1524 : BranchProbability::getZero(); 1525 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1526 for (auto &UnwindDest : UnwindDests) { 1527 UnwindDest.first->setIsEHPad(); 1528 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1529 } 1530 FuncInfo.MBB->normalizeSuccProbs(); 1531 1532 // Create the terminator node. 1533 SDValue Ret = 1534 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1535 DAG.setRoot(Ret); 1536 } 1537 1538 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1539 report_fatal_error("visitCatchSwitch not yet implemented!"); 1540 } 1541 1542 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1543 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1544 auto &DL = DAG.getDataLayout(); 1545 SDValue Chain = getControlRoot(); 1546 SmallVector<ISD::OutputArg, 8> Outs; 1547 SmallVector<SDValue, 8> OutVals; 1548 1549 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1550 // lower 1551 // 1552 // %val = call <ty> @llvm.experimental.deoptimize() 1553 // ret <ty> %val 1554 // 1555 // differently. 1556 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1557 LowerDeoptimizingReturn(); 1558 return; 1559 } 1560 1561 if (!FuncInfo.CanLowerReturn) { 1562 unsigned DemoteReg = FuncInfo.DemoteRegister; 1563 const Function *F = I.getParent()->getParent(); 1564 1565 // Emit a store of the return value through the virtual register. 1566 // Leave Outs empty so that LowerReturn won't try to load return 1567 // registers the usual way. 1568 SmallVector<EVT, 1> PtrValueVTs; 1569 ComputeValueVTs(TLI, DL, 1570 F->getReturnType()->getPointerTo( 1571 DAG.getDataLayout().getAllocaAddrSpace()), 1572 PtrValueVTs); 1573 1574 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1575 DemoteReg, PtrValueVTs[0]); 1576 SDValue RetOp = getValue(I.getOperand(0)); 1577 1578 SmallVector<EVT, 4> ValueVTs; 1579 SmallVector<uint64_t, 4> Offsets; 1580 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1581 unsigned NumValues = ValueVTs.size(); 1582 1583 SmallVector<SDValue, 4> Chains(NumValues); 1584 for (unsigned i = 0; i != NumValues; ++i) { 1585 // An aggregate return value cannot wrap around the address space, so 1586 // offsets to its parts don't wrap either. 1587 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1588 Chains[i] = DAG.getStore( 1589 Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1590 // FIXME: better loc info would be nice. 1591 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1592 } 1593 1594 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1595 MVT::Other, Chains); 1596 } else if (I.getNumOperands() != 0) { 1597 SmallVector<EVT, 4> ValueVTs; 1598 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1599 unsigned NumValues = ValueVTs.size(); 1600 if (NumValues) { 1601 SDValue RetOp = getValue(I.getOperand(0)); 1602 1603 const Function *F = I.getParent()->getParent(); 1604 1605 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1606 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1607 Attribute::SExt)) 1608 ExtendKind = ISD::SIGN_EXTEND; 1609 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1610 Attribute::ZExt)) 1611 ExtendKind = ISD::ZERO_EXTEND; 1612 1613 LLVMContext &Context = F->getContext(); 1614 bool RetInReg = F->getAttributes().hasAttribute( 1615 AttributeList::ReturnIndex, Attribute::InReg); 1616 1617 for (unsigned j = 0; j != NumValues; ++j) { 1618 EVT VT = ValueVTs[j]; 1619 1620 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1621 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1622 1623 CallingConv::ID CC = F->getCallingConv(); 1624 1625 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1626 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1627 SmallVector<SDValue, 4> Parts(NumParts); 1628 getCopyToParts(DAG, getCurSDLoc(), 1629 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1630 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1631 1632 // 'inreg' on function refers to return value 1633 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1634 if (RetInReg) 1635 Flags.setInReg(); 1636 1637 // Propagate extension type if any 1638 if (ExtendKind == ISD::SIGN_EXTEND) 1639 Flags.setSExt(); 1640 else if (ExtendKind == ISD::ZERO_EXTEND) 1641 Flags.setZExt(); 1642 1643 for (unsigned i = 0; i < NumParts; ++i) { 1644 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1645 VT, /*isfixed=*/true, 0, 0)); 1646 OutVals.push_back(Parts[i]); 1647 } 1648 } 1649 } 1650 } 1651 1652 // Push in swifterror virtual register as the last element of Outs. This makes 1653 // sure swifterror virtual register will be returned in the swifterror 1654 // physical register. 1655 const Function *F = I.getParent()->getParent(); 1656 if (TLI.supportSwiftError() && 1657 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1658 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument"); 1659 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1660 Flags.setSwiftError(); 1661 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1662 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1663 true /*isfixed*/, 1 /*origidx*/, 1664 0 /*partOffs*/)); 1665 // Create SDNode for the swifterror virtual register. 1666 OutVals.push_back( 1667 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt( 1668 &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first, 1669 EVT(TLI.getPointerTy(DL)))); 1670 } 1671 1672 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1673 CallingConv::ID CallConv = 1674 DAG.getMachineFunction().getFunction().getCallingConv(); 1675 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1676 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1677 1678 // Verify that the target's LowerReturn behaved as expected. 1679 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1680 "LowerReturn didn't return a valid chain!"); 1681 1682 // Update the DAG with the new chain value resulting from return lowering. 1683 DAG.setRoot(Chain); 1684 } 1685 1686 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1687 /// created for it, emit nodes to copy the value into the virtual 1688 /// registers. 1689 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1690 // Skip empty types 1691 if (V->getType()->isEmptyTy()) 1692 return; 1693 1694 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1695 if (VMI != FuncInfo.ValueMap.end()) { 1696 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1697 CopyValueToVirtualRegister(V, VMI->second); 1698 } 1699 } 1700 1701 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1702 /// the current basic block, add it to ValueMap now so that we'll get a 1703 /// CopyTo/FromReg. 1704 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1705 // No need to export constants. 1706 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1707 1708 // Already exported? 1709 if (FuncInfo.isExportedInst(V)) return; 1710 1711 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1712 CopyValueToVirtualRegister(V, Reg); 1713 } 1714 1715 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1716 const BasicBlock *FromBB) { 1717 // The operands of the setcc have to be in this block. We don't know 1718 // how to export them from some other block. 1719 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1720 // Can export from current BB. 1721 if (VI->getParent() == FromBB) 1722 return true; 1723 1724 // Is already exported, noop. 1725 return FuncInfo.isExportedInst(V); 1726 } 1727 1728 // If this is an argument, we can export it if the BB is the entry block or 1729 // if it is already exported. 1730 if (isa<Argument>(V)) { 1731 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1732 return true; 1733 1734 // Otherwise, can only export this if it is already exported. 1735 return FuncInfo.isExportedInst(V); 1736 } 1737 1738 // Otherwise, constants can always be exported. 1739 return true; 1740 } 1741 1742 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1743 BranchProbability 1744 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1745 const MachineBasicBlock *Dst) const { 1746 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1747 const BasicBlock *SrcBB = Src->getBasicBlock(); 1748 const BasicBlock *DstBB = Dst->getBasicBlock(); 1749 if (!BPI) { 1750 // If BPI is not available, set the default probability as 1 / N, where N is 1751 // the number of successors. 1752 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1753 return BranchProbability(1, SuccSize); 1754 } 1755 return BPI->getEdgeProbability(SrcBB, DstBB); 1756 } 1757 1758 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1759 MachineBasicBlock *Dst, 1760 BranchProbability Prob) { 1761 if (!FuncInfo.BPI) 1762 Src->addSuccessorWithoutProb(Dst); 1763 else { 1764 if (Prob.isUnknown()) 1765 Prob = getEdgeProbability(Src, Dst); 1766 Src->addSuccessor(Dst, Prob); 1767 } 1768 } 1769 1770 static bool InBlock(const Value *V, const BasicBlock *BB) { 1771 if (const Instruction *I = dyn_cast<Instruction>(V)) 1772 return I->getParent() == BB; 1773 return true; 1774 } 1775 1776 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1777 /// This function emits a branch and is used at the leaves of an OR or an 1778 /// AND operator tree. 1779 void 1780 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1781 MachineBasicBlock *TBB, 1782 MachineBasicBlock *FBB, 1783 MachineBasicBlock *CurBB, 1784 MachineBasicBlock *SwitchBB, 1785 BranchProbability TProb, 1786 BranchProbability FProb, 1787 bool InvertCond) { 1788 const BasicBlock *BB = CurBB->getBasicBlock(); 1789 1790 // If the leaf of the tree is a comparison, merge the condition into 1791 // the caseblock. 1792 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1793 // The operands of the cmp have to be in this block. We don't know 1794 // how to export them from some other block. If this is the first block 1795 // of the sequence, no exporting is needed. 1796 if (CurBB == SwitchBB || 1797 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1798 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1799 ISD::CondCode Condition; 1800 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1801 ICmpInst::Predicate Pred = 1802 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 1803 Condition = getICmpCondCode(Pred); 1804 } else { 1805 const FCmpInst *FC = cast<FCmpInst>(Cond); 1806 FCmpInst::Predicate Pred = 1807 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 1808 Condition = getFCmpCondCode(Pred); 1809 if (TM.Options.NoNaNsFPMath) 1810 Condition = getFCmpCodeWithoutNaN(Condition); 1811 } 1812 1813 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 1814 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1815 SwitchCases.push_back(CB); 1816 return; 1817 } 1818 } 1819 1820 // Create a CaseBlock record representing this branch. 1821 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 1822 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 1823 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1824 SwitchCases.push_back(CB); 1825 } 1826 1827 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1828 MachineBasicBlock *TBB, 1829 MachineBasicBlock *FBB, 1830 MachineBasicBlock *CurBB, 1831 MachineBasicBlock *SwitchBB, 1832 Instruction::BinaryOps Opc, 1833 BranchProbability TProb, 1834 BranchProbability FProb, 1835 bool InvertCond) { 1836 // Skip over not part of the tree and remember to invert op and operands at 1837 // next level. 1838 Value *NotCond; 1839 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 1840 InBlock(NotCond, CurBB->getBasicBlock())) { 1841 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 1842 !InvertCond); 1843 return; 1844 } 1845 1846 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1847 // Compute the effective opcode for Cond, taking into account whether it needs 1848 // to be inverted, e.g. 1849 // and (not (or A, B)), C 1850 // gets lowered as 1851 // and (and (not A, not B), C) 1852 unsigned BOpc = 0; 1853 if (BOp) { 1854 BOpc = BOp->getOpcode(); 1855 if (InvertCond) { 1856 if (BOpc == Instruction::And) 1857 BOpc = Instruction::Or; 1858 else if (BOpc == Instruction::Or) 1859 BOpc = Instruction::And; 1860 } 1861 } 1862 1863 // If this node is not part of the or/and tree, emit it as a branch. 1864 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1865 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 1866 BOp->getParent() != CurBB->getBasicBlock() || 1867 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1868 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1869 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 1870 TProb, FProb, InvertCond); 1871 return; 1872 } 1873 1874 // Create TmpBB after CurBB. 1875 MachineFunction::iterator BBI(CurBB); 1876 MachineFunction &MF = DAG.getMachineFunction(); 1877 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1878 CurBB->getParent()->insert(++BBI, TmpBB); 1879 1880 if (Opc == Instruction::Or) { 1881 // Codegen X | Y as: 1882 // BB1: 1883 // jmp_if_X TBB 1884 // jmp TmpBB 1885 // TmpBB: 1886 // jmp_if_Y TBB 1887 // jmp FBB 1888 // 1889 1890 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1891 // The requirement is that 1892 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 1893 // = TrueProb for original BB. 1894 // Assuming the original probabilities are A and B, one choice is to set 1895 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 1896 // A/(1+B) and 2B/(1+B). This choice assumes that 1897 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 1898 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 1899 // TmpBB, but the math is more complicated. 1900 1901 auto NewTrueProb = TProb / 2; 1902 auto NewFalseProb = TProb / 2 + FProb; 1903 // Emit the LHS condition. 1904 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 1905 NewTrueProb, NewFalseProb, InvertCond); 1906 1907 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 1908 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 1909 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1910 // Emit the RHS condition into TmpBB. 1911 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1912 Probs[0], Probs[1], InvertCond); 1913 } else { 1914 assert(Opc == Instruction::And && "Unknown merge op!"); 1915 // Codegen X & Y as: 1916 // BB1: 1917 // jmp_if_X TmpBB 1918 // jmp FBB 1919 // TmpBB: 1920 // jmp_if_Y TBB 1921 // jmp FBB 1922 // 1923 // This requires creation of TmpBB after CurBB. 1924 1925 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1926 // The requirement is that 1927 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 1928 // = FalseProb for original BB. 1929 // Assuming the original probabilities are A and B, one choice is to set 1930 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 1931 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 1932 // TrueProb for BB1 * FalseProb for TmpBB. 1933 1934 auto NewTrueProb = TProb + FProb / 2; 1935 auto NewFalseProb = FProb / 2; 1936 // Emit the LHS condition. 1937 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 1938 NewTrueProb, NewFalseProb, InvertCond); 1939 1940 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 1941 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 1942 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1943 // Emit the RHS condition into TmpBB. 1944 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1945 Probs[0], Probs[1], InvertCond); 1946 } 1947 } 1948 1949 /// If the set of cases should be emitted as a series of branches, return true. 1950 /// If we should emit this as a bunch of and/or'd together conditions, return 1951 /// false. 1952 bool 1953 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1954 if (Cases.size() != 2) return true; 1955 1956 // If this is two comparisons of the same values or'd or and'd together, they 1957 // will get folded into a single comparison, so don't emit two blocks. 1958 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1959 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1960 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1961 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1962 return false; 1963 } 1964 1965 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1966 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1967 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1968 Cases[0].CC == Cases[1].CC && 1969 isa<Constant>(Cases[0].CmpRHS) && 1970 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1971 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1972 return false; 1973 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1974 return false; 1975 } 1976 1977 return true; 1978 } 1979 1980 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1981 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1982 1983 // Update machine-CFG edges. 1984 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1985 1986 if (I.isUnconditional()) { 1987 // Update machine-CFG edges. 1988 BrMBB->addSuccessor(Succ0MBB); 1989 1990 // If this is not a fall-through branch or optimizations are switched off, 1991 // emit the branch. 1992 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 1993 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 1994 MVT::Other, getControlRoot(), 1995 DAG.getBasicBlock(Succ0MBB))); 1996 1997 return; 1998 } 1999 2000 // If this condition is one of the special cases we handle, do special stuff 2001 // now. 2002 const Value *CondVal = I.getCondition(); 2003 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2004 2005 // If this is a series of conditions that are or'd or and'd together, emit 2006 // this as a sequence of branches instead of setcc's with and/or operations. 2007 // As long as jumps are not expensive, this should improve performance. 2008 // For example, instead of something like: 2009 // cmp A, B 2010 // C = seteq 2011 // cmp D, E 2012 // F = setle 2013 // or C, F 2014 // jnz foo 2015 // Emit: 2016 // cmp A, B 2017 // je foo 2018 // cmp D, E 2019 // jle foo 2020 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2021 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2022 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2023 !I.getMetadata(LLVMContext::MD_unpredictable) && 2024 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2025 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2026 Opcode, 2027 getEdgeProbability(BrMBB, Succ0MBB), 2028 getEdgeProbability(BrMBB, Succ1MBB), 2029 /*InvertCond=*/false); 2030 // If the compares in later blocks need to use values not currently 2031 // exported from this block, export them now. This block should always 2032 // be the first entry. 2033 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2034 2035 // Allow some cases to be rejected. 2036 if (ShouldEmitAsBranches(SwitchCases)) { 2037 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 2038 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 2039 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 2040 } 2041 2042 // Emit the branch for this block. 2043 visitSwitchCase(SwitchCases[0], BrMBB); 2044 SwitchCases.erase(SwitchCases.begin()); 2045 return; 2046 } 2047 2048 // Okay, we decided not to do this, remove any inserted MBB's and clear 2049 // SwitchCases. 2050 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 2051 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 2052 2053 SwitchCases.clear(); 2054 } 2055 } 2056 2057 // Create a CaseBlock record representing this branch. 2058 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2059 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2060 2061 // Use visitSwitchCase to actually insert the fast branch sequence for this 2062 // cond branch. 2063 visitSwitchCase(CB, BrMBB); 2064 } 2065 2066 /// visitSwitchCase - Emits the necessary code to represent a single node in 2067 /// the binary search tree resulting from lowering a switch instruction. 2068 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2069 MachineBasicBlock *SwitchBB) { 2070 SDValue Cond; 2071 SDValue CondLHS = getValue(CB.CmpLHS); 2072 SDLoc dl = CB.DL; 2073 2074 // Build the setcc now. 2075 if (!CB.CmpMHS) { 2076 // Fold "(X == true)" to X and "(X == false)" to !X to 2077 // handle common cases produced by branch lowering. 2078 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2079 CB.CC == ISD::SETEQ) 2080 Cond = CondLHS; 2081 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2082 CB.CC == ISD::SETEQ) { 2083 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2084 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2085 } else 2086 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 2087 } else { 2088 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2089 2090 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2091 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2092 2093 SDValue CmpOp = getValue(CB.CmpMHS); 2094 EVT VT = CmpOp.getValueType(); 2095 2096 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2097 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2098 ISD::SETLE); 2099 } else { 2100 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2101 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2102 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2103 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2104 } 2105 } 2106 2107 // Update successor info 2108 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2109 // TrueBB and FalseBB are always different unless the incoming IR is 2110 // degenerate. This only happens when running llc on weird IR. 2111 if (CB.TrueBB != CB.FalseBB) 2112 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2113 SwitchBB->normalizeSuccProbs(); 2114 2115 // If the lhs block is the next block, invert the condition so that we can 2116 // fall through to the lhs instead of the rhs block. 2117 if (CB.TrueBB == NextBlock(SwitchBB)) { 2118 std::swap(CB.TrueBB, CB.FalseBB); 2119 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2120 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2121 } 2122 2123 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2124 MVT::Other, getControlRoot(), Cond, 2125 DAG.getBasicBlock(CB.TrueBB)); 2126 2127 // Insert the false branch. Do this even if it's a fall through branch, 2128 // this makes it easier to do DAG optimizations which require inverting 2129 // the branch condition. 2130 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2131 DAG.getBasicBlock(CB.FalseBB)); 2132 2133 DAG.setRoot(BrCond); 2134 } 2135 2136 /// visitJumpTable - Emit JumpTable node in the current MBB 2137 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 2138 // Emit the code for the jump table 2139 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2140 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2141 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2142 JT.Reg, PTy); 2143 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2144 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2145 MVT::Other, Index.getValue(1), 2146 Table, Index); 2147 DAG.setRoot(BrJumpTable); 2148 } 2149 2150 /// visitJumpTableHeader - This function emits necessary code to produce index 2151 /// in the JumpTable from switch case. 2152 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 2153 JumpTableHeader &JTH, 2154 MachineBasicBlock *SwitchBB) { 2155 SDLoc dl = getCurSDLoc(); 2156 2157 // Subtract the lowest switch case value from the value being switched on and 2158 // conditional branch to default mbb if the result is greater than the 2159 // difference between smallest and largest cases. 2160 SDValue SwitchOp = getValue(JTH.SValue); 2161 EVT VT = SwitchOp.getValueType(); 2162 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2163 DAG.getConstant(JTH.First, dl, VT)); 2164 2165 // The SDNode we just created, which holds the value being switched on minus 2166 // the smallest case value, needs to be copied to a virtual register so it 2167 // can be used as an index into the jump table in a subsequent basic block. 2168 // This value may be smaller or larger than the target's pointer type, and 2169 // therefore require extension or truncating. 2170 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2171 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2172 2173 unsigned JumpTableReg = 2174 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2175 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2176 JumpTableReg, SwitchOp); 2177 JT.Reg = JumpTableReg; 2178 2179 // Emit the range check for the jump table, and branch to the default block 2180 // for the switch statement if the value being switched on exceeds the largest 2181 // case in the switch. 2182 SDValue CMP = DAG.getSetCC( 2183 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2184 Sub.getValueType()), 2185 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2186 2187 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2188 MVT::Other, CopyTo, CMP, 2189 DAG.getBasicBlock(JT.Default)); 2190 2191 // Avoid emitting unnecessary branches to the next block. 2192 if (JT.MBB != NextBlock(SwitchBB)) 2193 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2194 DAG.getBasicBlock(JT.MBB)); 2195 2196 DAG.setRoot(BrCond); 2197 } 2198 2199 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2200 /// variable if there exists one. 2201 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2202 SDValue &Chain) { 2203 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2204 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2205 MachineFunction &MF = DAG.getMachineFunction(); 2206 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2207 MachineSDNode *Node = 2208 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2209 if (Global) { 2210 MachinePointerInfo MPInfo(Global); 2211 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2212 MachineMemOperand::MODereferenceable; 2213 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2214 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2215 DAG.setNodeMemRefs(Node, {MemRef}); 2216 } 2217 return SDValue(Node, 0); 2218 } 2219 2220 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2221 /// tail spliced into a stack protector check success bb. 2222 /// 2223 /// For a high level explanation of how this fits into the stack protector 2224 /// generation see the comment on the declaration of class 2225 /// StackProtectorDescriptor. 2226 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2227 MachineBasicBlock *ParentBB) { 2228 2229 // First create the loads to the guard/stack slot for the comparison. 2230 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2231 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2232 2233 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2234 int FI = MFI.getStackProtectorIndex(); 2235 2236 SDValue Guard; 2237 SDLoc dl = getCurSDLoc(); 2238 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2239 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2240 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2241 2242 // Generate code to load the content of the guard slot. 2243 SDValue GuardVal = DAG.getLoad( 2244 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2245 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2246 MachineMemOperand::MOVolatile); 2247 2248 if (TLI.useStackGuardXorFP()) 2249 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2250 2251 // Retrieve guard check function, nullptr if instrumentation is inlined. 2252 if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) { 2253 // The target provides a guard check function to validate the guard value. 2254 // Generate a call to that function with the content of the guard slot as 2255 // argument. 2256 auto *Fn = cast<Function>(GuardCheck); 2257 FunctionType *FnTy = Fn->getFunctionType(); 2258 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2259 2260 TargetLowering::ArgListTy Args; 2261 TargetLowering::ArgListEntry Entry; 2262 Entry.Node = GuardVal; 2263 Entry.Ty = FnTy->getParamType(0); 2264 if (Fn->hasAttribute(1, Attribute::AttrKind::InReg)) 2265 Entry.IsInReg = true; 2266 Args.push_back(Entry); 2267 2268 TargetLowering::CallLoweringInfo CLI(DAG); 2269 CLI.setDebugLoc(getCurSDLoc()) 2270 .setChain(DAG.getEntryNode()) 2271 .setCallee(Fn->getCallingConv(), FnTy->getReturnType(), 2272 getValue(GuardCheck), std::move(Args)); 2273 2274 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2275 DAG.setRoot(Result.second); 2276 return; 2277 } 2278 2279 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2280 // Otherwise, emit a volatile load to retrieve the stack guard value. 2281 SDValue Chain = DAG.getEntryNode(); 2282 if (TLI.useLoadStackGuardNode()) { 2283 Guard = getLoadStackGuard(DAG, dl, Chain); 2284 } else { 2285 const Value *IRGuard = TLI.getSDagStackGuard(M); 2286 SDValue GuardPtr = getValue(IRGuard); 2287 2288 Guard = 2289 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2290 Align, MachineMemOperand::MOVolatile); 2291 } 2292 2293 // Perform the comparison via a subtract/getsetcc. 2294 EVT VT = Guard.getValueType(); 2295 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2296 2297 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2298 *DAG.getContext(), 2299 Sub.getValueType()), 2300 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2301 2302 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2303 // branch to failure MBB. 2304 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2305 MVT::Other, GuardVal.getOperand(0), 2306 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2307 // Otherwise branch to success MBB. 2308 SDValue Br = DAG.getNode(ISD::BR, dl, 2309 MVT::Other, BrCond, 2310 DAG.getBasicBlock(SPD.getSuccessMBB())); 2311 2312 DAG.setRoot(Br); 2313 } 2314 2315 /// Codegen the failure basic block for a stack protector check. 2316 /// 2317 /// A failure stack protector machine basic block consists simply of a call to 2318 /// __stack_chk_fail(). 2319 /// 2320 /// For a high level explanation of how this fits into the stack protector 2321 /// generation see the comment on the declaration of class 2322 /// StackProtectorDescriptor. 2323 void 2324 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2325 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2326 SDValue Chain = 2327 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2328 None, false, getCurSDLoc(), false, false).second; 2329 DAG.setRoot(Chain); 2330 } 2331 2332 /// visitBitTestHeader - This function emits necessary code to produce value 2333 /// suitable for "bit tests" 2334 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2335 MachineBasicBlock *SwitchBB) { 2336 SDLoc dl = getCurSDLoc(); 2337 2338 // Subtract the minimum value 2339 SDValue SwitchOp = getValue(B.SValue); 2340 EVT VT = SwitchOp.getValueType(); 2341 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2342 DAG.getConstant(B.First, dl, VT)); 2343 2344 // Check range 2345 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2346 SDValue RangeCmp = DAG.getSetCC( 2347 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2348 Sub.getValueType()), 2349 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2350 2351 // Determine the type of the test operands. 2352 bool UsePtrType = false; 2353 if (!TLI.isTypeLegal(VT)) 2354 UsePtrType = true; 2355 else { 2356 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2357 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2358 // Switch table case range are encoded into series of masks. 2359 // Just use pointer type, it's guaranteed to fit. 2360 UsePtrType = true; 2361 break; 2362 } 2363 } 2364 if (UsePtrType) { 2365 VT = TLI.getPointerTy(DAG.getDataLayout()); 2366 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2367 } 2368 2369 B.RegVT = VT.getSimpleVT(); 2370 B.Reg = FuncInfo.CreateReg(B.RegVT); 2371 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2372 2373 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2374 2375 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2376 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2377 SwitchBB->normalizeSuccProbs(); 2378 2379 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2380 MVT::Other, CopyTo, RangeCmp, 2381 DAG.getBasicBlock(B.Default)); 2382 2383 // Avoid emitting unnecessary branches to the next block. 2384 if (MBB != NextBlock(SwitchBB)) 2385 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2386 DAG.getBasicBlock(MBB)); 2387 2388 DAG.setRoot(BrRange); 2389 } 2390 2391 /// visitBitTestCase - this function produces one "bit test" 2392 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2393 MachineBasicBlock* NextMBB, 2394 BranchProbability BranchProbToNext, 2395 unsigned Reg, 2396 BitTestCase &B, 2397 MachineBasicBlock *SwitchBB) { 2398 SDLoc dl = getCurSDLoc(); 2399 MVT VT = BB.RegVT; 2400 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2401 SDValue Cmp; 2402 unsigned PopCount = countPopulation(B.Mask); 2403 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2404 if (PopCount == 1) { 2405 // Testing for a single bit; just compare the shift count with what it 2406 // would need to be to shift a 1 bit in that position. 2407 Cmp = DAG.getSetCC( 2408 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2409 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2410 ISD::SETEQ); 2411 } else if (PopCount == BB.Range) { 2412 // There is only one zero bit in the range, test for it directly. 2413 Cmp = DAG.getSetCC( 2414 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2415 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2416 ISD::SETNE); 2417 } else { 2418 // Make desired shift 2419 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2420 DAG.getConstant(1, dl, VT), ShiftOp); 2421 2422 // Emit bit tests and jumps 2423 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2424 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2425 Cmp = DAG.getSetCC( 2426 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2427 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2428 } 2429 2430 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2431 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2432 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2433 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2434 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2435 // one as they are relative probabilities (and thus work more like weights), 2436 // and hence we need to normalize them to let the sum of them become one. 2437 SwitchBB->normalizeSuccProbs(); 2438 2439 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2440 MVT::Other, getControlRoot(), 2441 Cmp, DAG.getBasicBlock(B.TargetBB)); 2442 2443 // Avoid emitting unnecessary branches to the next block. 2444 if (NextMBB != NextBlock(SwitchBB)) 2445 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2446 DAG.getBasicBlock(NextMBB)); 2447 2448 DAG.setRoot(BrAnd); 2449 } 2450 2451 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2452 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2453 2454 // Retrieve successors. Look through artificial IR level blocks like 2455 // catchswitch for successors. 2456 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2457 const BasicBlock *EHPadBB = I.getSuccessor(1); 2458 2459 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2460 // have to do anything here to lower funclet bundles. 2461 assert(!I.hasOperandBundlesOtherThan( 2462 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2463 "Cannot lower invokes with arbitrary operand bundles yet!"); 2464 2465 const Value *Callee(I.getCalledValue()); 2466 const Function *Fn = dyn_cast<Function>(Callee); 2467 if (isa<InlineAsm>(Callee)) 2468 visitInlineAsm(&I); 2469 else if (Fn && Fn->isIntrinsic()) { 2470 switch (Fn->getIntrinsicID()) { 2471 default: 2472 llvm_unreachable("Cannot invoke this intrinsic"); 2473 case Intrinsic::donothing: 2474 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2475 break; 2476 case Intrinsic::experimental_patchpoint_void: 2477 case Intrinsic::experimental_patchpoint_i64: 2478 visitPatchpoint(&I, EHPadBB); 2479 break; 2480 case Intrinsic::experimental_gc_statepoint: 2481 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2482 break; 2483 } 2484 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2485 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2486 // Eventually we will support lowering the @llvm.experimental.deoptimize 2487 // intrinsic, and right now there are no plans to support other intrinsics 2488 // with deopt state. 2489 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2490 } else { 2491 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2492 } 2493 2494 // If the value of the invoke is used outside of its defining block, make it 2495 // available as a virtual register. 2496 // We already took care of the exported value for the statepoint instruction 2497 // during call to the LowerStatepoint. 2498 if (!isStatepoint(I)) { 2499 CopyToExportRegsIfNeeded(&I); 2500 } 2501 2502 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2503 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2504 BranchProbability EHPadBBProb = 2505 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2506 : BranchProbability::getZero(); 2507 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2508 2509 // Update successor info. 2510 addSuccessorWithProb(InvokeMBB, Return); 2511 for (auto &UnwindDest : UnwindDests) { 2512 UnwindDest.first->setIsEHPad(); 2513 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2514 } 2515 InvokeMBB->normalizeSuccProbs(); 2516 2517 // Drop into normal successor. 2518 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2519 MVT::Other, getControlRoot(), 2520 DAG.getBasicBlock(Return))); 2521 } 2522 2523 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2524 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2525 } 2526 2527 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2528 assert(FuncInfo.MBB->isEHPad() && 2529 "Call to landingpad not in landing pad!"); 2530 2531 // If there aren't registers to copy the values into (e.g., during SjLj 2532 // exceptions), then don't bother to create these DAG nodes. 2533 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2534 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2535 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2536 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2537 return; 2538 2539 // If landingpad's return type is token type, we don't create DAG nodes 2540 // for its exception pointer and selector value. The extraction of exception 2541 // pointer or selector value from token type landingpads is not currently 2542 // supported. 2543 if (LP.getType()->isTokenTy()) 2544 return; 2545 2546 SmallVector<EVT, 2> ValueVTs; 2547 SDLoc dl = getCurSDLoc(); 2548 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2549 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2550 2551 // Get the two live-in registers as SDValues. The physregs have already been 2552 // copied into virtual registers. 2553 SDValue Ops[2]; 2554 if (FuncInfo.ExceptionPointerVirtReg) { 2555 Ops[0] = DAG.getZExtOrTrunc( 2556 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2557 FuncInfo.ExceptionPointerVirtReg, 2558 TLI.getPointerTy(DAG.getDataLayout())), 2559 dl, ValueVTs[0]); 2560 } else { 2561 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2562 } 2563 Ops[1] = DAG.getZExtOrTrunc( 2564 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2565 FuncInfo.ExceptionSelectorVirtReg, 2566 TLI.getPointerTy(DAG.getDataLayout())), 2567 dl, ValueVTs[1]); 2568 2569 // Merge into one. 2570 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2571 DAG.getVTList(ValueVTs), Ops); 2572 setValue(&LP, Res); 2573 } 2574 2575 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2576 #ifndef NDEBUG 2577 for (const CaseCluster &CC : Clusters) 2578 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2579 #endif 2580 2581 llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) { 2582 return a.Low->getValue().slt(b.Low->getValue()); 2583 }); 2584 2585 // Merge adjacent clusters with the same destination. 2586 const unsigned N = Clusters.size(); 2587 unsigned DstIndex = 0; 2588 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2589 CaseCluster &CC = Clusters[SrcIndex]; 2590 const ConstantInt *CaseVal = CC.Low; 2591 MachineBasicBlock *Succ = CC.MBB; 2592 2593 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2594 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2595 // If this case has the same successor and is a neighbour, merge it into 2596 // the previous cluster. 2597 Clusters[DstIndex - 1].High = CaseVal; 2598 Clusters[DstIndex - 1].Prob += CC.Prob; 2599 } else { 2600 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2601 sizeof(Clusters[SrcIndex])); 2602 } 2603 } 2604 Clusters.resize(DstIndex); 2605 } 2606 2607 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2608 MachineBasicBlock *Last) { 2609 // Update JTCases. 2610 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2611 if (JTCases[i].first.HeaderBB == First) 2612 JTCases[i].first.HeaderBB = Last; 2613 2614 // Update BitTestCases. 2615 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2616 if (BitTestCases[i].Parent == First) 2617 BitTestCases[i].Parent = Last; 2618 } 2619 2620 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2621 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2622 2623 // Update machine-CFG edges with unique successors. 2624 SmallSet<BasicBlock*, 32> Done; 2625 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2626 BasicBlock *BB = I.getSuccessor(i); 2627 bool Inserted = Done.insert(BB).second; 2628 if (!Inserted) 2629 continue; 2630 2631 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2632 addSuccessorWithProb(IndirectBrMBB, Succ); 2633 } 2634 IndirectBrMBB->normalizeSuccProbs(); 2635 2636 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2637 MVT::Other, getControlRoot(), 2638 getValue(I.getAddress()))); 2639 } 2640 2641 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2642 if (!DAG.getTarget().Options.TrapUnreachable) 2643 return; 2644 2645 // We may be able to ignore unreachable behind a noreturn call. 2646 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2647 const BasicBlock &BB = *I.getParent(); 2648 if (&I != &BB.front()) { 2649 BasicBlock::const_iterator PredI = 2650 std::prev(BasicBlock::const_iterator(&I)); 2651 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2652 if (Call->doesNotReturn()) 2653 return; 2654 } 2655 } 2656 } 2657 2658 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2659 } 2660 2661 void SelectionDAGBuilder::visitFSub(const User &I) { 2662 // -0.0 - X --> fneg 2663 Type *Ty = I.getType(); 2664 if (isa<Constant>(I.getOperand(0)) && 2665 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2666 SDValue Op2 = getValue(I.getOperand(1)); 2667 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2668 Op2.getValueType(), Op2)); 2669 return; 2670 } 2671 2672 visitBinary(I, ISD::FSUB); 2673 } 2674 2675 /// Checks if the given instruction performs a vector reduction, in which case 2676 /// we have the freedom to alter the elements in the result as long as the 2677 /// reduction of them stays unchanged. 2678 static bool isVectorReductionOp(const User *I) { 2679 const Instruction *Inst = dyn_cast<Instruction>(I); 2680 if (!Inst || !Inst->getType()->isVectorTy()) 2681 return false; 2682 2683 auto OpCode = Inst->getOpcode(); 2684 switch (OpCode) { 2685 case Instruction::Add: 2686 case Instruction::Mul: 2687 case Instruction::And: 2688 case Instruction::Or: 2689 case Instruction::Xor: 2690 break; 2691 case Instruction::FAdd: 2692 case Instruction::FMul: 2693 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2694 if (FPOp->getFastMathFlags().isFast()) 2695 break; 2696 LLVM_FALLTHROUGH; 2697 default: 2698 return false; 2699 } 2700 2701 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2702 // Ensure the reduction size is a power of 2. 2703 if (!isPowerOf2_32(ElemNum)) 2704 return false; 2705 2706 unsigned ElemNumToReduce = ElemNum; 2707 2708 // Do DFS search on the def-use chain from the given instruction. We only 2709 // allow four kinds of operations during the search until we reach the 2710 // instruction that extracts the first element from the vector: 2711 // 2712 // 1. The reduction operation of the same opcode as the given instruction. 2713 // 2714 // 2. PHI node. 2715 // 2716 // 3. ShuffleVector instruction together with a reduction operation that 2717 // does a partial reduction. 2718 // 2719 // 4. ExtractElement that extracts the first element from the vector, and we 2720 // stop searching the def-use chain here. 2721 // 2722 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2723 // from 1-3 to the stack to continue the DFS. The given instruction is not 2724 // a reduction operation if we meet any other instructions other than those 2725 // listed above. 2726 2727 SmallVector<const User *, 16> UsersToVisit{Inst}; 2728 SmallPtrSet<const User *, 16> Visited; 2729 bool ReduxExtracted = false; 2730 2731 while (!UsersToVisit.empty()) { 2732 auto User = UsersToVisit.back(); 2733 UsersToVisit.pop_back(); 2734 if (!Visited.insert(User).second) 2735 continue; 2736 2737 for (const auto &U : User->users()) { 2738 auto Inst = dyn_cast<Instruction>(U); 2739 if (!Inst) 2740 return false; 2741 2742 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2743 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2744 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 2745 return false; 2746 UsersToVisit.push_back(U); 2747 } else if (const ShuffleVectorInst *ShufInst = 2748 dyn_cast<ShuffleVectorInst>(U)) { 2749 // Detect the following pattern: A ShuffleVector instruction together 2750 // with a reduction that do partial reduction on the first and second 2751 // ElemNumToReduce / 2 elements, and store the result in 2752 // ElemNumToReduce / 2 elements in another vector. 2753 2754 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2755 if (ResultElements < ElemNum) 2756 return false; 2757 2758 if (ElemNumToReduce == 1) 2759 return false; 2760 if (!isa<UndefValue>(U->getOperand(1))) 2761 return false; 2762 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2763 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2764 return false; 2765 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2766 if (ShufInst->getMaskValue(i) != -1) 2767 return false; 2768 2769 // There is only one user of this ShuffleVector instruction, which 2770 // must be a reduction operation. 2771 if (!U->hasOneUse()) 2772 return false; 2773 2774 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2775 if (!U2 || U2->getOpcode() != OpCode) 2776 return false; 2777 2778 // Check operands of the reduction operation. 2779 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2780 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2781 UsersToVisit.push_back(U2); 2782 ElemNumToReduce /= 2; 2783 } else 2784 return false; 2785 } else if (isa<ExtractElementInst>(U)) { 2786 // At this moment we should have reduced all elements in the vector. 2787 if (ElemNumToReduce != 1) 2788 return false; 2789 2790 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2791 if (!Val || !Val->isZero()) 2792 return false; 2793 2794 ReduxExtracted = true; 2795 } else 2796 return false; 2797 } 2798 } 2799 return ReduxExtracted; 2800 } 2801 2802 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 2803 SDNodeFlags Flags; 2804 2805 SDValue Op = getValue(I.getOperand(0)); 2806 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 2807 Op, Flags); 2808 setValue(&I, UnNodeValue); 2809 } 2810 2811 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 2812 SDNodeFlags Flags; 2813 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 2814 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 2815 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 2816 } 2817 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 2818 Flags.setExact(ExactOp->isExact()); 2819 } 2820 if (isVectorReductionOp(&I)) { 2821 Flags.setVectorReduction(true); 2822 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2823 } 2824 2825 SDValue Op1 = getValue(I.getOperand(0)); 2826 SDValue Op2 = getValue(I.getOperand(1)); 2827 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 2828 Op1, Op2, Flags); 2829 setValue(&I, BinNodeValue); 2830 } 2831 2832 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2833 SDValue Op1 = getValue(I.getOperand(0)); 2834 SDValue Op2 = getValue(I.getOperand(1)); 2835 2836 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2837 Op1.getValueType(), DAG.getDataLayout()); 2838 2839 // Coerce the shift amount to the right type if we can. 2840 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2841 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2842 unsigned Op2Size = Op2.getValueSizeInBits(); 2843 SDLoc DL = getCurSDLoc(); 2844 2845 // If the operand is smaller than the shift count type, promote it. 2846 if (ShiftSize > Op2Size) 2847 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2848 2849 // If the operand is larger than the shift count type but the shift 2850 // count type has enough bits to represent any shift value, truncate 2851 // it now. This is a common case and it exposes the truncate to 2852 // optimization early. 2853 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 2854 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2855 // Otherwise we'll need to temporarily settle for some other convenient 2856 // type. Type legalization will make adjustments once the shiftee is split. 2857 else 2858 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2859 } 2860 2861 bool nuw = false; 2862 bool nsw = false; 2863 bool exact = false; 2864 2865 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2866 2867 if (const OverflowingBinaryOperator *OFBinOp = 2868 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2869 nuw = OFBinOp->hasNoUnsignedWrap(); 2870 nsw = OFBinOp->hasNoSignedWrap(); 2871 } 2872 if (const PossiblyExactOperator *ExactOp = 2873 dyn_cast<const PossiblyExactOperator>(&I)) 2874 exact = ExactOp->isExact(); 2875 } 2876 SDNodeFlags Flags; 2877 Flags.setExact(exact); 2878 Flags.setNoSignedWrap(nsw); 2879 Flags.setNoUnsignedWrap(nuw); 2880 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2881 Flags); 2882 setValue(&I, Res); 2883 } 2884 2885 void SelectionDAGBuilder::visitSDiv(const User &I) { 2886 SDValue Op1 = getValue(I.getOperand(0)); 2887 SDValue Op2 = getValue(I.getOperand(1)); 2888 2889 SDNodeFlags Flags; 2890 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2891 cast<PossiblyExactOperator>(&I)->isExact()); 2892 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2893 Op2, Flags)); 2894 } 2895 2896 void SelectionDAGBuilder::visitICmp(const User &I) { 2897 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2898 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2899 predicate = IC->getPredicate(); 2900 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2901 predicate = ICmpInst::Predicate(IC->getPredicate()); 2902 SDValue Op1 = getValue(I.getOperand(0)); 2903 SDValue Op2 = getValue(I.getOperand(1)); 2904 ISD::CondCode Opcode = getICmpCondCode(predicate); 2905 2906 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2907 I.getType()); 2908 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2909 } 2910 2911 void SelectionDAGBuilder::visitFCmp(const User &I) { 2912 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2913 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2914 predicate = FC->getPredicate(); 2915 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2916 predicate = FCmpInst::Predicate(FC->getPredicate()); 2917 SDValue Op1 = getValue(I.getOperand(0)); 2918 SDValue Op2 = getValue(I.getOperand(1)); 2919 2920 ISD::CondCode Condition = getFCmpCondCode(predicate); 2921 auto *FPMO = dyn_cast<FPMathOperator>(&I); 2922 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 2923 Condition = getFCmpCodeWithoutNaN(Condition); 2924 2925 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2926 I.getType()); 2927 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2928 } 2929 2930 // Check if the condition of the select has one use or two users that are both 2931 // selects with the same condition. 2932 static bool hasOnlySelectUsers(const Value *Cond) { 2933 return llvm::all_of(Cond->users(), [](const Value *V) { 2934 return isa<SelectInst>(V); 2935 }); 2936 } 2937 2938 void SelectionDAGBuilder::visitSelect(const User &I) { 2939 SmallVector<EVT, 4> ValueVTs; 2940 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2941 ValueVTs); 2942 unsigned NumValues = ValueVTs.size(); 2943 if (NumValues == 0) return; 2944 2945 SmallVector<SDValue, 4> Values(NumValues); 2946 SDValue Cond = getValue(I.getOperand(0)); 2947 SDValue LHSVal = getValue(I.getOperand(1)); 2948 SDValue RHSVal = getValue(I.getOperand(2)); 2949 auto BaseOps = {Cond}; 2950 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2951 ISD::VSELECT : ISD::SELECT; 2952 2953 // Min/max matching is only viable if all output VTs are the same. 2954 if (is_splat(ValueVTs)) { 2955 EVT VT = ValueVTs[0]; 2956 LLVMContext &Ctx = *DAG.getContext(); 2957 auto &TLI = DAG.getTargetLoweringInfo(); 2958 2959 // We care about the legality of the operation after it has been type 2960 // legalized. 2961 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 2962 VT != TLI.getTypeToTransformTo(Ctx, VT)) 2963 VT = TLI.getTypeToTransformTo(Ctx, VT); 2964 2965 // If the vselect is legal, assume we want to leave this as a vector setcc + 2966 // vselect. Otherwise, if this is going to be scalarized, we want to see if 2967 // min/max is legal on the scalar type. 2968 bool UseScalarMinMax = VT.isVector() && 2969 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 2970 2971 Value *LHS, *RHS; 2972 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2973 ISD::NodeType Opc = ISD::DELETED_NODE; 2974 switch (SPR.Flavor) { 2975 case SPF_UMAX: Opc = ISD::UMAX; break; 2976 case SPF_UMIN: Opc = ISD::UMIN; break; 2977 case SPF_SMAX: Opc = ISD::SMAX; break; 2978 case SPF_SMIN: Opc = ISD::SMIN; break; 2979 case SPF_FMINNUM: 2980 switch (SPR.NaNBehavior) { 2981 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2982 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 2983 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 2984 case SPNB_RETURNS_ANY: { 2985 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 2986 Opc = ISD::FMINNUM; 2987 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 2988 Opc = ISD::FMINIMUM; 2989 else if (UseScalarMinMax) 2990 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 2991 ISD::FMINNUM : ISD::FMINIMUM; 2992 break; 2993 } 2994 } 2995 break; 2996 case SPF_FMAXNUM: 2997 switch (SPR.NaNBehavior) { 2998 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2999 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3000 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3001 case SPNB_RETURNS_ANY: 3002 3003 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3004 Opc = ISD::FMAXNUM; 3005 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3006 Opc = ISD::FMAXIMUM; 3007 else if (UseScalarMinMax) 3008 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3009 ISD::FMAXNUM : ISD::FMAXIMUM; 3010 break; 3011 } 3012 break; 3013 default: break; 3014 } 3015 3016 if (Opc != ISD::DELETED_NODE && 3017 (TLI.isOperationLegalOrCustom(Opc, VT) || 3018 (UseScalarMinMax && 3019 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3020 // If the underlying comparison instruction is used by any other 3021 // instruction, the consumed instructions won't be destroyed, so it is 3022 // not profitable to convert to a min/max. 3023 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3024 OpCode = Opc; 3025 LHSVal = getValue(LHS); 3026 RHSVal = getValue(RHS); 3027 BaseOps = {}; 3028 } 3029 } 3030 3031 for (unsigned i = 0; i != NumValues; ++i) { 3032 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3033 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3034 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3035 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 3036 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 3037 Ops); 3038 } 3039 3040 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3041 DAG.getVTList(ValueVTs), Values)); 3042 } 3043 3044 void SelectionDAGBuilder::visitTrunc(const User &I) { 3045 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3046 SDValue N = getValue(I.getOperand(0)); 3047 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3048 I.getType()); 3049 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3050 } 3051 3052 void SelectionDAGBuilder::visitZExt(const User &I) { 3053 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3054 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3055 SDValue N = getValue(I.getOperand(0)); 3056 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3057 I.getType()); 3058 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3059 } 3060 3061 void SelectionDAGBuilder::visitSExt(const User &I) { 3062 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3063 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3064 SDValue N = getValue(I.getOperand(0)); 3065 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3066 I.getType()); 3067 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3068 } 3069 3070 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3071 // FPTrunc is never a no-op cast, no need to check 3072 SDValue N = getValue(I.getOperand(0)); 3073 SDLoc dl = getCurSDLoc(); 3074 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3075 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3076 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3077 DAG.getTargetConstant( 3078 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3079 } 3080 3081 void SelectionDAGBuilder::visitFPExt(const User &I) { 3082 // FPExt is never a no-op cast, no need to check 3083 SDValue N = getValue(I.getOperand(0)); 3084 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3085 I.getType()); 3086 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3087 } 3088 3089 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3090 // FPToUI is never a no-op cast, no need to check 3091 SDValue N = getValue(I.getOperand(0)); 3092 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3093 I.getType()); 3094 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3095 } 3096 3097 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3098 // FPToSI is never a no-op cast, no need to check 3099 SDValue N = getValue(I.getOperand(0)); 3100 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3101 I.getType()); 3102 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3103 } 3104 3105 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3106 // UIToFP is never a no-op cast, no need to check 3107 SDValue N = getValue(I.getOperand(0)); 3108 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3109 I.getType()); 3110 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3111 } 3112 3113 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3114 // SIToFP is never a no-op cast, no need to check 3115 SDValue N = getValue(I.getOperand(0)); 3116 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3117 I.getType()); 3118 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3119 } 3120 3121 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3122 // What to do depends on the size of the integer and the size of the pointer. 3123 // We can either truncate, zero extend, or no-op, accordingly. 3124 SDValue N = getValue(I.getOperand(0)); 3125 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3126 I.getType()); 3127 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3128 } 3129 3130 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3131 // What to do depends on the size of the integer and the size of the pointer. 3132 // We can either truncate, zero extend, or no-op, accordingly. 3133 SDValue N = getValue(I.getOperand(0)); 3134 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3135 I.getType()); 3136 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3137 } 3138 3139 void SelectionDAGBuilder::visitBitCast(const User &I) { 3140 SDValue N = getValue(I.getOperand(0)); 3141 SDLoc dl = getCurSDLoc(); 3142 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3143 I.getType()); 3144 3145 // BitCast assures us that source and destination are the same size so this is 3146 // either a BITCAST or a no-op. 3147 if (DestVT != N.getValueType()) 3148 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3149 DestVT, N)); // convert types. 3150 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3151 // might fold any kind of constant expression to an integer constant and that 3152 // is not what we are looking for. Only recognize a bitcast of a genuine 3153 // constant integer as an opaque constant. 3154 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3155 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3156 /*isOpaque*/true)); 3157 else 3158 setValue(&I, N); // noop cast. 3159 } 3160 3161 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3162 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3163 const Value *SV = I.getOperand(0); 3164 SDValue N = getValue(SV); 3165 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3166 3167 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3168 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3169 3170 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3171 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3172 3173 setValue(&I, N); 3174 } 3175 3176 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3177 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3178 SDValue InVec = getValue(I.getOperand(0)); 3179 SDValue InVal = getValue(I.getOperand(1)); 3180 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3181 TLI.getVectorIdxTy(DAG.getDataLayout())); 3182 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3183 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3184 InVec, InVal, InIdx)); 3185 } 3186 3187 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3188 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3189 SDValue InVec = getValue(I.getOperand(0)); 3190 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3191 TLI.getVectorIdxTy(DAG.getDataLayout())); 3192 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3193 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3194 InVec, InIdx)); 3195 } 3196 3197 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3198 SDValue Src1 = getValue(I.getOperand(0)); 3199 SDValue Src2 = getValue(I.getOperand(1)); 3200 SDLoc DL = getCurSDLoc(); 3201 3202 SmallVector<int, 8> Mask; 3203 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3204 unsigned MaskNumElts = Mask.size(); 3205 3206 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3207 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3208 EVT SrcVT = Src1.getValueType(); 3209 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3210 3211 if (SrcNumElts == MaskNumElts) { 3212 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3213 return; 3214 } 3215 3216 // Normalize the shuffle vector since mask and vector length don't match. 3217 if (SrcNumElts < MaskNumElts) { 3218 // Mask is longer than the source vectors. We can use concatenate vector to 3219 // make the mask and vectors lengths match. 3220 3221 if (MaskNumElts % SrcNumElts == 0) { 3222 // Mask length is a multiple of the source vector length. 3223 // Check if the shuffle is some kind of concatenation of the input 3224 // vectors. 3225 unsigned NumConcat = MaskNumElts / SrcNumElts; 3226 bool IsConcat = true; 3227 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3228 for (unsigned i = 0; i != MaskNumElts; ++i) { 3229 int Idx = Mask[i]; 3230 if (Idx < 0) 3231 continue; 3232 // Ensure the indices in each SrcVT sized piece are sequential and that 3233 // the same source is used for the whole piece. 3234 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3235 (ConcatSrcs[i / SrcNumElts] >= 0 && 3236 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3237 IsConcat = false; 3238 break; 3239 } 3240 // Remember which source this index came from. 3241 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3242 } 3243 3244 // The shuffle is concatenating multiple vectors together. Just emit 3245 // a CONCAT_VECTORS operation. 3246 if (IsConcat) { 3247 SmallVector<SDValue, 8> ConcatOps; 3248 for (auto Src : ConcatSrcs) { 3249 if (Src < 0) 3250 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3251 else if (Src == 0) 3252 ConcatOps.push_back(Src1); 3253 else 3254 ConcatOps.push_back(Src2); 3255 } 3256 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3257 return; 3258 } 3259 } 3260 3261 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3262 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3263 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3264 PaddedMaskNumElts); 3265 3266 // Pad both vectors with undefs to make them the same length as the mask. 3267 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3268 3269 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3270 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3271 MOps1[0] = Src1; 3272 MOps2[0] = Src2; 3273 3274 Src1 = Src1.isUndef() 3275 ? DAG.getUNDEF(PaddedVT) 3276 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3277 Src2 = Src2.isUndef() 3278 ? DAG.getUNDEF(PaddedVT) 3279 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3280 3281 // Readjust mask for new input vector length. 3282 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3283 for (unsigned i = 0; i != MaskNumElts; ++i) { 3284 int Idx = Mask[i]; 3285 if (Idx >= (int)SrcNumElts) 3286 Idx -= SrcNumElts - PaddedMaskNumElts; 3287 MappedOps[i] = Idx; 3288 } 3289 3290 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3291 3292 // If the concatenated vector was padded, extract a subvector with the 3293 // correct number of elements. 3294 if (MaskNumElts != PaddedMaskNumElts) 3295 Result = DAG.getNode( 3296 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3297 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3298 3299 setValue(&I, Result); 3300 return; 3301 } 3302 3303 if (SrcNumElts > MaskNumElts) { 3304 // Analyze the access pattern of the vector to see if we can extract 3305 // two subvectors and do the shuffle. 3306 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3307 bool CanExtract = true; 3308 for (int Idx : Mask) { 3309 unsigned Input = 0; 3310 if (Idx < 0) 3311 continue; 3312 3313 if (Idx >= (int)SrcNumElts) { 3314 Input = 1; 3315 Idx -= SrcNumElts; 3316 } 3317 3318 // If all the indices come from the same MaskNumElts sized portion of 3319 // the sources we can use extract. Also make sure the extract wouldn't 3320 // extract past the end of the source. 3321 int NewStartIdx = alignDown(Idx, MaskNumElts); 3322 if (NewStartIdx + MaskNumElts > SrcNumElts || 3323 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3324 CanExtract = false; 3325 // Make sure we always update StartIdx as we use it to track if all 3326 // elements are undef. 3327 StartIdx[Input] = NewStartIdx; 3328 } 3329 3330 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3331 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3332 return; 3333 } 3334 if (CanExtract) { 3335 // Extract appropriate subvector and generate a vector shuffle 3336 for (unsigned Input = 0; Input < 2; ++Input) { 3337 SDValue &Src = Input == 0 ? Src1 : Src2; 3338 if (StartIdx[Input] < 0) 3339 Src = DAG.getUNDEF(VT); 3340 else { 3341 Src = DAG.getNode( 3342 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3343 DAG.getConstant(StartIdx[Input], DL, 3344 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3345 } 3346 } 3347 3348 // Calculate new mask. 3349 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3350 for (int &Idx : MappedOps) { 3351 if (Idx >= (int)SrcNumElts) 3352 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3353 else if (Idx >= 0) 3354 Idx -= StartIdx[0]; 3355 } 3356 3357 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3358 return; 3359 } 3360 } 3361 3362 // We can't use either concat vectors or extract subvectors so fall back to 3363 // replacing the shuffle with extract and build vector. 3364 // to insert and build vector. 3365 EVT EltVT = VT.getVectorElementType(); 3366 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3367 SmallVector<SDValue,8> Ops; 3368 for (int Idx : Mask) { 3369 SDValue Res; 3370 3371 if (Idx < 0) { 3372 Res = DAG.getUNDEF(EltVT); 3373 } else { 3374 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3375 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3376 3377 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3378 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3379 } 3380 3381 Ops.push_back(Res); 3382 } 3383 3384 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3385 } 3386 3387 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3388 ArrayRef<unsigned> Indices; 3389 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3390 Indices = IV->getIndices(); 3391 else 3392 Indices = cast<ConstantExpr>(&I)->getIndices(); 3393 3394 const Value *Op0 = I.getOperand(0); 3395 const Value *Op1 = I.getOperand(1); 3396 Type *AggTy = I.getType(); 3397 Type *ValTy = Op1->getType(); 3398 bool IntoUndef = isa<UndefValue>(Op0); 3399 bool FromUndef = isa<UndefValue>(Op1); 3400 3401 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3402 3403 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3404 SmallVector<EVT, 4> AggValueVTs; 3405 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3406 SmallVector<EVT, 4> ValValueVTs; 3407 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3408 3409 unsigned NumAggValues = AggValueVTs.size(); 3410 unsigned NumValValues = ValValueVTs.size(); 3411 SmallVector<SDValue, 4> Values(NumAggValues); 3412 3413 // Ignore an insertvalue that produces an empty object 3414 if (!NumAggValues) { 3415 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3416 return; 3417 } 3418 3419 SDValue Agg = getValue(Op0); 3420 unsigned i = 0; 3421 // Copy the beginning value(s) from the original aggregate. 3422 for (; i != LinearIndex; ++i) 3423 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3424 SDValue(Agg.getNode(), Agg.getResNo() + i); 3425 // Copy values from the inserted value(s). 3426 if (NumValValues) { 3427 SDValue Val = getValue(Op1); 3428 for (; i != LinearIndex + NumValValues; ++i) 3429 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3430 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3431 } 3432 // Copy remaining value(s) from the original aggregate. 3433 for (; i != NumAggValues; ++i) 3434 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3435 SDValue(Agg.getNode(), Agg.getResNo() + i); 3436 3437 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3438 DAG.getVTList(AggValueVTs), Values)); 3439 } 3440 3441 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3442 ArrayRef<unsigned> Indices; 3443 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3444 Indices = EV->getIndices(); 3445 else 3446 Indices = cast<ConstantExpr>(&I)->getIndices(); 3447 3448 const Value *Op0 = I.getOperand(0); 3449 Type *AggTy = Op0->getType(); 3450 Type *ValTy = I.getType(); 3451 bool OutOfUndef = isa<UndefValue>(Op0); 3452 3453 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3454 3455 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3456 SmallVector<EVT, 4> ValValueVTs; 3457 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3458 3459 unsigned NumValValues = ValValueVTs.size(); 3460 3461 // Ignore a extractvalue that produces an empty object 3462 if (!NumValValues) { 3463 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3464 return; 3465 } 3466 3467 SmallVector<SDValue, 4> Values(NumValValues); 3468 3469 SDValue Agg = getValue(Op0); 3470 // Copy out the selected value(s). 3471 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3472 Values[i - LinearIndex] = 3473 OutOfUndef ? 3474 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3475 SDValue(Agg.getNode(), Agg.getResNo() + i); 3476 3477 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3478 DAG.getVTList(ValValueVTs), Values)); 3479 } 3480 3481 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3482 Value *Op0 = I.getOperand(0); 3483 // Note that the pointer operand may be a vector of pointers. Take the scalar 3484 // element which holds a pointer. 3485 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3486 SDValue N = getValue(Op0); 3487 SDLoc dl = getCurSDLoc(); 3488 3489 // Normalize Vector GEP - all scalar operands should be converted to the 3490 // splat vector. 3491 unsigned VectorWidth = I.getType()->isVectorTy() ? 3492 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3493 3494 if (VectorWidth && !N.getValueType().isVector()) { 3495 LLVMContext &Context = *DAG.getContext(); 3496 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3497 N = DAG.getSplatBuildVector(VT, dl, N); 3498 } 3499 3500 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3501 GTI != E; ++GTI) { 3502 const Value *Idx = GTI.getOperand(); 3503 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3504 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3505 if (Field) { 3506 // N = N + Offset 3507 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3508 3509 // In an inbounds GEP with an offset that is nonnegative even when 3510 // interpreted as signed, assume there is no unsigned overflow. 3511 SDNodeFlags Flags; 3512 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3513 Flags.setNoUnsignedWrap(true); 3514 3515 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3516 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3517 } 3518 } else { 3519 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3520 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3521 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3522 3523 // If this is a scalar constant or a splat vector of constants, 3524 // handle it quickly. 3525 const auto *CI = dyn_cast<ConstantInt>(Idx); 3526 if (!CI && isa<ConstantDataVector>(Idx) && 3527 cast<ConstantDataVector>(Idx)->getSplatValue()) 3528 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3529 3530 if (CI) { 3531 if (CI->isZero()) 3532 continue; 3533 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3534 LLVMContext &Context = *DAG.getContext(); 3535 SDValue OffsVal = VectorWidth ? 3536 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3537 DAG.getConstant(Offs, dl, IdxTy); 3538 3539 // In an inbouds GEP with an offset that is nonnegative even when 3540 // interpreted as signed, assume there is no unsigned overflow. 3541 SDNodeFlags Flags; 3542 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3543 Flags.setNoUnsignedWrap(true); 3544 3545 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3546 continue; 3547 } 3548 3549 // N = N + Idx * ElementSize; 3550 SDValue IdxN = getValue(Idx); 3551 3552 if (!IdxN.getValueType().isVector() && VectorWidth) { 3553 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3554 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3555 } 3556 3557 // If the index is smaller or larger than intptr_t, truncate or extend 3558 // it. 3559 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3560 3561 // If this is a multiply by a power of two, turn it into a shl 3562 // immediately. This is a very common case. 3563 if (ElementSize != 1) { 3564 if (ElementSize.isPowerOf2()) { 3565 unsigned Amt = ElementSize.logBase2(); 3566 IdxN = DAG.getNode(ISD::SHL, dl, 3567 N.getValueType(), IdxN, 3568 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3569 } else { 3570 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3571 IdxN = DAG.getNode(ISD::MUL, dl, 3572 N.getValueType(), IdxN, Scale); 3573 } 3574 } 3575 3576 N = DAG.getNode(ISD::ADD, dl, 3577 N.getValueType(), N, IdxN); 3578 } 3579 } 3580 3581 setValue(&I, N); 3582 } 3583 3584 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3585 // If this is a fixed sized alloca in the entry block of the function, 3586 // allocate it statically on the stack. 3587 if (FuncInfo.StaticAllocaMap.count(&I)) 3588 return; // getValue will auto-populate this. 3589 3590 SDLoc dl = getCurSDLoc(); 3591 Type *Ty = I.getAllocatedType(); 3592 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3593 auto &DL = DAG.getDataLayout(); 3594 uint64_t TySize = DL.getTypeAllocSize(Ty); 3595 unsigned Align = 3596 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3597 3598 SDValue AllocSize = getValue(I.getArraySize()); 3599 3600 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3601 if (AllocSize.getValueType() != IntPtr) 3602 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3603 3604 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3605 AllocSize, 3606 DAG.getConstant(TySize, dl, IntPtr)); 3607 3608 // Handle alignment. If the requested alignment is less than or equal to 3609 // the stack alignment, ignore it. If the size is greater than or equal to 3610 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3611 unsigned StackAlign = 3612 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3613 if (Align <= StackAlign) 3614 Align = 0; 3615 3616 // Round the size of the allocation up to the stack alignment size 3617 // by add SA-1 to the size. This doesn't overflow because we're computing 3618 // an address inside an alloca. 3619 SDNodeFlags Flags; 3620 Flags.setNoUnsignedWrap(true); 3621 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3622 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3623 3624 // Mask out the low bits for alignment purposes. 3625 AllocSize = 3626 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3627 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3628 3629 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3630 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3631 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3632 setValue(&I, DSA); 3633 DAG.setRoot(DSA.getValue(1)); 3634 3635 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3636 } 3637 3638 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3639 if (I.isAtomic()) 3640 return visitAtomicLoad(I); 3641 3642 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3643 const Value *SV = I.getOperand(0); 3644 if (TLI.supportSwiftError()) { 3645 // Swifterror values can come from either a function parameter with 3646 // swifterror attribute or an alloca with swifterror attribute. 3647 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3648 if (Arg->hasSwiftErrorAttr()) 3649 return visitLoadFromSwiftError(I); 3650 } 3651 3652 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3653 if (Alloca->isSwiftError()) 3654 return visitLoadFromSwiftError(I); 3655 } 3656 } 3657 3658 SDValue Ptr = getValue(SV); 3659 3660 Type *Ty = I.getType(); 3661 3662 bool isVolatile = I.isVolatile(); 3663 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3664 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3665 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3666 unsigned Alignment = I.getAlignment(); 3667 3668 AAMDNodes AAInfo; 3669 I.getAAMetadata(AAInfo); 3670 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3671 3672 SmallVector<EVT, 4> ValueVTs; 3673 SmallVector<uint64_t, 4> Offsets; 3674 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3675 unsigned NumValues = ValueVTs.size(); 3676 if (NumValues == 0) 3677 return; 3678 3679 SDValue Root; 3680 bool ConstantMemory = false; 3681 if (isVolatile || NumValues > MaxParallelChains) 3682 // Serialize volatile loads with other side effects. 3683 Root = getRoot(); 3684 else if (AA && 3685 AA->pointsToConstantMemory(MemoryLocation( 3686 SV, 3687 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3688 AAInfo))) { 3689 // Do not serialize (non-volatile) loads of constant memory with anything. 3690 Root = DAG.getEntryNode(); 3691 ConstantMemory = true; 3692 } else { 3693 // Do not serialize non-volatile loads against each other. 3694 Root = DAG.getRoot(); 3695 } 3696 3697 SDLoc dl = getCurSDLoc(); 3698 3699 if (isVolatile) 3700 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3701 3702 // An aggregate load cannot wrap around the address space, so offsets to its 3703 // parts don't wrap either. 3704 SDNodeFlags Flags; 3705 Flags.setNoUnsignedWrap(true); 3706 3707 SmallVector<SDValue, 4> Values(NumValues); 3708 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3709 EVT PtrVT = Ptr.getValueType(); 3710 unsigned ChainI = 0; 3711 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3712 // Serializing loads here may result in excessive register pressure, and 3713 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3714 // could recover a bit by hoisting nodes upward in the chain by recognizing 3715 // they are side-effect free or do not alias. The optimizer should really 3716 // avoid this case by converting large object/array copies to llvm.memcpy 3717 // (MaxParallelChains should always remain as failsafe). 3718 if (ChainI == MaxParallelChains) { 3719 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3720 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3721 makeArrayRef(Chains.data(), ChainI)); 3722 Root = Chain; 3723 ChainI = 0; 3724 } 3725 SDValue A = DAG.getNode(ISD::ADD, dl, 3726 PtrVT, Ptr, 3727 DAG.getConstant(Offsets[i], dl, PtrVT), 3728 Flags); 3729 auto MMOFlags = MachineMemOperand::MONone; 3730 if (isVolatile) 3731 MMOFlags |= MachineMemOperand::MOVolatile; 3732 if (isNonTemporal) 3733 MMOFlags |= MachineMemOperand::MONonTemporal; 3734 if (isInvariant) 3735 MMOFlags |= MachineMemOperand::MOInvariant; 3736 if (isDereferenceable) 3737 MMOFlags |= MachineMemOperand::MODereferenceable; 3738 MMOFlags |= TLI.getMMOFlags(I); 3739 3740 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3741 MachinePointerInfo(SV, Offsets[i]), Alignment, 3742 MMOFlags, AAInfo, Ranges); 3743 3744 Values[i] = L; 3745 Chains[ChainI] = L.getValue(1); 3746 } 3747 3748 if (!ConstantMemory) { 3749 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3750 makeArrayRef(Chains.data(), ChainI)); 3751 if (isVolatile) 3752 DAG.setRoot(Chain); 3753 else 3754 PendingLoads.push_back(Chain); 3755 } 3756 3757 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3758 DAG.getVTList(ValueVTs), Values)); 3759 } 3760 3761 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3762 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3763 "call visitStoreToSwiftError when backend supports swifterror"); 3764 3765 SmallVector<EVT, 4> ValueVTs; 3766 SmallVector<uint64_t, 4> Offsets; 3767 const Value *SrcV = I.getOperand(0); 3768 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3769 SrcV->getType(), ValueVTs, &Offsets); 3770 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3771 "expect a single EVT for swifterror"); 3772 3773 SDValue Src = getValue(SrcV); 3774 // Create a virtual register, then update the virtual register. 3775 unsigned VReg; bool CreatedVReg; 3776 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 3777 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3778 // Chain can be getRoot or getControlRoot. 3779 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3780 SDValue(Src.getNode(), Src.getResNo())); 3781 DAG.setRoot(CopyNode); 3782 if (CreatedVReg) 3783 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3784 } 3785 3786 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3787 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3788 "call visitLoadFromSwiftError when backend supports swifterror"); 3789 3790 assert(!I.isVolatile() && 3791 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3792 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3793 "Support volatile, non temporal, invariant for load_from_swift_error"); 3794 3795 const Value *SV = I.getOperand(0); 3796 Type *Ty = I.getType(); 3797 AAMDNodes AAInfo; 3798 I.getAAMetadata(AAInfo); 3799 assert( 3800 (!AA || 3801 !AA->pointsToConstantMemory(MemoryLocation( 3802 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3803 AAInfo))) && 3804 "load_from_swift_error should not be constant memory"); 3805 3806 SmallVector<EVT, 4> ValueVTs; 3807 SmallVector<uint64_t, 4> Offsets; 3808 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3809 ValueVTs, &Offsets); 3810 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3811 "expect a single EVT for swifterror"); 3812 3813 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3814 SDValue L = DAG.getCopyFromReg( 3815 getRoot(), getCurSDLoc(), 3816 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 3817 ValueVTs[0]); 3818 3819 setValue(&I, L); 3820 } 3821 3822 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3823 if (I.isAtomic()) 3824 return visitAtomicStore(I); 3825 3826 const Value *SrcV = I.getOperand(0); 3827 const Value *PtrV = I.getOperand(1); 3828 3829 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3830 if (TLI.supportSwiftError()) { 3831 // Swifterror values can come from either a function parameter with 3832 // swifterror attribute or an alloca with swifterror attribute. 3833 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3834 if (Arg->hasSwiftErrorAttr()) 3835 return visitStoreToSwiftError(I); 3836 } 3837 3838 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3839 if (Alloca->isSwiftError()) 3840 return visitStoreToSwiftError(I); 3841 } 3842 } 3843 3844 SmallVector<EVT, 4> ValueVTs; 3845 SmallVector<uint64_t, 4> Offsets; 3846 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3847 SrcV->getType(), ValueVTs, &Offsets); 3848 unsigned NumValues = ValueVTs.size(); 3849 if (NumValues == 0) 3850 return; 3851 3852 // Get the lowered operands. Note that we do this after 3853 // checking if NumResults is zero, because with zero results 3854 // the operands won't have values in the map. 3855 SDValue Src = getValue(SrcV); 3856 SDValue Ptr = getValue(PtrV); 3857 3858 SDValue Root = getRoot(); 3859 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3860 SDLoc dl = getCurSDLoc(); 3861 EVT PtrVT = Ptr.getValueType(); 3862 unsigned Alignment = I.getAlignment(); 3863 AAMDNodes AAInfo; 3864 I.getAAMetadata(AAInfo); 3865 3866 auto MMOFlags = MachineMemOperand::MONone; 3867 if (I.isVolatile()) 3868 MMOFlags |= MachineMemOperand::MOVolatile; 3869 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3870 MMOFlags |= MachineMemOperand::MONonTemporal; 3871 MMOFlags |= TLI.getMMOFlags(I); 3872 3873 // An aggregate load cannot wrap around the address space, so offsets to its 3874 // parts don't wrap either. 3875 SDNodeFlags Flags; 3876 Flags.setNoUnsignedWrap(true); 3877 3878 unsigned ChainI = 0; 3879 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3880 // See visitLoad comments. 3881 if (ChainI == MaxParallelChains) { 3882 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3883 makeArrayRef(Chains.data(), ChainI)); 3884 Root = Chain; 3885 ChainI = 0; 3886 } 3887 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3888 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 3889 SDValue St = DAG.getStore( 3890 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3891 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3892 Chains[ChainI] = St; 3893 } 3894 3895 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3896 makeArrayRef(Chains.data(), ChainI)); 3897 DAG.setRoot(StoreNode); 3898 } 3899 3900 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 3901 bool IsCompressing) { 3902 SDLoc sdl = getCurSDLoc(); 3903 3904 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3905 unsigned& Alignment) { 3906 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3907 Src0 = I.getArgOperand(0); 3908 Ptr = I.getArgOperand(1); 3909 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3910 Mask = I.getArgOperand(3); 3911 }; 3912 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3913 unsigned& Alignment) { 3914 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 3915 Src0 = I.getArgOperand(0); 3916 Ptr = I.getArgOperand(1); 3917 Mask = I.getArgOperand(2); 3918 Alignment = 0; 3919 }; 3920 3921 Value *PtrOperand, *MaskOperand, *Src0Operand; 3922 unsigned Alignment; 3923 if (IsCompressing) 3924 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3925 else 3926 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3927 3928 SDValue Ptr = getValue(PtrOperand); 3929 SDValue Src0 = getValue(Src0Operand); 3930 SDValue Mask = getValue(MaskOperand); 3931 3932 EVT VT = Src0.getValueType(); 3933 if (!Alignment) 3934 Alignment = DAG.getEVTAlignment(VT); 3935 3936 AAMDNodes AAInfo; 3937 I.getAAMetadata(AAInfo); 3938 3939 MachineMemOperand *MMO = 3940 DAG.getMachineFunction(). 3941 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3942 MachineMemOperand::MOStore, VT.getStoreSize(), 3943 Alignment, AAInfo); 3944 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3945 MMO, false /* Truncating */, 3946 IsCompressing); 3947 DAG.setRoot(StoreNode); 3948 setValue(&I, StoreNode); 3949 } 3950 3951 // Get a uniform base for the Gather/Scatter intrinsic. 3952 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 3953 // We try to represent it as a base pointer + vector of indices. 3954 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 3955 // The first operand of the GEP may be a single pointer or a vector of pointers 3956 // Example: 3957 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 3958 // or 3959 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 3960 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 3961 // 3962 // When the first GEP operand is a single pointer - it is the uniform base we 3963 // are looking for. If first operand of the GEP is a splat vector - we 3964 // extract the splat value and use it as a uniform base. 3965 // In all other cases the function returns 'false'. 3966 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 3967 SDValue &Scale, SelectionDAGBuilder* SDB) { 3968 SelectionDAG& DAG = SDB->DAG; 3969 LLVMContext &Context = *DAG.getContext(); 3970 3971 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 3972 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 3973 if (!GEP) 3974 return false; 3975 3976 const Value *GEPPtr = GEP->getPointerOperand(); 3977 if (!GEPPtr->getType()->isVectorTy()) 3978 Ptr = GEPPtr; 3979 else if (!(Ptr = getSplatValue(GEPPtr))) 3980 return false; 3981 3982 unsigned FinalIndex = GEP->getNumOperands() - 1; 3983 Value *IndexVal = GEP->getOperand(FinalIndex); 3984 3985 // Ensure all the other indices are 0. 3986 for (unsigned i = 1; i < FinalIndex; ++i) { 3987 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 3988 if (!C || !C->isZero()) 3989 return false; 3990 } 3991 3992 // The operands of the GEP may be defined in another basic block. 3993 // In this case we'll not find nodes for the operands. 3994 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 3995 return false; 3996 3997 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3998 const DataLayout &DL = DAG.getDataLayout(); 3999 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4000 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4001 Base = SDB->getValue(Ptr); 4002 Index = SDB->getValue(IndexVal); 4003 4004 if (!Index.getValueType().isVector()) { 4005 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4006 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4007 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4008 } 4009 return true; 4010 } 4011 4012 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4013 SDLoc sdl = getCurSDLoc(); 4014 4015 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4016 const Value *Ptr = I.getArgOperand(1); 4017 SDValue Src0 = getValue(I.getArgOperand(0)); 4018 SDValue Mask = getValue(I.getArgOperand(3)); 4019 EVT VT = Src0.getValueType(); 4020 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4021 if (!Alignment) 4022 Alignment = DAG.getEVTAlignment(VT); 4023 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4024 4025 AAMDNodes AAInfo; 4026 I.getAAMetadata(AAInfo); 4027 4028 SDValue Base; 4029 SDValue Index; 4030 SDValue Scale; 4031 const Value *BasePtr = Ptr; 4032 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4033 4034 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4035 MachineMemOperand *MMO = DAG.getMachineFunction(). 4036 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4037 MachineMemOperand::MOStore, VT.getStoreSize(), 4038 Alignment, AAInfo); 4039 if (!UniformBase) { 4040 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4041 Index = getValue(Ptr); 4042 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4043 } 4044 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4045 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4046 Ops, MMO); 4047 DAG.setRoot(Scatter); 4048 setValue(&I, Scatter); 4049 } 4050 4051 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4052 SDLoc sdl = getCurSDLoc(); 4053 4054 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4055 unsigned& Alignment) { 4056 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4057 Ptr = I.getArgOperand(0); 4058 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4059 Mask = I.getArgOperand(2); 4060 Src0 = I.getArgOperand(3); 4061 }; 4062 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4063 unsigned& Alignment) { 4064 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4065 Ptr = I.getArgOperand(0); 4066 Alignment = 0; 4067 Mask = I.getArgOperand(1); 4068 Src0 = I.getArgOperand(2); 4069 }; 4070 4071 Value *PtrOperand, *MaskOperand, *Src0Operand; 4072 unsigned Alignment; 4073 if (IsExpanding) 4074 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4075 else 4076 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4077 4078 SDValue Ptr = getValue(PtrOperand); 4079 SDValue Src0 = getValue(Src0Operand); 4080 SDValue Mask = getValue(MaskOperand); 4081 4082 EVT VT = Src0.getValueType(); 4083 if (!Alignment) 4084 Alignment = DAG.getEVTAlignment(VT); 4085 4086 AAMDNodes AAInfo; 4087 I.getAAMetadata(AAInfo); 4088 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4089 4090 // Do not serialize masked loads of constant memory with anything. 4091 bool AddToChain = 4092 !AA || !AA->pointsToConstantMemory(MemoryLocation( 4093 PtrOperand, 4094 LocationSize::precise( 4095 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4096 AAInfo)); 4097 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4098 4099 MachineMemOperand *MMO = 4100 DAG.getMachineFunction(). 4101 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4102 MachineMemOperand::MOLoad, VT.getStoreSize(), 4103 Alignment, AAInfo, Ranges); 4104 4105 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4106 ISD::NON_EXTLOAD, IsExpanding); 4107 if (AddToChain) 4108 PendingLoads.push_back(Load.getValue(1)); 4109 setValue(&I, Load); 4110 } 4111 4112 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4113 SDLoc sdl = getCurSDLoc(); 4114 4115 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4116 const Value *Ptr = I.getArgOperand(0); 4117 SDValue Src0 = getValue(I.getArgOperand(3)); 4118 SDValue Mask = getValue(I.getArgOperand(2)); 4119 4120 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4121 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4122 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4123 if (!Alignment) 4124 Alignment = DAG.getEVTAlignment(VT); 4125 4126 AAMDNodes AAInfo; 4127 I.getAAMetadata(AAInfo); 4128 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4129 4130 SDValue Root = DAG.getRoot(); 4131 SDValue Base; 4132 SDValue Index; 4133 SDValue Scale; 4134 const Value *BasePtr = Ptr; 4135 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4136 bool ConstantMemory = false; 4137 if (UniformBase && AA && 4138 AA->pointsToConstantMemory( 4139 MemoryLocation(BasePtr, 4140 LocationSize::precise( 4141 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4142 AAInfo))) { 4143 // Do not serialize (non-volatile) loads of constant memory with anything. 4144 Root = DAG.getEntryNode(); 4145 ConstantMemory = true; 4146 } 4147 4148 MachineMemOperand *MMO = 4149 DAG.getMachineFunction(). 4150 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4151 MachineMemOperand::MOLoad, VT.getStoreSize(), 4152 Alignment, AAInfo, Ranges); 4153 4154 if (!UniformBase) { 4155 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4156 Index = getValue(Ptr); 4157 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4158 } 4159 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4160 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4161 Ops, MMO); 4162 4163 SDValue OutChain = Gather.getValue(1); 4164 if (!ConstantMemory) 4165 PendingLoads.push_back(OutChain); 4166 setValue(&I, Gather); 4167 } 4168 4169 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4170 SDLoc dl = getCurSDLoc(); 4171 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 4172 AtomicOrdering FailureOrder = I.getFailureOrdering(); 4173 SyncScope::ID SSID = I.getSyncScopeID(); 4174 4175 SDValue InChain = getRoot(); 4176 4177 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4178 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4179 SDValue L = DAG.getAtomicCmpSwap( 4180 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 4181 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 4182 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 4183 /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID); 4184 4185 SDValue OutChain = L.getValue(2); 4186 4187 setValue(&I, L); 4188 DAG.setRoot(OutChain); 4189 } 4190 4191 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4192 SDLoc dl = getCurSDLoc(); 4193 ISD::NodeType NT; 4194 switch (I.getOperation()) { 4195 default: llvm_unreachable("Unknown atomicrmw operation"); 4196 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4197 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4198 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4199 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4200 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4201 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4202 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4203 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4204 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4205 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4206 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4207 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4208 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4209 } 4210 AtomicOrdering Order = I.getOrdering(); 4211 SyncScope::ID SSID = I.getSyncScopeID(); 4212 4213 SDValue InChain = getRoot(); 4214 4215 SDValue L = 4216 DAG.getAtomic(NT, dl, 4217 getValue(I.getValOperand()).getSimpleValueType(), 4218 InChain, 4219 getValue(I.getPointerOperand()), 4220 getValue(I.getValOperand()), 4221 I.getPointerOperand(), 4222 /* Alignment=*/ 0, Order, SSID); 4223 4224 SDValue OutChain = L.getValue(1); 4225 4226 setValue(&I, L); 4227 DAG.setRoot(OutChain); 4228 } 4229 4230 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4231 SDLoc dl = getCurSDLoc(); 4232 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4233 SDValue Ops[3]; 4234 Ops[0] = getRoot(); 4235 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4236 TLI.getFenceOperandTy(DAG.getDataLayout())); 4237 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4238 TLI.getFenceOperandTy(DAG.getDataLayout())); 4239 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4240 } 4241 4242 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4243 SDLoc dl = getCurSDLoc(); 4244 AtomicOrdering Order = I.getOrdering(); 4245 SyncScope::ID SSID = I.getSyncScopeID(); 4246 4247 SDValue InChain = getRoot(); 4248 4249 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4250 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4251 4252 if (!TLI.supportsUnalignedAtomics() && 4253 I.getAlignment() < VT.getStoreSize()) 4254 report_fatal_error("Cannot generate unaligned atomic load"); 4255 4256 MachineMemOperand *MMO = 4257 DAG.getMachineFunction(). 4258 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4259 MachineMemOperand::MOVolatile | 4260 MachineMemOperand::MOLoad, 4261 VT.getStoreSize(), 4262 I.getAlignment() ? I.getAlignment() : 4263 DAG.getEVTAlignment(VT), 4264 AAMDNodes(), nullptr, SSID, Order); 4265 4266 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4267 SDValue L = 4268 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4269 getValue(I.getPointerOperand()), MMO); 4270 4271 SDValue OutChain = L.getValue(1); 4272 4273 setValue(&I, L); 4274 DAG.setRoot(OutChain); 4275 } 4276 4277 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4278 SDLoc dl = getCurSDLoc(); 4279 4280 AtomicOrdering Order = I.getOrdering(); 4281 SyncScope::ID SSID = I.getSyncScopeID(); 4282 4283 SDValue InChain = getRoot(); 4284 4285 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4286 EVT VT = 4287 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4288 4289 if (I.getAlignment() < VT.getStoreSize()) 4290 report_fatal_error("Cannot generate unaligned atomic store"); 4291 4292 SDValue OutChain = 4293 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4294 InChain, 4295 getValue(I.getPointerOperand()), 4296 getValue(I.getValueOperand()), 4297 I.getPointerOperand(), I.getAlignment(), 4298 Order, SSID); 4299 4300 DAG.setRoot(OutChain); 4301 } 4302 4303 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4304 /// node. 4305 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4306 unsigned Intrinsic) { 4307 // Ignore the callsite's attributes. A specific call site may be marked with 4308 // readnone, but the lowering code will expect the chain based on the 4309 // definition. 4310 const Function *F = I.getCalledFunction(); 4311 bool HasChain = !F->doesNotAccessMemory(); 4312 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4313 4314 // Build the operand list. 4315 SmallVector<SDValue, 8> Ops; 4316 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4317 if (OnlyLoad) { 4318 // We don't need to serialize loads against other loads. 4319 Ops.push_back(DAG.getRoot()); 4320 } else { 4321 Ops.push_back(getRoot()); 4322 } 4323 } 4324 4325 // Info is set by getTgtMemInstrinsic 4326 TargetLowering::IntrinsicInfo Info; 4327 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4328 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4329 DAG.getMachineFunction(), 4330 Intrinsic); 4331 4332 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4333 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4334 Info.opc == ISD::INTRINSIC_W_CHAIN) 4335 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4336 TLI.getPointerTy(DAG.getDataLayout()))); 4337 4338 // Add all operands of the call to the operand list. 4339 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4340 SDValue Op = getValue(I.getArgOperand(i)); 4341 Ops.push_back(Op); 4342 } 4343 4344 SmallVector<EVT, 4> ValueVTs; 4345 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4346 4347 if (HasChain) 4348 ValueVTs.push_back(MVT::Other); 4349 4350 SDVTList VTs = DAG.getVTList(ValueVTs); 4351 4352 // Create the node. 4353 SDValue Result; 4354 if (IsTgtIntrinsic) { 4355 // This is target intrinsic that touches memory 4356 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4357 Ops, Info.memVT, 4358 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4359 Info.flags, Info.size); 4360 } else if (!HasChain) { 4361 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4362 } else if (!I.getType()->isVoidTy()) { 4363 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4364 } else { 4365 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4366 } 4367 4368 if (HasChain) { 4369 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4370 if (OnlyLoad) 4371 PendingLoads.push_back(Chain); 4372 else 4373 DAG.setRoot(Chain); 4374 } 4375 4376 if (!I.getType()->isVoidTy()) { 4377 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4378 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4379 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4380 } else 4381 Result = lowerRangeToAssertZExt(DAG, I, Result); 4382 4383 setValue(&I, Result); 4384 } 4385 } 4386 4387 /// GetSignificand - Get the significand and build it into a floating-point 4388 /// number with exponent of 1: 4389 /// 4390 /// Op = (Op & 0x007fffff) | 0x3f800000; 4391 /// 4392 /// where Op is the hexadecimal representation of floating point value. 4393 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4394 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4395 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4396 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4397 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4398 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4399 } 4400 4401 /// GetExponent - Get the exponent: 4402 /// 4403 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4404 /// 4405 /// where Op is the hexadecimal representation of floating point value. 4406 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4407 const TargetLowering &TLI, const SDLoc &dl) { 4408 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4409 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4410 SDValue t1 = DAG.getNode( 4411 ISD::SRL, dl, MVT::i32, t0, 4412 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4413 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4414 DAG.getConstant(127, dl, MVT::i32)); 4415 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4416 } 4417 4418 /// getF32Constant - Get 32-bit floating point constant. 4419 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4420 const SDLoc &dl) { 4421 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4422 MVT::f32); 4423 } 4424 4425 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4426 SelectionDAG &DAG) { 4427 // TODO: What fast-math-flags should be set on the floating-point nodes? 4428 4429 // IntegerPartOfX = ((int32_t)(t0); 4430 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4431 4432 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4433 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4434 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4435 4436 // IntegerPartOfX <<= 23; 4437 IntegerPartOfX = DAG.getNode( 4438 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4439 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4440 DAG.getDataLayout()))); 4441 4442 SDValue TwoToFractionalPartOfX; 4443 if (LimitFloatPrecision <= 6) { 4444 // For floating-point precision of 6: 4445 // 4446 // TwoToFractionalPartOfX = 4447 // 0.997535578f + 4448 // (0.735607626f + 0.252464424f * x) * x; 4449 // 4450 // error 0.0144103317, which is 6 bits 4451 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4452 getF32Constant(DAG, 0x3e814304, dl)); 4453 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4454 getF32Constant(DAG, 0x3f3c50c8, dl)); 4455 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4456 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4457 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4458 } else if (LimitFloatPrecision <= 12) { 4459 // For floating-point precision of 12: 4460 // 4461 // TwoToFractionalPartOfX = 4462 // 0.999892986f + 4463 // (0.696457318f + 4464 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4465 // 4466 // error 0.000107046256, which is 13 to 14 bits 4467 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4468 getF32Constant(DAG, 0x3da235e3, dl)); 4469 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4470 getF32Constant(DAG, 0x3e65b8f3, dl)); 4471 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4472 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4473 getF32Constant(DAG, 0x3f324b07, dl)); 4474 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4475 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4476 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4477 } else { // LimitFloatPrecision <= 18 4478 // For floating-point precision of 18: 4479 // 4480 // TwoToFractionalPartOfX = 4481 // 0.999999982f + 4482 // (0.693148872f + 4483 // (0.240227044f + 4484 // (0.554906021e-1f + 4485 // (0.961591928e-2f + 4486 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4487 // error 2.47208000*10^(-7), which is better than 18 bits 4488 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4489 getF32Constant(DAG, 0x3924b03e, dl)); 4490 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4491 getF32Constant(DAG, 0x3ab24b87, dl)); 4492 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4493 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4494 getF32Constant(DAG, 0x3c1d8c17, dl)); 4495 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4496 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4497 getF32Constant(DAG, 0x3d634a1d, dl)); 4498 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4499 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4500 getF32Constant(DAG, 0x3e75fe14, dl)); 4501 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4502 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4503 getF32Constant(DAG, 0x3f317234, dl)); 4504 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4505 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4506 getF32Constant(DAG, 0x3f800000, dl)); 4507 } 4508 4509 // Add the exponent into the result in integer domain. 4510 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4511 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4512 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4513 } 4514 4515 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4516 /// limited-precision mode. 4517 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4518 const TargetLowering &TLI) { 4519 if (Op.getValueType() == MVT::f32 && 4520 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4521 4522 // Put the exponent in the right bit position for later addition to the 4523 // final result: 4524 // 4525 // #define LOG2OFe 1.4426950f 4526 // t0 = Op * LOG2OFe 4527 4528 // TODO: What fast-math-flags should be set here? 4529 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4530 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4531 return getLimitedPrecisionExp2(t0, dl, DAG); 4532 } 4533 4534 // No special expansion. 4535 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4536 } 4537 4538 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4539 /// limited-precision mode. 4540 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4541 const TargetLowering &TLI) { 4542 // TODO: What fast-math-flags should be set on the floating-point nodes? 4543 4544 if (Op.getValueType() == MVT::f32 && 4545 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4546 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4547 4548 // Scale the exponent by log(2) [0.69314718f]. 4549 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4550 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4551 getF32Constant(DAG, 0x3f317218, dl)); 4552 4553 // Get the significand and build it into a floating-point number with 4554 // exponent of 1. 4555 SDValue X = GetSignificand(DAG, Op1, dl); 4556 4557 SDValue LogOfMantissa; 4558 if (LimitFloatPrecision <= 6) { 4559 // For floating-point precision of 6: 4560 // 4561 // LogofMantissa = 4562 // -1.1609546f + 4563 // (1.4034025f - 0.23903021f * x) * x; 4564 // 4565 // error 0.0034276066, which is better than 8 bits 4566 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4567 getF32Constant(DAG, 0xbe74c456, dl)); 4568 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4569 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4570 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4571 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4572 getF32Constant(DAG, 0x3f949a29, dl)); 4573 } else if (LimitFloatPrecision <= 12) { 4574 // For floating-point precision of 12: 4575 // 4576 // LogOfMantissa = 4577 // -1.7417939f + 4578 // (2.8212026f + 4579 // (-1.4699568f + 4580 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4581 // 4582 // error 0.000061011436, which is 14 bits 4583 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4584 getF32Constant(DAG, 0xbd67b6d6, dl)); 4585 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4586 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4587 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4588 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4589 getF32Constant(DAG, 0x3fbc278b, dl)); 4590 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4591 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4592 getF32Constant(DAG, 0x40348e95, dl)); 4593 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4594 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4595 getF32Constant(DAG, 0x3fdef31a, dl)); 4596 } else { // LimitFloatPrecision <= 18 4597 // For floating-point precision of 18: 4598 // 4599 // LogOfMantissa = 4600 // -2.1072184f + 4601 // (4.2372794f + 4602 // (-3.7029485f + 4603 // (2.2781945f + 4604 // (-0.87823314f + 4605 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4606 // 4607 // error 0.0000023660568, which is better than 18 bits 4608 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4609 getF32Constant(DAG, 0xbc91e5ac, dl)); 4610 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4611 getF32Constant(DAG, 0x3e4350aa, dl)); 4612 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4613 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4614 getF32Constant(DAG, 0x3f60d3e3, dl)); 4615 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4616 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4617 getF32Constant(DAG, 0x4011cdf0, dl)); 4618 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4619 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4620 getF32Constant(DAG, 0x406cfd1c, dl)); 4621 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4622 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4623 getF32Constant(DAG, 0x408797cb, dl)); 4624 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4625 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4626 getF32Constant(DAG, 0x4006dcab, dl)); 4627 } 4628 4629 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4630 } 4631 4632 // No special expansion. 4633 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4634 } 4635 4636 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4637 /// limited-precision mode. 4638 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4639 const TargetLowering &TLI) { 4640 // TODO: What fast-math-flags should be set on the floating-point nodes? 4641 4642 if (Op.getValueType() == MVT::f32 && 4643 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4644 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4645 4646 // Get the exponent. 4647 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4648 4649 // Get the significand and build it into a floating-point number with 4650 // exponent of 1. 4651 SDValue X = GetSignificand(DAG, Op1, dl); 4652 4653 // Different possible minimax approximations of significand in 4654 // floating-point for various degrees of accuracy over [1,2]. 4655 SDValue Log2ofMantissa; 4656 if (LimitFloatPrecision <= 6) { 4657 // For floating-point precision of 6: 4658 // 4659 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4660 // 4661 // error 0.0049451742, which is more than 7 bits 4662 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4663 getF32Constant(DAG, 0xbeb08fe0, dl)); 4664 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4665 getF32Constant(DAG, 0x40019463, dl)); 4666 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4667 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4668 getF32Constant(DAG, 0x3fd6633d, dl)); 4669 } else if (LimitFloatPrecision <= 12) { 4670 // For floating-point precision of 12: 4671 // 4672 // Log2ofMantissa = 4673 // -2.51285454f + 4674 // (4.07009056f + 4675 // (-2.12067489f + 4676 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4677 // 4678 // error 0.0000876136000, which is better than 13 bits 4679 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4680 getF32Constant(DAG, 0xbda7262e, dl)); 4681 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4682 getF32Constant(DAG, 0x3f25280b, dl)); 4683 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4684 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4685 getF32Constant(DAG, 0x4007b923, dl)); 4686 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4687 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4688 getF32Constant(DAG, 0x40823e2f, dl)); 4689 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4690 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4691 getF32Constant(DAG, 0x4020d29c, dl)); 4692 } else { // LimitFloatPrecision <= 18 4693 // For floating-point precision of 18: 4694 // 4695 // Log2ofMantissa = 4696 // -3.0400495f + 4697 // (6.1129976f + 4698 // (-5.3420409f + 4699 // (3.2865683f + 4700 // (-1.2669343f + 4701 // (0.27515199f - 4702 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4703 // 4704 // error 0.0000018516, which is better than 18 bits 4705 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4706 getF32Constant(DAG, 0xbcd2769e, dl)); 4707 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4708 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4709 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4710 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4711 getF32Constant(DAG, 0x3fa22ae7, dl)); 4712 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4713 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4714 getF32Constant(DAG, 0x40525723, dl)); 4715 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4716 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4717 getF32Constant(DAG, 0x40aaf200, dl)); 4718 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4719 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4720 getF32Constant(DAG, 0x40c39dad, dl)); 4721 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4722 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4723 getF32Constant(DAG, 0x4042902c, dl)); 4724 } 4725 4726 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4727 } 4728 4729 // No special expansion. 4730 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4731 } 4732 4733 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4734 /// limited-precision mode. 4735 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4736 const TargetLowering &TLI) { 4737 // TODO: What fast-math-flags should be set on the floating-point nodes? 4738 4739 if (Op.getValueType() == MVT::f32 && 4740 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4741 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4742 4743 // Scale the exponent by log10(2) [0.30102999f]. 4744 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4745 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4746 getF32Constant(DAG, 0x3e9a209a, dl)); 4747 4748 // Get the significand and build it into a floating-point number with 4749 // exponent of 1. 4750 SDValue X = GetSignificand(DAG, Op1, dl); 4751 4752 SDValue Log10ofMantissa; 4753 if (LimitFloatPrecision <= 6) { 4754 // For floating-point precision of 6: 4755 // 4756 // Log10ofMantissa = 4757 // -0.50419619f + 4758 // (0.60948995f - 0.10380950f * x) * x; 4759 // 4760 // error 0.0014886165, which is 6 bits 4761 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4762 getF32Constant(DAG, 0xbdd49a13, dl)); 4763 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4764 getF32Constant(DAG, 0x3f1c0789, dl)); 4765 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4766 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4767 getF32Constant(DAG, 0x3f011300, dl)); 4768 } else if (LimitFloatPrecision <= 12) { 4769 // For floating-point precision of 12: 4770 // 4771 // Log10ofMantissa = 4772 // -0.64831180f + 4773 // (0.91751397f + 4774 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4775 // 4776 // error 0.00019228036, which is better than 12 bits 4777 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4778 getF32Constant(DAG, 0x3d431f31, dl)); 4779 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4780 getF32Constant(DAG, 0x3ea21fb2, dl)); 4781 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4782 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4783 getF32Constant(DAG, 0x3f6ae232, dl)); 4784 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4785 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4786 getF32Constant(DAG, 0x3f25f7c3, dl)); 4787 } else { // LimitFloatPrecision <= 18 4788 // For floating-point precision of 18: 4789 // 4790 // Log10ofMantissa = 4791 // -0.84299375f + 4792 // (1.5327582f + 4793 // (-1.0688956f + 4794 // (0.49102474f + 4795 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4796 // 4797 // error 0.0000037995730, which is better than 18 bits 4798 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4799 getF32Constant(DAG, 0x3c5d51ce, dl)); 4800 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4801 getF32Constant(DAG, 0x3e00685a, dl)); 4802 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4803 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4804 getF32Constant(DAG, 0x3efb6798, dl)); 4805 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4806 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4807 getF32Constant(DAG, 0x3f88d192, dl)); 4808 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4809 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4810 getF32Constant(DAG, 0x3fc4316c, dl)); 4811 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4812 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4813 getF32Constant(DAG, 0x3f57ce70, dl)); 4814 } 4815 4816 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4817 } 4818 4819 // No special expansion. 4820 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4821 } 4822 4823 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4824 /// limited-precision mode. 4825 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4826 const TargetLowering &TLI) { 4827 if (Op.getValueType() == MVT::f32 && 4828 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4829 return getLimitedPrecisionExp2(Op, dl, DAG); 4830 4831 // No special expansion. 4832 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4833 } 4834 4835 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4836 /// limited-precision mode with x == 10.0f. 4837 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4838 SelectionDAG &DAG, const TargetLowering &TLI) { 4839 bool IsExp10 = false; 4840 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4841 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4842 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4843 APFloat Ten(10.0f); 4844 IsExp10 = LHSC->isExactlyValue(Ten); 4845 } 4846 } 4847 4848 // TODO: What fast-math-flags should be set on the FMUL node? 4849 if (IsExp10) { 4850 // Put the exponent in the right bit position for later addition to the 4851 // final result: 4852 // 4853 // #define LOG2OF10 3.3219281f 4854 // t0 = Op * LOG2OF10; 4855 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4856 getF32Constant(DAG, 0x40549a78, dl)); 4857 return getLimitedPrecisionExp2(t0, dl, DAG); 4858 } 4859 4860 // No special expansion. 4861 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4862 } 4863 4864 /// ExpandPowI - Expand a llvm.powi intrinsic. 4865 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4866 SelectionDAG &DAG) { 4867 // If RHS is a constant, we can expand this out to a multiplication tree, 4868 // otherwise we end up lowering to a call to __powidf2 (for example). When 4869 // optimizing for size, we only want to do this if the expansion would produce 4870 // a small number of multiplies, otherwise we do the full expansion. 4871 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4872 // Get the exponent as a positive value. 4873 unsigned Val = RHSC->getSExtValue(); 4874 if ((int)Val < 0) Val = -Val; 4875 4876 // powi(x, 0) -> 1.0 4877 if (Val == 0) 4878 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4879 4880 const Function &F = DAG.getMachineFunction().getFunction(); 4881 if (!F.optForSize() || 4882 // If optimizing for size, don't insert too many multiplies. 4883 // This inserts up to 5 multiplies. 4884 countPopulation(Val) + Log2_32(Val) < 7) { 4885 // We use the simple binary decomposition method to generate the multiply 4886 // sequence. There are more optimal ways to do this (for example, 4887 // powi(x,15) generates one more multiply than it should), but this has 4888 // the benefit of being both really simple and much better than a libcall. 4889 SDValue Res; // Logically starts equal to 1.0 4890 SDValue CurSquare = LHS; 4891 // TODO: Intrinsics should have fast-math-flags that propagate to these 4892 // nodes. 4893 while (Val) { 4894 if (Val & 1) { 4895 if (Res.getNode()) 4896 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4897 else 4898 Res = CurSquare; // 1.0*CurSquare. 4899 } 4900 4901 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4902 CurSquare, CurSquare); 4903 Val >>= 1; 4904 } 4905 4906 // If the original was negative, invert the result, producing 1/(x*x*x). 4907 if (RHSC->getSExtValue() < 0) 4908 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4909 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4910 return Res; 4911 } 4912 } 4913 4914 // Otherwise, expand to a libcall. 4915 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4916 } 4917 4918 // getUnderlyingArgReg - Find underlying register used for a truncated or 4919 // bitcasted argument. 4920 static unsigned getUnderlyingArgReg(const SDValue &N) { 4921 switch (N.getOpcode()) { 4922 case ISD::CopyFromReg: 4923 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4924 case ISD::BITCAST: 4925 case ISD::AssertZext: 4926 case ISD::AssertSext: 4927 case ISD::TRUNCATE: 4928 return getUnderlyingArgReg(N.getOperand(0)); 4929 default: 4930 return 0; 4931 } 4932 } 4933 4934 /// If the DbgValueInst is a dbg_value of a function argument, create the 4935 /// corresponding DBG_VALUE machine instruction for it now. At the end of 4936 /// instruction selection, they will be inserted to the entry BB. 4937 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4938 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4939 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 4940 const Argument *Arg = dyn_cast<Argument>(V); 4941 if (!Arg) 4942 return false; 4943 4944 MachineFunction &MF = DAG.getMachineFunction(); 4945 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4946 4947 bool IsIndirect = false; 4948 Optional<MachineOperand> Op; 4949 // Some arguments' frame index is recorded during argument lowering. 4950 int FI = FuncInfo.getArgumentFrameIndex(Arg); 4951 if (FI != std::numeric_limits<int>::max()) 4952 Op = MachineOperand::CreateFI(FI); 4953 4954 if (!Op && N.getNode()) { 4955 unsigned Reg = getUnderlyingArgReg(N); 4956 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4957 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4958 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4959 if (PR) 4960 Reg = PR; 4961 } 4962 if (Reg) { 4963 Op = MachineOperand::CreateReg(Reg, false); 4964 IsIndirect = IsDbgDeclare; 4965 } 4966 } 4967 4968 if (!Op && N.getNode()) 4969 // Check if frame index is available. 4970 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4971 if (FrameIndexSDNode *FINode = 4972 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4973 Op = MachineOperand::CreateFI(FINode->getIndex()); 4974 4975 if (!Op) { 4976 // Check if ValueMap has reg number. 4977 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4978 if (VMI != FuncInfo.ValueMap.end()) { 4979 const auto &TLI = DAG.getTargetLoweringInfo(); 4980 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 4981 V->getType(), getABIRegCopyCC(V)); 4982 if (RFV.occupiesMultipleRegs()) { 4983 unsigned Offset = 0; 4984 for (auto RegAndSize : RFV.getRegsAndSizes()) { 4985 Op = MachineOperand::CreateReg(RegAndSize.first, false); 4986 auto FragmentExpr = DIExpression::createFragmentExpression( 4987 Expr, Offset, RegAndSize.second); 4988 if (!FragmentExpr) 4989 continue; 4990 FuncInfo.ArgDbgValues.push_back( 4991 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 4992 Op->getReg(), Variable, *FragmentExpr)); 4993 Offset += RegAndSize.second; 4994 } 4995 return true; 4996 } 4997 Op = MachineOperand::CreateReg(VMI->second, false); 4998 IsIndirect = IsDbgDeclare; 4999 } 5000 } 5001 5002 if (!Op) 5003 return false; 5004 5005 assert(Variable->isValidLocationForIntrinsic(DL) && 5006 "Expected inlined-at fields to agree"); 5007 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5008 FuncInfo.ArgDbgValues.push_back( 5009 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5010 *Op, Variable, Expr)); 5011 5012 return true; 5013 } 5014 5015 /// Return the appropriate SDDbgValue based on N. 5016 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5017 DILocalVariable *Variable, 5018 DIExpression *Expr, 5019 const DebugLoc &dl, 5020 unsigned DbgSDNodeOrder) { 5021 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5022 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5023 // stack slot locations. 5024 // 5025 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5026 // debug values here after optimization: 5027 // 5028 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5029 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5030 // 5031 // Both describe the direct values of their associated variables. 5032 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5033 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5034 } 5035 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5036 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5037 } 5038 5039 // VisualStudio defines setjmp as _setjmp 5040 #if defined(_MSC_VER) && defined(setjmp) && \ 5041 !defined(setjmp_undefined_for_msvc) 5042 # pragma push_macro("setjmp") 5043 # undef setjmp 5044 # define setjmp_undefined_for_msvc 5045 #endif 5046 5047 /// Lower the call to the specified intrinsic function. If we want to emit this 5048 /// as a call to a named external function, return the name. Otherwise, lower it 5049 /// and return null. 5050 const char * 5051 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5052 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5053 SDLoc sdl = getCurSDLoc(); 5054 DebugLoc dl = getCurDebugLoc(); 5055 SDValue Res; 5056 5057 switch (Intrinsic) { 5058 default: 5059 // By default, turn this into a target intrinsic node. 5060 visitTargetIntrinsic(I, Intrinsic); 5061 return nullptr; 5062 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5063 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5064 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5065 case Intrinsic::returnaddress: 5066 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5067 TLI.getPointerTy(DAG.getDataLayout()), 5068 getValue(I.getArgOperand(0)))); 5069 return nullptr; 5070 case Intrinsic::addressofreturnaddress: 5071 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5072 TLI.getPointerTy(DAG.getDataLayout()))); 5073 return nullptr; 5074 case Intrinsic::sponentry: 5075 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5076 TLI.getPointerTy(DAG.getDataLayout()))); 5077 return nullptr; 5078 case Intrinsic::frameaddress: 5079 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5080 TLI.getPointerTy(DAG.getDataLayout()), 5081 getValue(I.getArgOperand(0)))); 5082 return nullptr; 5083 case Intrinsic::read_register: { 5084 Value *Reg = I.getArgOperand(0); 5085 SDValue Chain = getRoot(); 5086 SDValue RegName = 5087 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5088 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5089 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5090 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5091 setValue(&I, Res); 5092 DAG.setRoot(Res.getValue(1)); 5093 return nullptr; 5094 } 5095 case Intrinsic::write_register: { 5096 Value *Reg = I.getArgOperand(0); 5097 Value *RegValue = I.getArgOperand(1); 5098 SDValue Chain = getRoot(); 5099 SDValue RegName = 5100 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5101 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5102 RegName, getValue(RegValue))); 5103 return nullptr; 5104 } 5105 case Intrinsic::setjmp: 5106 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5107 case Intrinsic::longjmp: 5108 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5109 case Intrinsic::memcpy: { 5110 const auto &MCI = cast<MemCpyInst>(I); 5111 SDValue Op1 = getValue(I.getArgOperand(0)); 5112 SDValue Op2 = getValue(I.getArgOperand(1)); 5113 SDValue Op3 = getValue(I.getArgOperand(2)); 5114 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5115 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5116 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5117 unsigned Align = MinAlign(DstAlign, SrcAlign); 5118 bool isVol = MCI.isVolatile(); 5119 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5120 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5121 // node. 5122 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5123 false, isTC, 5124 MachinePointerInfo(I.getArgOperand(0)), 5125 MachinePointerInfo(I.getArgOperand(1))); 5126 updateDAGForMaybeTailCall(MC); 5127 return nullptr; 5128 } 5129 case Intrinsic::memset: { 5130 const auto &MSI = cast<MemSetInst>(I); 5131 SDValue Op1 = getValue(I.getArgOperand(0)); 5132 SDValue Op2 = getValue(I.getArgOperand(1)); 5133 SDValue Op3 = getValue(I.getArgOperand(2)); 5134 // @llvm.memset defines 0 and 1 to both mean no alignment. 5135 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5136 bool isVol = MSI.isVolatile(); 5137 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5138 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5139 isTC, MachinePointerInfo(I.getArgOperand(0))); 5140 updateDAGForMaybeTailCall(MS); 5141 return nullptr; 5142 } 5143 case Intrinsic::memmove: { 5144 const auto &MMI = cast<MemMoveInst>(I); 5145 SDValue Op1 = getValue(I.getArgOperand(0)); 5146 SDValue Op2 = getValue(I.getArgOperand(1)); 5147 SDValue Op3 = getValue(I.getArgOperand(2)); 5148 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5149 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5150 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5151 unsigned Align = MinAlign(DstAlign, SrcAlign); 5152 bool isVol = MMI.isVolatile(); 5153 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5154 // FIXME: Support passing different dest/src alignments to the memmove DAG 5155 // node. 5156 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5157 isTC, MachinePointerInfo(I.getArgOperand(0)), 5158 MachinePointerInfo(I.getArgOperand(1))); 5159 updateDAGForMaybeTailCall(MM); 5160 return nullptr; 5161 } 5162 case Intrinsic::memcpy_element_unordered_atomic: { 5163 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5164 SDValue Dst = getValue(MI.getRawDest()); 5165 SDValue Src = getValue(MI.getRawSource()); 5166 SDValue Length = getValue(MI.getLength()); 5167 5168 unsigned DstAlign = MI.getDestAlignment(); 5169 unsigned SrcAlign = MI.getSourceAlignment(); 5170 Type *LengthTy = MI.getLength()->getType(); 5171 unsigned ElemSz = MI.getElementSizeInBytes(); 5172 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5173 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5174 SrcAlign, Length, LengthTy, ElemSz, isTC, 5175 MachinePointerInfo(MI.getRawDest()), 5176 MachinePointerInfo(MI.getRawSource())); 5177 updateDAGForMaybeTailCall(MC); 5178 return nullptr; 5179 } 5180 case Intrinsic::memmove_element_unordered_atomic: { 5181 auto &MI = cast<AtomicMemMoveInst>(I); 5182 SDValue Dst = getValue(MI.getRawDest()); 5183 SDValue Src = getValue(MI.getRawSource()); 5184 SDValue Length = getValue(MI.getLength()); 5185 5186 unsigned DstAlign = MI.getDestAlignment(); 5187 unsigned SrcAlign = MI.getSourceAlignment(); 5188 Type *LengthTy = MI.getLength()->getType(); 5189 unsigned ElemSz = MI.getElementSizeInBytes(); 5190 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5191 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5192 SrcAlign, Length, LengthTy, ElemSz, isTC, 5193 MachinePointerInfo(MI.getRawDest()), 5194 MachinePointerInfo(MI.getRawSource())); 5195 updateDAGForMaybeTailCall(MC); 5196 return nullptr; 5197 } 5198 case Intrinsic::memset_element_unordered_atomic: { 5199 auto &MI = cast<AtomicMemSetInst>(I); 5200 SDValue Dst = getValue(MI.getRawDest()); 5201 SDValue Val = getValue(MI.getValue()); 5202 SDValue Length = getValue(MI.getLength()); 5203 5204 unsigned DstAlign = MI.getDestAlignment(); 5205 Type *LengthTy = MI.getLength()->getType(); 5206 unsigned ElemSz = MI.getElementSizeInBytes(); 5207 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5208 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5209 LengthTy, ElemSz, isTC, 5210 MachinePointerInfo(MI.getRawDest())); 5211 updateDAGForMaybeTailCall(MC); 5212 return nullptr; 5213 } 5214 case Intrinsic::dbg_addr: 5215 case Intrinsic::dbg_declare: { 5216 const auto &DI = cast<DbgVariableIntrinsic>(I); 5217 DILocalVariable *Variable = DI.getVariable(); 5218 DIExpression *Expression = DI.getExpression(); 5219 dropDanglingDebugInfo(Variable, Expression); 5220 assert(Variable && "Missing variable"); 5221 5222 // Check if address has undef value. 5223 const Value *Address = DI.getVariableLocation(); 5224 if (!Address || isa<UndefValue>(Address) || 5225 (Address->use_empty() && !isa<Argument>(Address))) { 5226 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5227 return nullptr; 5228 } 5229 5230 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5231 5232 // Check if this variable can be described by a frame index, typically 5233 // either as a static alloca or a byval parameter. 5234 int FI = std::numeric_limits<int>::max(); 5235 if (const auto *AI = 5236 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5237 if (AI->isStaticAlloca()) { 5238 auto I = FuncInfo.StaticAllocaMap.find(AI); 5239 if (I != FuncInfo.StaticAllocaMap.end()) 5240 FI = I->second; 5241 } 5242 } else if (const auto *Arg = dyn_cast<Argument>( 5243 Address->stripInBoundsConstantOffsets())) { 5244 FI = FuncInfo.getArgumentFrameIndex(Arg); 5245 } 5246 5247 // llvm.dbg.addr is control dependent and always generates indirect 5248 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5249 // the MachineFunction variable table. 5250 if (FI != std::numeric_limits<int>::max()) { 5251 if (Intrinsic == Intrinsic::dbg_addr) { 5252 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5253 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5254 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5255 } 5256 return nullptr; 5257 } 5258 5259 SDValue &N = NodeMap[Address]; 5260 if (!N.getNode() && isa<Argument>(Address)) 5261 // Check unused arguments map. 5262 N = UnusedArgNodeMap[Address]; 5263 SDDbgValue *SDV; 5264 if (N.getNode()) { 5265 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5266 Address = BCI->getOperand(0); 5267 // Parameters are handled specially. 5268 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5269 if (isParameter && FINode) { 5270 // Byval parameter. We have a frame index at this point. 5271 SDV = 5272 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5273 /*IsIndirect*/ true, dl, SDNodeOrder); 5274 } else if (isa<Argument>(Address)) { 5275 // Address is an argument, so try to emit its dbg value using 5276 // virtual register info from the FuncInfo.ValueMap. 5277 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5278 return nullptr; 5279 } else { 5280 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5281 true, dl, SDNodeOrder); 5282 } 5283 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5284 } else { 5285 // If Address is an argument then try to emit its dbg value using 5286 // virtual register info from the FuncInfo.ValueMap. 5287 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5288 N)) { 5289 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5290 } 5291 } 5292 return nullptr; 5293 } 5294 case Intrinsic::dbg_label: { 5295 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5296 DILabel *Label = DI.getLabel(); 5297 assert(Label && "Missing label"); 5298 5299 SDDbgLabel *SDV; 5300 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5301 DAG.AddDbgLabel(SDV); 5302 return nullptr; 5303 } 5304 case Intrinsic::dbg_value: { 5305 const DbgValueInst &DI = cast<DbgValueInst>(I); 5306 assert(DI.getVariable() && "Missing variable"); 5307 5308 DILocalVariable *Variable = DI.getVariable(); 5309 DIExpression *Expression = DI.getExpression(); 5310 dropDanglingDebugInfo(Variable, Expression); 5311 const Value *V = DI.getValue(); 5312 if (!V) 5313 return nullptr; 5314 5315 SDDbgValue *SDV; 5316 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 5317 isa<ConstantPointerNull>(V)) { 5318 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5319 DAG.AddDbgValue(SDV, nullptr, false); 5320 return nullptr; 5321 } 5322 5323 // Do not use getValue() in here; we don't want to generate code at 5324 // this point if it hasn't been done yet. 5325 SDValue N = NodeMap[V]; 5326 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5327 N = UnusedArgNodeMap[V]; 5328 if (N.getNode()) { 5329 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5330 return nullptr; 5331 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5332 DAG.AddDbgValue(SDV, N.getNode(), false); 5333 return nullptr; 5334 } 5335 5336 // The value is not used in this block yet (or it would have an SDNode). 5337 // We still want the value to appear for the user if possible -- if it has 5338 // an associated VReg, we can refer to that instead. 5339 if (!isa<Argument>(V)) { 5340 auto VMI = FuncInfo.ValueMap.find(V); 5341 if (VMI != FuncInfo.ValueMap.end()) { 5342 unsigned Reg = VMI->second; 5343 // If this is a PHI node, it may be split up into several MI PHI nodes 5344 // (in FunctionLoweringInfo::set). 5345 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 5346 V->getType(), None); 5347 if (RFV.occupiesMultipleRegs()) { 5348 unsigned Offset = 0; 5349 unsigned BitsToDescribe = 0; 5350 if (auto VarSize = Variable->getSizeInBits()) 5351 BitsToDescribe = *VarSize; 5352 if (auto Fragment = Expression->getFragmentInfo()) 5353 BitsToDescribe = Fragment->SizeInBits; 5354 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5355 unsigned RegisterSize = RegAndSize.second; 5356 // Bail out if all bits are described already. 5357 if (Offset >= BitsToDescribe) 5358 break; 5359 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 5360 ? BitsToDescribe - Offset 5361 : RegisterSize; 5362 auto FragmentExpr = DIExpression::createFragmentExpression( 5363 Expression, Offset, FragmentSize); 5364 if (!FragmentExpr) 5365 continue; 5366 SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first, 5367 false, dl, SDNodeOrder); 5368 DAG.AddDbgValue(SDV, nullptr, false); 5369 Offset += RegisterSize; 5370 } 5371 } else { 5372 SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl, 5373 SDNodeOrder); 5374 DAG.AddDbgValue(SDV, nullptr, false); 5375 } 5376 return nullptr; 5377 } 5378 } 5379 5380 // TODO: When we get here we will either drop the dbg.value completely, or 5381 // we try to move it forward by letting it dangle for awhile. So we should 5382 // probably add an extra DbgValue to the DAG here, with a reference to 5383 // "noreg", to indicate that we have lost the debug location for the 5384 // variable. 5385 5386 if (!V->use_empty() ) { 5387 // Do not call getValue(V) yet, as we don't want to generate code. 5388 // Remember it for later. 5389 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5390 return nullptr; 5391 } 5392 5393 LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5394 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5395 return nullptr; 5396 } 5397 5398 case Intrinsic::eh_typeid_for: { 5399 // Find the type id for the given typeinfo. 5400 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5401 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5402 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5403 setValue(&I, Res); 5404 return nullptr; 5405 } 5406 5407 case Intrinsic::eh_return_i32: 5408 case Intrinsic::eh_return_i64: 5409 DAG.getMachineFunction().setCallsEHReturn(true); 5410 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5411 MVT::Other, 5412 getControlRoot(), 5413 getValue(I.getArgOperand(0)), 5414 getValue(I.getArgOperand(1)))); 5415 return nullptr; 5416 case Intrinsic::eh_unwind_init: 5417 DAG.getMachineFunction().setCallsUnwindInit(true); 5418 return nullptr; 5419 case Intrinsic::eh_dwarf_cfa: 5420 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5421 TLI.getPointerTy(DAG.getDataLayout()), 5422 getValue(I.getArgOperand(0)))); 5423 return nullptr; 5424 case Intrinsic::eh_sjlj_callsite: { 5425 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5426 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5427 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5428 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5429 5430 MMI.setCurrentCallSite(CI->getZExtValue()); 5431 return nullptr; 5432 } 5433 case Intrinsic::eh_sjlj_functioncontext: { 5434 // Get and store the index of the function context. 5435 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5436 AllocaInst *FnCtx = 5437 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5438 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5439 MFI.setFunctionContextIndex(FI); 5440 return nullptr; 5441 } 5442 case Intrinsic::eh_sjlj_setjmp: { 5443 SDValue Ops[2]; 5444 Ops[0] = getRoot(); 5445 Ops[1] = getValue(I.getArgOperand(0)); 5446 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5447 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5448 setValue(&I, Op.getValue(0)); 5449 DAG.setRoot(Op.getValue(1)); 5450 return nullptr; 5451 } 5452 case Intrinsic::eh_sjlj_longjmp: 5453 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5454 getRoot(), getValue(I.getArgOperand(0)))); 5455 return nullptr; 5456 case Intrinsic::eh_sjlj_setup_dispatch: 5457 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5458 getRoot())); 5459 return nullptr; 5460 case Intrinsic::masked_gather: 5461 visitMaskedGather(I); 5462 return nullptr; 5463 case Intrinsic::masked_load: 5464 visitMaskedLoad(I); 5465 return nullptr; 5466 case Intrinsic::masked_scatter: 5467 visitMaskedScatter(I); 5468 return nullptr; 5469 case Intrinsic::masked_store: 5470 visitMaskedStore(I); 5471 return nullptr; 5472 case Intrinsic::masked_expandload: 5473 visitMaskedLoad(I, true /* IsExpanding */); 5474 return nullptr; 5475 case Intrinsic::masked_compressstore: 5476 visitMaskedStore(I, true /* IsCompressing */); 5477 return nullptr; 5478 case Intrinsic::x86_mmx_pslli_w: 5479 case Intrinsic::x86_mmx_pslli_d: 5480 case Intrinsic::x86_mmx_pslli_q: 5481 case Intrinsic::x86_mmx_psrli_w: 5482 case Intrinsic::x86_mmx_psrli_d: 5483 case Intrinsic::x86_mmx_psrli_q: 5484 case Intrinsic::x86_mmx_psrai_w: 5485 case Intrinsic::x86_mmx_psrai_d: { 5486 SDValue ShAmt = getValue(I.getArgOperand(1)); 5487 if (isa<ConstantSDNode>(ShAmt)) { 5488 visitTargetIntrinsic(I, Intrinsic); 5489 return nullptr; 5490 } 5491 unsigned NewIntrinsic = 0; 5492 EVT ShAmtVT = MVT::v2i32; 5493 switch (Intrinsic) { 5494 case Intrinsic::x86_mmx_pslli_w: 5495 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5496 break; 5497 case Intrinsic::x86_mmx_pslli_d: 5498 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5499 break; 5500 case Intrinsic::x86_mmx_pslli_q: 5501 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5502 break; 5503 case Intrinsic::x86_mmx_psrli_w: 5504 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5505 break; 5506 case Intrinsic::x86_mmx_psrli_d: 5507 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5508 break; 5509 case Intrinsic::x86_mmx_psrli_q: 5510 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5511 break; 5512 case Intrinsic::x86_mmx_psrai_w: 5513 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5514 break; 5515 case Intrinsic::x86_mmx_psrai_d: 5516 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5517 break; 5518 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5519 } 5520 5521 // The vector shift intrinsics with scalars uses 32b shift amounts but 5522 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5523 // to be zero. 5524 // We must do this early because v2i32 is not a legal type. 5525 SDValue ShOps[2]; 5526 ShOps[0] = ShAmt; 5527 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5528 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5529 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5530 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5531 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5532 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5533 getValue(I.getArgOperand(0)), ShAmt); 5534 setValue(&I, Res); 5535 return nullptr; 5536 } 5537 case Intrinsic::powi: 5538 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5539 getValue(I.getArgOperand(1)), DAG)); 5540 return nullptr; 5541 case Intrinsic::log: 5542 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5543 return nullptr; 5544 case Intrinsic::log2: 5545 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5546 return nullptr; 5547 case Intrinsic::log10: 5548 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5549 return nullptr; 5550 case Intrinsic::exp: 5551 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5552 return nullptr; 5553 case Intrinsic::exp2: 5554 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5555 return nullptr; 5556 case Intrinsic::pow: 5557 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5558 getValue(I.getArgOperand(1)), DAG, TLI)); 5559 return nullptr; 5560 case Intrinsic::sqrt: 5561 case Intrinsic::fabs: 5562 case Intrinsic::sin: 5563 case Intrinsic::cos: 5564 case Intrinsic::floor: 5565 case Intrinsic::ceil: 5566 case Intrinsic::trunc: 5567 case Intrinsic::rint: 5568 case Intrinsic::nearbyint: 5569 case Intrinsic::round: 5570 case Intrinsic::canonicalize: { 5571 unsigned Opcode; 5572 switch (Intrinsic) { 5573 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5574 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5575 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5576 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5577 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5578 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5579 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5580 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5581 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5582 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5583 case Intrinsic::round: Opcode = ISD::FROUND; break; 5584 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5585 } 5586 5587 setValue(&I, DAG.getNode(Opcode, sdl, 5588 getValue(I.getArgOperand(0)).getValueType(), 5589 getValue(I.getArgOperand(0)))); 5590 return nullptr; 5591 } 5592 case Intrinsic::minnum: { 5593 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5594 unsigned Opc = 5595 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT) 5596 ? ISD::FMINIMUM 5597 : ISD::FMINNUM; 5598 setValue(&I, DAG.getNode(Opc, sdl, VT, 5599 getValue(I.getArgOperand(0)), 5600 getValue(I.getArgOperand(1)))); 5601 return nullptr; 5602 } 5603 case Intrinsic::maxnum: { 5604 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5605 unsigned Opc = 5606 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT) 5607 ? ISD::FMAXIMUM 5608 : ISD::FMAXNUM; 5609 setValue(&I, DAG.getNode(Opc, sdl, VT, 5610 getValue(I.getArgOperand(0)), 5611 getValue(I.getArgOperand(1)))); 5612 return nullptr; 5613 } 5614 case Intrinsic::minimum: 5615 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 5616 getValue(I.getArgOperand(0)).getValueType(), 5617 getValue(I.getArgOperand(0)), 5618 getValue(I.getArgOperand(1)))); 5619 return nullptr; 5620 case Intrinsic::maximum: 5621 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 5622 getValue(I.getArgOperand(0)).getValueType(), 5623 getValue(I.getArgOperand(0)), 5624 getValue(I.getArgOperand(1)))); 5625 return nullptr; 5626 case Intrinsic::copysign: 5627 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5628 getValue(I.getArgOperand(0)).getValueType(), 5629 getValue(I.getArgOperand(0)), 5630 getValue(I.getArgOperand(1)))); 5631 return nullptr; 5632 case Intrinsic::fma: 5633 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5634 getValue(I.getArgOperand(0)).getValueType(), 5635 getValue(I.getArgOperand(0)), 5636 getValue(I.getArgOperand(1)), 5637 getValue(I.getArgOperand(2)))); 5638 return nullptr; 5639 case Intrinsic::experimental_constrained_fadd: 5640 case Intrinsic::experimental_constrained_fsub: 5641 case Intrinsic::experimental_constrained_fmul: 5642 case Intrinsic::experimental_constrained_fdiv: 5643 case Intrinsic::experimental_constrained_frem: 5644 case Intrinsic::experimental_constrained_fma: 5645 case Intrinsic::experimental_constrained_sqrt: 5646 case Intrinsic::experimental_constrained_pow: 5647 case Intrinsic::experimental_constrained_powi: 5648 case Intrinsic::experimental_constrained_sin: 5649 case Intrinsic::experimental_constrained_cos: 5650 case Intrinsic::experimental_constrained_exp: 5651 case Intrinsic::experimental_constrained_exp2: 5652 case Intrinsic::experimental_constrained_log: 5653 case Intrinsic::experimental_constrained_log10: 5654 case Intrinsic::experimental_constrained_log2: 5655 case Intrinsic::experimental_constrained_rint: 5656 case Intrinsic::experimental_constrained_nearbyint: 5657 case Intrinsic::experimental_constrained_maxnum: 5658 case Intrinsic::experimental_constrained_minnum: 5659 case Intrinsic::experimental_constrained_ceil: 5660 case Intrinsic::experimental_constrained_floor: 5661 case Intrinsic::experimental_constrained_round: 5662 case Intrinsic::experimental_constrained_trunc: 5663 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5664 return nullptr; 5665 case Intrinsic::fmuladd: { 5666 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5667 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5668 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5669 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5670 getValue(I.getArgOperand(0)).getValueType(), 5671 getValue(I.getArgOperand(0)), 5672 getValue(I.getArgOperand(1)), 5673 getValue(I.getArgOperand(2)))); 5674 } else { 5675 // TODO: Intrinsic calls should have fast-math-flags. 5676 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5677 getValue(I.getArgOperand(0)).getValueType(), 5678 getValue(I.getArgOperand(0)), 5679 getValue(I.getArgOperand(1))); 5680 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5681 getValue(I.getArgOperand(0)).getValueType(), 5682 Mul, 5683 getValue(I.getArgOperand(2))); 5684 setValue(&I, Add); 5685 } 5686 return nullptr; 5687 } 5688 case Intrinsic::convert_to_fp16: 5689 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5690 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5691 getValue(I.getArgOperand(0)), 5692 DAG.getTargetConstant(0, sdl, 5693 MVT::i32)))); 5694 return nullptr; 5695 case Intrinsic::convert_from_fp16: 5696 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5697 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5698 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5699 getValue(I.getArgOperand(0))))); 5700 return nullptr; 5701 case Intrinsic::pcmarker: { 5702 SDValue Tmp = getValue(I.getArgOperand(0)); 5703 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5704 return nullptr; 5705 } 5706 case Intrinsic::readcyclecounter: { 5707 SDValue Op = getRoot(); 5708 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5709 DAG.getVTList(MVT::i64, MVT::Other), Op); 5710 setValue(&I, Res); 5711 DAG.setRoot(Res.getValue(1)); 5712 return nullptr; 5713 } 5714 case Intrinsic::bitreverse: 5715 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5716 getValue(I.getArgOperand(0)).getValueType(), 5717 getValue(I.getArgOperand(0)))); 5718 return nullptr; 5719 case Intrinsic::bswap: 5720 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5721 getValue(I.getArgOperand(0)).getValueType(), 5722 getValue(I.getArgOperand(0)))); 5723 return nullptr; 5724 case Intrinsic::cttz: { 5725 SDValue Arg = getValue(I.getArgOperand(0)); 5726 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5727 EVT Ty = Arg.getValueType(); 5728 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5729 sdl, Ty, Arg)); 5730 return nullptr; 5731 } 5732 case Intrinsic::ctlz: { 5733 SDValue Arg = getValue(I.getArgOperand(0)); 5734 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5735 EVT Ty = Arg.getValueType(); 5736 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5737 sdl, Ty, Arg)); 5738 return nullptr; 5739 } 5740 case Intrinsic::ctpop: { 5741 SDValue Arg = getValue(I.getArgOperand(0)); 5742 EVT Ty = Arg.getValueType(); 5743 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5744 return nullptr; 5745 } 5746 case Intrinsic::fshl: 5747 case Intrinsic::fshr: { 5748 bool IsFSHL = Intrinsic == Intrinsic::fshl; 5749 SDValue X = getValue(I.getArgOperand(0)); 5750 SDValue Y = getValue(I.getArgOperand(1)); 5751 SDValue Z = getValue(I.getArgOperand(2)); 5752 EVT VT = X.getValueType(); 5753 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 5754 SDValue Zero = DAG.getConstant(0, sdl, VT); 5755 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 5756 5757 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 5758 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 5759 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 5760 return nullptr; 5761 } 5762 5763 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 5764 // avoid the select that is necessary in the general case to filter out 5765 // the 0-shift possibility that leads to UB. 5766 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 5767 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 5768 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5769 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 5770 return nullptr; 5771 } 5772 5773 // Some targets only rotate one way. Try the opposite direction. 5774 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 5775 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5776 // Negate the shift amount because it is safe to ignore the high bits. 5777 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5778 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 5779 return nullptr; 5780 } 5781 5782 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 5783 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 5784 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5785 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 5786 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 5787 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 5788 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 5789 return nullptr; 5790 } 5791 5792 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 5793 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 5794 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 5795 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 5796 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 5797 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 5798 5799 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 5800 // and that is undefined. We must compare and select to avoid UB. 5801 EVT CCVT = MVT::i1; 5802 if (VT.isVector()) 5803 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 5804 5805 // For fshl, 0-shift returns the 1st arg (X). 5806 // For fshr, 0-shift returns the 2nd arg (Y). 5807 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 5808 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 5809 return nullptr; 5810 } 5811 case Intrinsic::sadd_sat: { 5812 SDValue Op1 = getValue(I.getArgOperand(0)); 5813 SDValue Op2 = getValue(I.getArgOperand(1)); 5814 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5815 return nullptr; 5816 } 5817 case Intrinsic::uadd_sat: { 5818 SDValue Op1 = getValue(I.getArgOperand(0)); 5819 SDValue Op2 = getValue(I.getArgOperand(1)); 5820 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5821 return nullptr; 5822 } 5823 case Intrinsic::ssub_sat: { 5824 SDValue Op1 = getValue(I.getArgOperand(0)); 5825 SDValue Op2 = getValue(I.getArgOperand(1)); 5826 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5827 return nullptr; 5828 } 5829 case Intrinsic::usub_sat: { 5830 SDValue Op1 = getValue(I.getArgOperand(0)); 5831 SDValue Op2 = getValue(I.getArgOperand(1)); 5832 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5833 return nullptr; 5834 } 5835 case Intrinsic::smul_fix: { 5836 SDValue Op1 = getValue(I.getArgOperand(0)); 5837 SDValue Op2 = getValue(I.getArgOperand(1)); 5838 SDValue Op3 = getValue(I.getArgOperand(2)); 5839 setValue(&I, 5840 DAG.getNode(ISD::SMULFIX, sdl, Op1.getValueType(), Op1, Op2, Op3)); 5841 return nullptr; 5842 } 5843 case Intrinsic::stacksave: { 5844 SDValue Op = getRoot(); 5845 Res = DAG.getNode( 5846 ISD::STACKSAVE, sdl, 5847 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5848 setValue(&I, Res); 5849 DAG.setRoot(Res.getValue(1)); 5850 return nullptr; 5851 } 5852 case Intrinsic::stackrestore: 5853 Res = getValue(I.getArgOperand(0)); 5854 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5855 return nullptr; 5856 case Intrinsic::get_dynamic_area_offset: { 5857 SDValue Op = getRoot(); 5858 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5859 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5860 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5861 // target. 5862 if (PtrTy != ResTy) 5863 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5864 " intrinsic!"); 5865 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5866 Op); 5867 DAG.setRoot(Op); 5868 setValue(&I, Res); 5869 return nullptr; 5870 } 5871 case Intrinsic::stackguard: { 5872 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5873 MachineFunction &MF = DAG.getMachineFunction(); 5874 const Module &M = *MF.getFunction().getParent(); 5875 SDValue Chain = getRoot(); 5876 if (TLI.useLoadStackGuardNode()) { 5877 Res = getLoadStackGuard(DAG, sdl, Chain); 5878 } else { 5879 const Value *Global = TLI.getSDagStackGuard(M); 5880 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5881 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5882 MachinePointerInfo(Global, 0), Align, 5883 MachineMemOperand::MOVolatile); 5884 } 5885 if (TLI.useStackGuardXorFP()) 5886 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 5887 DAG.setRoot(Chain); 5888 setValue(&I, Res); 5889 return nullptr; 5890 } 5891 case Intrinsic::stackprotector: { 5892 // Emit code into the DAG to store the stack guard onto the stack. 5893 MachineFunction &MF = DAG.getMachineFunction(); 5894 MachineFrameInfo &MFI = MF.getFrameInfo(); 5895 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5896 SDValue Src, Chain = getRoot(); 5897 5898 if (TLI.useLoadStackGuardNode()) 5899 Src = getLoadStackGuard(DAG, sdl, Chain); 5900 else 5901 Src = getValue(I.getArgOperand(0)); // The guard's value. 5902 5903 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5904 5905 int FI = FuncInfo.StaticAllocaMap[Slot]; 5906 MFI.setStackProtectorIndex(FI); 5907 5908 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5909 5910 // Store the stack protector onto the stack. 5911 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5912 DAG.getMachineFunction(), FI), 5913 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5914 setValue(&I, Res); 5915 DAG.setRoot(Res); 5916 return nullptr; 5917 } 5918 case Intrinsic::objectsize: { 5919 // If we don't know by now, we're never going to know. 5920 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5921 5922 assert(CI && "Non-constant type in __builtin_object_size?"); 5923 5924 SDValue Arg = getValue(I.getCalledValue()); 5925 EVT Ty = Arg.getValueType(); 5926 5927 if (CI->isZero()) 5928 Res = DAG.getConstant(-1ULL, sdl, Ty); 5929 else 5930 Res = DAG.getConstant(0, sdl, Ty); 5931 5932 setValue(&I, Res); 5933 return nullptr; 5934 } 5935 5936 case Intrinsic::is_constant: 5937 // If this wasn't constant-folded away by now, then it's not a 5938 // constant. 5939 setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); 5940 return nullptr; 5941 5942 case Intrinsic::annotation: 5943 case Intrinsic::ptr_annotation: 5944 case Intrinsic::launder_invariant_group: 5945 case Intrinsic::strip_invariant_group: 5946 // Drop the intrinsic, but forward the value 5947 setValue(&I, getValue(I.getOperand(0))); 5948 return nullptr; 5949 case Intrinsic::assume: 5950 case Intrinsic::var_annotation: 5951 case Intrinsic::sideeffect: 5952 // Discard annotate attributes, assumptions, and artificial side-effects. 5953 return nullptr; 5954 5955 case Intrinsic::codeview_annotation: { 5956 // Emit a label associated with this metadata. 5957 MachineFunction &MF = DAG.getMachineFunction(); 5958 MCSymbol *Label = 5959 MF.getMMI().getContext().createTempSymbol("annotation", true); 5960 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 5961 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 5962 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 5963 DAG.setRoot(Res); 5964 return nullptr; 5965 } 5966 5967 case Intrinsic::init_trampoline: { 5968 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5969 5970 SDValue Ops[6]; 5971 Ops[0] = getRoot(); 5972 Ops[1] = getValue(I.getArgOperand(0)); 5973 Ops[2] = getValue(I.getArgOperand(1)); 5974 Ops[3] = getValue(I.getArgOperand(2)); 5975 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5976 Ops[5] = DAG.getSrcValue(F); 5977 5978 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 5979 5980 DAG.setRoot(Res); 5981 return nullptr; 5982 } 5983 case Intrinsic::adjust_trampoline: 5984 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 5985 TLI.getPointerTy(DAG.getDataLayout()), 5986 getValue(I.getArgOperand(0)))); 5987 return nullptr; 5988 case Intrinsic::gcroot: { 5989 assert(DAG.getMachineFunction().getFunction().hasGC() && 5990 "only valid in functions with gc specified, enforced by Verifier"); 5991 assert(GFI && "implied by previous"); 5992 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 5993 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 5994 5995 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 5996 GFI->addStackRoot(FI->getIndex(), TypeMap); 5997 return nullptr; 5998 } 5999 case Intrinsic::gcread: 6000 case Intrinsic::gcwrite: 6001 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6002 case Intrinsic::flt_rounds: 6003 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6004 return nullptr; 6005 6006 case Intrinsic::expect: 6007 // Just replace __builtin_expect(exp, c) with EXP. 6008 setValue(&I, getValue(I.getArgOperand(0))); 6009 return nullptr; 6010 6011 case Intrinsic::debugtrap: 6012 case Intrinsic::trap: { 6013 StringRef TrapFuncName = 6014 I.getAttributes() 6015 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6016 .getValueAsString(); 6017 if (TrapFuncName.empty()) { 6018 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6019 ISD::TRAP : ISD::DEBUGTRAP; 6020 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6021 return nullptr; 6022 } 6023 TargetLowering::ArgListTy Args; 6024 6025 TargetLowering::CallLoweringInfo CLI(DAG); 6026 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6027 CallingConv::C, I.getType(), 6028 DAG.getExternalSymbol(TrapFuncName.data(), 6029 TLI.getPointerTy(DAG.getDataLayout())), 6030 std::move(Args)); 6031 6032 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6033 DAG.setRoot(Result.second); 6034 return nullptr; 6035 } 6036 6037 case Intrinsic::uadd_with_overflow: 6038 case Intrinsic::sadd_with_overflow: 6039 case Intrinsic::usub_with_overflow: 6040 case Intrinsic::ssub_with_overflow: 6041 case Intrinsic::umul_with_overflow: 6042 case Intrinsic::smul_with_overflow: { 6043 ISD::NodeType Op; 6044 switch (Intrinsic) { 6045 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6046 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6047 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6048 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6049 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6050 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6051 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6052 } 6053 SDValue Op1 = getValue(I.getArgOperand(0)); 6054 SDValue Op2 = getValue(I.getArgOperand(1)); 6055 6056 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 6057 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6058 return nullptr; 6059 } 6060 case Intrinsic::prefetch: { 6061 SDValue Ops[5]; 6062 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6063 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6064 Ops[0] = DAG.getRoot(); 6065 Ops[1] = getValue(I.getArgOperand(0)); 6066 Ops[2] = getValue(I.getArgOperand(1)); 6067 Ops[3] = getValue(I.getArgOperand(2)); 6068 Ops[4] = getValue(I.getArgOperand(3)); 6069 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6070 DAG.getVTList(MVT::Other), Ops, 6071 EVT::getIntegerVT(*Context, 8), 6072 MachinePointerInfo(I.getArgOperand(0)), 6073 0, /* align */ 6074 Flags); 6075 6076 // Chain the prefetch in parallell with any pending loads, to stay out of 6077 // the way of later optimizations. 6078 PendingLoads.push_back(Result); 6079 Result = getRoot(); 6080 DAG.setRoot(Result); 6081 return nullptr; 6082 } 6083 case Intrinsic::lifetime_start: 6084 case Intrinsic::lifetime_end: { 6085 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6086 // Stack coloring is not enabled in O0, discard region information. 6087 if (TM.getOptLevel() == CodeGenOpt::None) 6088 return nullptr; 6089 6090 SmallVector<Value *, 4> Allocas; 6091 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 6092 6093 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 6094 E = Allocas.end(); Object != E; ++Object) { 6095 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6096 6097 // Could not find an Alloca. 6098 if (!LifetimeObject) 6099 continue; 6100 6101 // First check that the Alloca is static, otherwise it won't have a 6102 // valid frame index. 6103 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6104 if (SI == FuncInfo.StaticAllocaMap.end()) 6105 return nullptr; 6106 6107 int FI = SI->second; 6108 6109 SDValue Ops[2]; 6110 Ops[0] = getRoot(); 6111 Ops[1] = 6112 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 6113 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 6114 6115 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 6116 DAG.setRoot(Res); 6117 } 6118 return nullptr; 6119 } 6120 case Intrinsic::invariant_start: 6121 // Discard region information. 6122 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6123 return nullptr; 6124 case Intrinsic::invariant_end: 6125 // Discard region information. 6126 return nullptr; 6127 case Intrinsic::clear_cache: 6128 return TLI.getClearCacheBuiltinName(); 6129 case Intrinsic::donothing: 6130 // ignore 6131 return nullptr; 6132 case Intrinsic::experimental_stackmap: 6133 visitStackmap(I); 6134 return nullptr; 6135 case Intrinsic::experimental_patchpoint_void: 6136 case Intrinsic::experimental_patchpoint_i64: 6137 visitPatchpoint(&I); 6138 return nullptr; 6139 case Intrinsic::experimental_gc_statepoint: 6140 LowerStatepoint(ImmutableStatepoint(&I)); 6141 return nullptr; 6142 case Intrinsic::experimental_gc_result: 6143 visitGCResult(cast<GCResultInst>(I)); 6144 return nullptr; 6145 case Intrinsic::experimental_gc_relocate: 6146 visitGCRelocate(cast<GCRelocateInst>(I)); 6147 return nullptr; 6148 case Intrinsic::instrprof_increment: 6149 llvm_unreachable("instrprof failed to lower an increment"); 6150 case Intrinsic::instrprof_value_profile: 6151 llvm_unreachable("instrprof failed to lower a value profiling call"); 6152 case Intrinsic::localescape: { 6153 MachineFunction &MF = DAG.getMachineFunction(); 6154 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6155 6156 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6157 // is the same on all targets. 6158 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6159 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6160 if (isa<ConstantPointerNull>(Arg)) 6161 continue; // Skip null pointers. They represent a hole in index space. 6162 AllocaInst *Slot = cast<AllocaInst>(Arg); 6163 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6164 "can only escape static allocas"); 6165 int FI = FuncInfo.StaticAllocaMap[Slot]; 6166 MCSymbol *FrameAllocSym = 6167 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6168 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6169 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6170 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6171 .addSym(FrameAllocSym) 6172 .addFrameIndex(FI); 6173 } 6174 6175 MF.setHasLocalEscape(true); 6176 6177 return nullptr; 6178 } 6179 6180 case Intrinsic::localrecover: { 6181 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6182 MachineFunction &MF = DAG.getMachineFunction(); 6183 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6184 6185 // Get the symbol that defines the frame offset. 6186 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6187 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6188 unsigned IdxVal = 6189 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6190 MCSymbol *FrameAllocSym = 6191 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6192 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6193 6194 // Create a MCSymbol for the label to avoid any target lowering 6195 // that would make this PC relative. 6196 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6197 SDValue OffsetVal = 6198 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6199 6200 // Add the offset to the FP. 6201 Value *FP = I.getArgOperand(1); 6202 SDValue FPVal = getValue(FP); 6203 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6204 setValue(&I, Add); 6205 6206 return nullptr; 6207 } 6208 6209 case Intrinsic::eh_exceptionpointer: 6210 case Intrinsic::eh_exceptioncode: { 6211 // Get the exception pointer vreg, copy from it, and resize it to fit. 6212 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6213 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6214 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6215 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6216 SDValue N = 6217 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6218 if (Intrinsic == Intrinsic::eh_exceptioncode) 6219 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6220 setValue(&I, N); 6221 return nullptr; 6222 } 6223 case Intrinsic::xray_customevent: { 6224 // Here we want to make sure that the intrinsic behaves as if it has a 6225 // specific calling convention, and only for x86_64. 6226 // FIXME: Support other platforms later. 6227 const auto &Triple = DAG.getTarget().getTargetTriple(); 6228 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6229 return nullptr; 6230 6231 SDLoc DL = getCurSDLoc(); 6232 SmallVector<SDValue, 8> Ops; 6233 6234 // We want to say that we always want the arguments in registers. 6235 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6236 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6237 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6238 SDValue Chain = getRoot(); 6239 Ops.push_back(LogEntryVal); 6240 Ops.push_back(StrSizeVal); 6241 Ops.push_back(Chain); 6242 6243 // We need to enforce the calling convention for the callsite, so that 6244 // argument ordering is enforced correctly, and that register allocation can 6245 // see that some registers may be assumed clobbered and have to preserve 6246 // them across calls to the intrinsic. 6247 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6248 DL, NodeTys, Ops); 6249 SDValue patchableNode = SDValue(MN, 0); 6250 DAG.setRoot(patchableNode); 6251 setValue(&I, patchableNode); 6252 return nullptr; 6253 } 6254 case Intrinsic::xray_typedevent: { 6255 // Here we want to make sure that the intrinsic behaves as if it has a 6256 // specific calling convention, and only for x86_64. 6257 // FIXME: Support other platforms later. 6258 const auto &Triple = DAG.getTarget().getTargetTriple(); 6259 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6260 return nullptr; 6261 6262 SDLoc DL = getCurSDLoc(); 6263 SmallVector<SDValue, 8> Ops; 6264 6265 // We want to say that we always want the arguments in registers. 6266 // It's unclear to me how manipulating the selection DAG here forces callers 6267 // to provide arguments in registers instead of on the stack. 6268 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6269 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6270 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6271 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6272 SDValue Chain = getRoot(); 6273 Ops.push_back(LogTypeId); 6274 Ops.push_back(LogEntryVal); 6275 Ops.push_back(StrSizeVal); 6276 Ops.push_back(Chain); 6277 6278 // We need to enforce the calling convention for the callsite, so that 6279 // argument ordering is enforced correctly, and that register allocation can 6280 // see that some registers may be assumed clobbered and have to preserve 6281 // them across calls to the intrinsic. 6282 MachineSDNode *MN = DAG.getMachineNode( 6283 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6284 SDValue patchableNode = SDValue(MN, 0); 6285 DAG.setRoot(patchableNode); 6286 setValue(&I, patchableNode); 6287 return nullptr; 6288 } 6289 case Intrinsic::experimental_deoptimize: 6290 LowerDeoptimizeCall(&I); 6291 return nullptr; 6292 6293 case Intrinsic::experimental_vector_reduce_fadd: 6294 case Intrinsic::experimental_vector_reduce_fmul: 6295 case Intrinsic::experimental_vector_reduce_add: 6296 case Intrinsic::experimental_vector_reduce_mul: 6297 case Intrinsic::experimental_vector_reduce_and: 6298 case Intrinsic::experimental_vector_reduce_or: 6299 case Intrinsic::experimental_vector_reduce_xor: 6300 case Intrinsic::experimental_vector_reduce_smax: 6301 case Intrinsic::experimental_vector_reduce_smin: 6302 case Intrinsic::experimental_vector_reduce_umax: 6303 case Intrinsic::experimental_vector_reduce_umin: 6304 case Intrinsic::experimental_vector_reduce_fmax: 6305 case Intrinsic::experimental_vector_reduce_fmin: 6306 visitVectorReduce(I, Intrinsic); 6307 return nullptr; 6308 6309 case Intrinsic::icall_branch_funnel: { 6310 SmallVector<SDValue, 16> Ops; 6311 Ops.push_back(DAG.getRoot()); 6312 Ops.push_back(getValue(I.getArgOperand(0))); 6313 6314 int64_t Offset; 6315 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6316 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6317 if (!Base) 6318 report_fatal_error( 6319 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6320 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6321 6322 struct BranchFunnelTarget { 6323 int64_t Offset; 6324 SDValue Target; 6325 }; 6326 SmallVector<BranchFunnelTarget, 8> Targets; 6327 6328 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6329 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6330 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6331 if (ElemBase != Base) 6332 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6333 "to the same GlobalValue"); 6334 6335 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6336 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6337 if (!GA) 6338 report_fatal_error( 6339 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6340 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6341 GA->getGlobal(), getCurSDLoc(), 6342 Val.getValueType(), GA->getOffset())}); 6343 } 6344 llvm::sort(Targets, 6345 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6346 return T1.Offset < T2.Offset; 6347 }); 6348 6349 for (auto &T : Targets) { 6350 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6351 Ops.push_back(T.Target); 6352 } 6353 6354 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6355 getCurSDLoc(), MVT::Other, Ops), 6356 0); 6357 DAG.setRoot(N); 6358 setValue(&I, N); 6359 HasTailCall = true; 6360 return nullptr; 6361 } 6362 6363 case Intrinsic::wasm_landingpad_index: 6364 // Information this intrinsic contained has been transferred to 6365 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6366 // delete it now. 6367 return nullptr; 6368 } 6369 } 6370 6371 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6372 const ConstrainedFPIntrinsic &FPI) { 6373 SDLoc sdl = getCurSDLoc(); 6374 unsigned Opcode; 6375 switch (FPI.getIntrinsicID()) { 6376 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6377 case Intrinsic::experimental_constrained_fadd: 6378 Opcode = ISD::STRICT_FADD; 6379 break; 6380 case Intrinsic::experimental_constrained_fsub: 6381 Opcode = ISD::STRICT_FSUB; 6382 break; 6383 case Intrinsic::experimental_constrained_fmul: 6384 Opcode = ISD::STRICT_FMUL; 6385 break; 6386 case Intrinsic::experimental_constrained_fdiv: 6387 Opcode = ISD::STRICT_FDIV; 6388 break; 6389 case Intrinsic::experimental_constrained_frem: 6390 Opcode = ISD::STRICT_FREM; 6391 break; 6392 case Intrinsic::experimental_constrained_fma: 6393 Opcode = ISD::STRICT_FMA; 6394 break; 6395 case Intrinsic::experimental_constrained_sqrt: 6396 Opcode = ISD::STRICT_FSQRT; 6397 break; 6398 case Intrinsic::experimental_constrained_pow: 6399 Opcode = ISD::STRICT_FPOW; 6400 break; 6401 case Intrinsic::experimental_constrained_powi: 6402 Opcode = ISD::STRICT_FPOWI; 6403 break; 6404 case Intrinsic::experimental_constrained_sin: 6405 Opcode = ISD::STRICT_FSIN; 6406 break; 6407 case Intrinsic::experimental_constrained_cos: 6408 Opcode = ISD::STRICT_FCOS; 6409 break; 6410 case Intrinsic::experimental_constrained_exp: 6411 Opcode = ISD::STRICT_FEXP; 6412 break; 6413 case Intrinsic::experimental_constrained_exp2: 6414 Opcode = ISD::STRICT_FEXP2; 6415 break; 6416 case Intrinsic::experimental_constrained_log: 6417 Opcode = ISD::STRICT_FLOG; 6418 break; 6419 case Intrinsic::experimental_constrained_log10: 6420 Opcode = ISD::STRICT_FLOG10; 6421 break; 6422 case Intrinsic::experimental_constrained_log2: 6423 Opcode = ISD::STRICT_FLOG2; 6424 break; 6425 case Intrinsic::experimental_constrained_rint: 6426 Opcode = ISD::STRICT_FRINT; 6427 break; 6428 case Intrinsic::experimental_constrained_nearbyint: 6429 Opcode = ISD::STRICT_FNEARBYINT; 6430 break; 6431 case Intrinsic::experimental_constrained_maxnum: 6432 Opcode = ISD::STRICT_FMAXNUM; 6433 break; 6434 case Intrinsic::experimental_constrained_minnum: 6435 Opcode = ISD::STRICT_FMINNUM; 6436 break; 6437 case Intrinsic::experimental_constrained_ceil: 6438 Opcode = ISD::STRICT_FCEIL; 6439 break; 6440 case Intrinsic::experimental_constrained_floor: 6441 Opcode = ISD::STRICT_FFLOOR; 6442 break; 6443 case Intrinsic::experimental_constrained_round: 6444 Opcode = ISD::STRICT_FROUND; 6445 break; 6446 case Intrinsic::experimental_constrained_trunc: 6447 Opcode = ISD::STRICT_FTRUNC; 6448 break; 6449 } 6450 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6451 SDValue Chain = getRoot(); 6452 SmallVector<EVT, 4> ValueVTs; 6453 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6454 ValueVTs.push_back(MVT::Other); // Out chain 6455 6456 SDVTList VTs = DAG.getVTList(ValueVTs); 6457 SDValue Result; 6458 if (FPI.isUnaryOp()) 6459 Result = DAG.getNode(Opcode, sdl, VTs, 6460 { Chain, getValue(FPI.getArgOperand(0)) }); 6461 else if (FPI.isTernaryOp()) 6462 Result = DAG.getNode(Opcode, sdl, VTs, 6463 { Chain, getValue(FPI.getArgOperand(0)), 6464 getValue(FPI.getArgOperand(1)), 6465 getValue(FPI.getArgOperand(2)) }); 6466 else 6467 Result = DAG.getNode(Opcode, sdl, VTs, 6468 { Chain, getValue(FPI.getArgOperand(0)), 6469 getValue(FPI.getArgOperand(1)) }); 6470 6471 assert(Result.getNode()->getNumValues() == 2); 6472 SDValue OutChain = Result.getValue(1); 6473 DAG.setRoot(OutChain); 6474 SDValue FPResult = Result.getValue(0); 6475 setValue(&FPI, FPResult); 6476 } 6477 6478 std::pair<SDValue, SDValue> 6479 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6480 const BasicBlock *EHPadBB) { 6481 MachineFunction &MF = DAG.getMachineFunction(); 6482 MachineModuleInfo &MMI = MF.getMMI(); 6483 MCSymbol *BeginLabel = nullptr; 6484 6485 if (EHPadBB) { 6486 // Insert a label before the invoke call to mark the try range. This can be 6487 // used to detect deletion of the invoke via the MachineModuleInfo. 6488 BeginLabel = MMI.getContext().createTempSymbol(); 6489 6490 // For SjLj, keep track of which landing pads go with which invokes 6491 // so as to maintain the ordering of pads in the LSDA. 6492 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6493 if (CallSiteIndex) { 6494 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6495 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6496 6497 // Now that the call site is handled, stop tracking it. 6498 MMI.setCurrentCallSite(0); 6499 } 6500 6501 // Both PendingLoads and PendingExports must be flushed here; 6502 // this call might not return. 6503 (void)getRoot(); 6504 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6505 6506 CLI.setChain(getRoot()); 6507 } 6508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6509 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6510 6511 assert((CLI.IsTailCall || Result.second.getNode()) && 6512 "Non-null chain expected with non-tail call!"); 6513 assert((Result.second.getNode() || !Result.first.getNode()) && 6514 "Null value expected with tail call!"); 6515 6516 if (!Result.second.getNode()) { 6517 // As a special case, a null chain means that a tail call has been emitted 6518 // and the DAG root is already updated. 6519 HasTailCall = true; 6520 6521 // Since there's no actual continuation from this block, nothing can be 6522 // relying on us setting vregs for them. 6523 PendingExports.clear(); 6524 } else { 6525 DAG.setRoot(Result.second); 6526 } 6527 6528 if (EHPadBB) { 6529 // Insert a label at the end of the invoke call to mark the try range. This 6530 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6531 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6532 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6533 6534 // Inform MachineModuleInfo of range. 6535 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6536 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6537 // actually use outlined funclets and their LSDA info style. 6538 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6539 assert(CLI.CS); 6540 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6541 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6542 BeginLabel, EndLabel); 6543 } else if (!isScopedEHPersonality(Pers)) { 6544 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6545 } 6546 } 6547 6548 return Result; 6549 } 6550 6551 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6552 bool isTailCall, 6553 const BasicBlock *EHPadBB) { 6554 auto &DL = DAG.getDataLayout(); 6555 FunctionType *FTy = CS.getFunctionType(); 6556 Type *RetTy = CS.getType(); 6557 6558 TargetLowering::ArgListTy Args; 6559 Args.reserve(CS.arg_size()); 6560 6561 const Value *SwiftErrorVal = nullptr; 6562 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6563 6564 // We can't tail call inside a function with a swifterror argument. Lowering 6565 // does not support this yet. It would have to move into the swifterror 6566 // register before the call. 6567 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6568 if (TLI.supportSwiftError() && 6569 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6570 isTailCall = false; 6571 6572 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6573 i != e; ++i) { 6574 TargetLowering::ArgListEntry Entry; 6575 const Value *V = *i; 6576 6577 // Skip empty types 6578 if (V->getType()->isEmptyTy()) 6579 continue; 6580 6581 SDValue ArgNode = getValue(V); 6582 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6583 6584 Entry.setAttributes(&CS, i - CS.arg_begin()); 6585 6586 // Use swifterror virtual register as input to the call. 6587 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6588 SwiftErrorVal = V; 6589 // We find the virtual register for the actual swifterror argument. 6590 // Instead of using the Value, we use the virtual register instead. 6591 Entry.Node = DAG.getRegister(FuncInfo 6592 .getOrCreateSwiftErrorVRegUseAt( 6593 CS.getInstruction(), FuncInfo.MBB, V) 6594 .first, 6595 EVT(TLI.getPointerTy(DL))); 6596 } 6597 6598 Args.push_back(Entry); 6599 6600 // If we have an explicit sret argument that is an Instruction, (i.e., it 6601 // might point to function-local memory), we can't meaningfully tail-call. 6602 if (Entry.IsSRet && isa<Instruction>(V)) 6603 isTailCall = false; 6604 } 6605 6606 // Check if target-independent constraints permit a tail call here. 6607 // Target-dependent constraints are checked within TLI->LowerCallTo. 6608 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6609 isTailCall = false; 6610 6611 // Disable tail calls if there is an swifterror argument. Targets have not 6612 // been updated to support tail calls. 6613 if (TLI.supportSwiftError() && SwiftErrorVal) 6614 isTailCall = false; 6615 6616 TargetLowering::CallLoweringInfo CLI(DAG); 6617 CLI.setDebugLoc(getCurSDLoc()) 6618 .setChain(getRoot()) 6619 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6620 .setTailCall(isTailCall) 6621 .setConvergent(CS.isConvergent()); 6622 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6623 6624 if (Result.first.getNode()) { 6625 const Instruction *Inst = CS.getInstruction(); 6626 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6627 setValue(Inst, Result.first); 6628 } 6629 6630 // The last element of CLI.InVals has the SDValue for swifterror return. 6631 // Here we copy it to a virtual register and update SwiftErrorMap for 6632 // book-keeping. 6633 if (SwiftErrorVal && TLI.supportSwiftError()) { 6634 // Get the last element of InVals. 6635 SDValue Src = CLI.InVals.back(); 6636 unsigned VReg; bool CreatedVReg; 6637 std::tie(VReg, CreatedVReg) = 6638 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6639 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6640 // We update the virtual register for the actual swifterror argument. 6641 if (CreatedVReg) 6642 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6643 DAG.setRoot(CopyNode); 6644 } 6645 } 6646 6647 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6648 SelectionDAGBuilder &Builder) { 6649 // Check to see if this load can be trivially constant folded, e.g. if the 6650 // input is from a string literal. 6651 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6652 // Cast pointer to the type we really want to load. 6653 Type *LoadTy = 6654 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6655 if (LoadVT.isVector()) 6656 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6657 6658 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6659 PointerType::getUnqual(LoadTy)); 6660 6661 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6662 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6663 return Builder.getValue(LoadCst); 6664 } 6665 6666 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6667 // still constant memory, the input chain can be the entry node. 6668 SDValue Root; 6669 bool ConstantMemory = false; 6670 6671 // Do not serialize (non-volatile) loads of constant memory with anything. 6672 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6673 Root = Builder.DAG.getEntryNode(); 6674 ConstantMemory = true; 6675 } else { 6676 // Do not serialize non-volatile loads against each other. 6677 Root = Builder.DAG.getRoot(); 6678 } 6679 6680 SDValue Ptr = Builder.getValue(PtrVal); 6681 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6682 Ptr, MachinePointerInfo(PtrVal), 6683 /* Alignment = */ 1); 6684 6685 if (!ConstantMemory) 6686 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6687 return LoadVal; 6688 } 6689 6690 /// Record the value for an instruction that produces an integer result, 6691 /// converting the type where necessary. 6692 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6693 SDValue Value, 6694 bool IsSigned) { 6695 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6696 I.getType(), true); 6697 if (IsSigned) 6698 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6699 else 6700 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6701 setValue(&I, Value); 6702 } 6703 6704 /// See if we can lower a memcmp call into an optimized form. If so, return 6705 /// true and lower it. Otherwise return false, and it will be lowered like a 6706 /// normal call. 6707 /// The caller already checked that \p I calls the appropriate LibFunc with a 6708 /// correct prototype. 6709 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6710 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6711 const Value *Size = I.getArgOperand(2); 6712 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6713 if (CSize && CSize->getZExtValue() == 0) { 6714 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6715 I.getType(), true); 6716 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6717 return true; 6718 } 6719 6720 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6721 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6722 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6723 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6724 if (Res.first.getNode()) { 6725 processIntegerCallValue(I, Res.first, true); 6726 PendingLoads.push_back(Res.second); 6727 return true; 6728 } 6729 6730 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6731 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6732 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6733 return false; 6734 6735 // If the target has a fast compare for the given size, it will return a 6736 // preferred load type for that size. Require that the load VT is legal and 6737 // that the target supports unaligned loads of that type. Otherwise, return 6738 // INVALID. 6739 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6740 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6741 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6742 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6743 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6744 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6745 // TODO: Check alignment of src and dest ptrs. 6746 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6747 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6748 if (!TLI.isTypeLegal(LVT) || 6749 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6750 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6751 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6752 } 6753 6754 return LVT; 6755 }; 6756 6757 // This turns into unaligned loads. We only do this if the target natively 6758 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6759 // we'll only produce a small number of byte loads. 6760 MVT LoadVT; 6761 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6762 switch (NumBitsToCompare) { 6763 default: 6764 return false; 6765 case 16: 6766 LoadVT = MVT::i16; 6767 break; 6768 case 32: 6769 LoadVT = MVT::i32; 6770 break; 6771 case 64: 6772 case 128: 6773 case 256: 6774 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6775 break; 6776 } 6777 6778 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6779 return false; 6780 6781 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6782 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6783 6784 // Bitcast to a wide integer type if the loads are vectors. 6785 if (LoadVT.isVector()) { 6786 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6787 LoadL = DAG.getBitcast(CmpVT, LoadL); 6788 LoadR = DAG.getBitcast(CmpVT, LoadR); 6789 } 6790 6791 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6792 processIntegerCallValue(I, Cmp, false); 6793 return true; 6794 } 6795 6796 /// See if we can lower a memchr call into an optimized form. If so, return 6797 /// true and lower it. Otherwise return false, and it will be lowered like a 6798 /// normal call. 6799 /// The caller already checked that \p I calls the appropriate LibFunc with a 6800 /// correct prototype. 6801 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6802 const Value *Src = I.getArgOperand(0); 6803 const Value *Char = I.getArgOperand(1); 6804 const Value *Length = I.getArgOperand(2); 6805 6806 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6807 std::pair<SDValue, SDValue> Res = 6808 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6809 getValue(Src), getValue(Char), getValue(Length), 6810 MachinePointerInfo(Src)); 6811 if (Res.first.getNode()) { 6812 setValue(&I, Res.first); 6813 PendingLoads.push_back(Res.second); 6814 return true; 6815 } 6816 6817 return false; 6818 } 6819 6820 /// See if we can lower a mempcpy call into an optimized form. If so, return 6821 /// true and lower it. Otherwise return false, and it will be lowered like a 6822 /// normal call. 6823 /// The caller already checked that \p I calls the appropriate LibFunc with a 6824 /// correct prototype. 6825 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6826 SDValue Dst = getValue(I.getArgOperand(0)); 6827 SDValue Src = getValue(I.getArgOperand(1)); 6828 SDValue Size = getValue(I.getArgOperand(2)); 6829 6830 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6831 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6832 unsigned Align = std::min(DstAlign, SrcAlign); 6833 if (Align == 0) // Alignment of one or both could not be inferred. 6834 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6835 6836 bool isVol = false; 6837 SDLoc sdl = getCurSDLoc(); 6838 6839 // In the mempcpy context we need to pass in a false value for isTailCall 6840 // because the return pointer needs to be adjusted by the size of 6841 // the copied memory. 6842 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6843 false, /*isTailCall=*/false, 6844 MachinePointerInfo(I.getArgOperand(0)), 6845 MachinePointerInfo(I.getArgOperand(1))); 6846 assert(MC.getNode() != nullptr && 6847 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6848 DAG.setRoot(MC); 6849 6850 // Check if Size needs to be truncated or extended. 6851 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6852 6853 // Adjust return pointer to point just past the last dst byte. 6854 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6855 Dst, Size); 6856 setValue(&I, DstPlusSize); 6857 return true; 6858 } 6859 6860 /// See if we can lower a strcpy call into an optimized form. If so, return 6861 /// true and lower it, otherwise return false and it will be lowered like a 6862 /// normal call. 6863 /// The caller already checked that \p I calls the appropriate LibFunc with a 6864 /// correct prototype. 6865 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6866 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6867 6868 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6869 std::pair<SDValue, SDValue> Res = 6870 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6871 getValue(Arg0), getValue(Arg1), 6872 MachinePointerInfo(Arg0), 6873 MachinePointerInfo(Arg1), isStpcpy); 6874 if (Res.first.getNode()) { 6875 setValue(&I, Res.first); 6876 DAG.setRoot(Res.second); 6877 return true; 6878 } 6879 6880 return false; 6881 } 6882 6883 /// See if we can lower a strcmp call into an optimized form. If so, return 6884 /// true and lower it, otherwise return false and it will be lowered like a 6885 /// normal call. 6886 /// The caller already checked that \p I calls the appropriate LibFunc with a 6887 /// correct prototype. 6888 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6889 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6890 6891 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6892 std::pair<SDValue, SDValue> Res = 6893 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6894 getValue(Arg0), getValue(Arg1), 6895 MachinePointerInfo(Arg0), 6896 MachinePointerInfo(Arg1)); 6897 if (Res.first.getNode()) { 6898 processIntegerCallValue(I, Res.first, true); 6899 PendingLoads.push_back(Res.second); 6900 return true; 6901 } 6902 6903 return false; 6904 } 6905 6906 /// See if we can lower a strlen call into an optimized form. If so, return 6907 /// true and lower it, otherwise return false and it will be lowered like a 6908 /// normal call. 6909 /// The caller already checked that \p I calls the appropriate LibFunc with a 6910 /// correct prototype. 6911 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6912 const Value *Arg0 = I.getArgOperand(0); 6913 6914 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6915 std::pair<SDValue, SDValue> Res = 6916 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6917 getValue(Arg0), MachinePointerInfo(Arg0)); 6918 if (Res.first.getNode()) { 6919 processIntegerCallValue(I, Res.first, false); 6920 PendingLoads.push_back(Res.second); 6921 return true; 6922 } 6923 6924 return false; 6925 } 6926 6927 /// See if we can lower a strnlen call into an optimized form. If so, return 6928 /// true and lower it, otherwise return false and it will be lowered like a 6929 /// normal call. 6930 /// The caller already checked that \p I calls the appropriate LibFunc with a 6931 /// correct prototype. 6932 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6933 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6934 6935 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6936 std::pair<SDValue, SDValue> Res = 6937 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6938 getValue(Arg0), getValue(Arg1), 6939 MachinePointerInfo(Arg0)); 6940 if (Res.first.getNode()) { 6941 processIntegerCallValue(I, Res.first, false); 6942 PendingLoads.push_back(Res.second); 6943 return true; 6944 } 6945 6946 return false; 6947 } 6948 6949 /// See if we can lower a unary floating-point operation into an SDNode with 6950 /// the specified Opcode. If so, return true and lower it, otherwise return 6951 /// false and it will be lowered like a normal call. 6952 /// The caller already checked that \p I calls the appropriate LibFunc with a 6953 /// correct prototype. 6954 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6955 unsigned Opcode) { 6956 // We already checked this call's prototype; verify it doesn't modify errno. 6957 if (!I.onlyReadsMemory()) 6958 return false; 6959 6960 SDValue Tmp = getValue(I.getArgOperand(0)); 6961 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6962 return true; 6963 } 6964 6965 /// See if we can lower a binary floating-point operation into an SDNode with 6966 /// the specified Opcode. If so, return true and lower it. Otherwise return 6967 /// false, and it will be lowered like a normal call. 6968 /// The caller already checked that \p I calls the appropriate LibFunc with a 6969 /// correct prototype. 6970 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6971 unsigned Opcode) { 6972 // We already checked this call's prototype; verify it doesn't modify errno. 6973 if (!I.onlyReadsMemory()) 6974 return false; 6975 6976 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6977 SDValue Tmp1 = getValue(I.getArgOperand(1)); 6978 EVT VT = Tmp0.getValueType(); 6979 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 6980 return true; 6981 } 6982 6983 void SelectionDAGBuilder::visitCall(const CallInst &I) { 6984 // Handle inline assembly differently. 6985 if (isa<InlineAsm>(I.getCalledValue())) { 6986 visitInlineAsm(&I); 6987 return; 6988 } 6989 6990 const char *RenameFn = nullptr; 6991 if (Function *F = I.getCalledFunction()) { 6992 if (F->isDeclaration()) { 6993 // Is this an LLVM intrinsic or a target-specific intrinsic? 6994 unsigned IID = F->getIntrinsicID(); 6995 if (!IID) 6996 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 6997 IID = II->getIntrinsicID(F); 6998 6999 if (IID) { 7000 RenameFn = visitIntrinsicCall(I, IID); 7001 if (!RenameFn) 7002 return; 7003 } 7004 } 7005 7006 // Check for well-known libc/libm calls. If the function is internal, it 7007 // can't be a library call. Don't do the check if marked as nobuiltin for 7008 // some reason or the call site requires strict floating point semantics. 7009 LibFunc Func; 7010 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7011 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7012 LibInfo->hasOptimizedCodeGen(Func)) { 7013 switch (Func) { 7014 default: break; 7015 case LibFunc_copysign: 7016 case LibFunc_copysignf: 7017 case LibFunc_copysignl: 7018 // We already checked this call's prototype; verify it doesn't modify 7019 // errno. 7020 if (I.onlyReadsMemory()) { 7021 SDValue LHS = getValue(I.getArgOperand(0)); 7022 SDValue RHS = getValue(I.getArgOperand(1)); 7023 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7024 LHS.getValueType(), LHS, RHS)); 7025 return; 7026 } 7027 break; 7028 case LibFunc_fabs: 7029 case LibFunc_fabsf: 7030 case LibFunc_fabsl: 7031 if (visitUnaryFloatCall(I, ISD::FABS)) 7032 return; 7033 break; 7034 case LibFunc_fmin: 7035 case LibFunc_fminf: 7036 case LibFunc_fminl: 7037 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7038 return; 7039 break; 7040 case LibFunc_fmax: 7041 case LibFunc_fmaxf: 7042 case LibFunc_fmaxl: 7043 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7044 return; 7045 break; 7046 case LibFunc_sin: 7047 case LibFunc_sinf: 7048 case LibFunc_sinl: 7049 if (visitUnaryFloatCall(I, ISD::FSIN)) 7050 return; 7051 break; 7052 case LibFunc_cos: 7053 case LibFunc_cosf: 7054 case LibFunc_cosl: 7055 if (visitUnaryFloatCall(I, ISD::FCOS)) 7056 return; 7057 break; 7058 case LibFunc_sqrt: 7059 case LibFunc_sqrtf: 7060 case LibFunc_sqrtl: 7061 case LibFunc_sqrt_finite: 7062 case LibFunc_sqrtf_finite: 7063 case LibFunc_sqrtl_finite: 7064 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7065 return; 7066 break; 7067 case LibFunc_floor: 7068 case LibFunc_floorf: 7069 case LibFunc_floorl: 7070 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7071 return; 7072 break; 7073 case LibFunc_nearbyint: 7074 case LibFunc_nearbyintf: 7075 case LibFunc_nearbyintl: 7076 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7077 return; 7078 break; 7079 case LibFunc_ceil: 7080 case LibFunc_ceilf: 7081 case LibFunc_ceill: 7082 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7083 return; 7084 break; 7085 case LibFunc_rint: 7086 case LibFunc_rintf: 7087 case LibFunc_rintl: 7088 if (visitUnaryFloatCall(I, ISD::FRINT)) 7089 return; 7090 break; 7091 case LibFunc_round: 7092 case LibFunc_roundf: 7093 case LibFunc_roundl: 7094 if (visitUnaryFloatCall(I, ISD::FROUND)) 7095 return; 7096 break; 7097 case LibFunc_trunc: 7098 case LibFunc_truncf: 7099 case LibFunc_truncl: 7100 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7101 return; 7102 break; 7103 case LibFunc_log2: 7104 case LibFunc_log2f: 7105 case LibFunc_log2l: 7106 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7107 return; 7108 break; 7109 case LibFunc_exp2: 7110 case LibFunc_exp2f: 7111 case LibFunc_exp2l: 7112 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7113 return; 7114 break; 7115 case LibFunc_memcmp: 7116 if (visitMemCmpCall(I)) 7117 return; 7118 break; 7119 case LibFunc_mempcpy: 7120 if (visitMemPCpyCall(I)) 7121 return; 7122 break; 7123 case LibFunc_memchr: 7124 if (visitMemChrCall(I)) 7125 return; 7126 break; 7127 case LibFunc_strcpy: 7128 if (visitStrCpyCall(I, false)) 7129 return; 7130 break; 7131 case LibFunc_stpcpy: 7132 if (visitStrCpyCall(I, true)) 7133 return; 7134 break; 7135 case LibFunc_strcmp: 7136 if (visitStrCmpCall(I)) 7137 return; 7138 break; 7139 case LibFunc_strlen: 7140 if (visitStrLenCall(I)) 7141 return; 7142 break; 7143 case LibFunc_strnlen: 7144 if (visitStrNLenCall(I)) 7145 return; 7146 break; 7147 } 7148 } 7149 } 7150 7151 SDValue Callee; 7152 if (!RenameFn) 7153 Callee = getValue(I.getCalledValue()); 7154 else 7155 Callee = DAG.getExternalSymbol( 7156 RenameFn, 7157 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7158 7159 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7160 // have to do anything here to lower funclet bundles. 7161 assert(!I.hasOperandBundlesOtherThan( 7162 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7163 "Cannot lower calls with arbitrary operand bundles!"); 7164 7165 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7166 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7167 else 7168 // Check if we can potentially perform a tail call. More detailed checking 7169 // is be done within LowerCallTo, after more information about the call is 7170 // known. 7171 LowerCallTo(&I, Callee, I.isTailCall()); 7172 } 7173 7174 namespace { 7175 7176 /// AsmOperandInfo - This contains information for each constraint that we are 7177 /// lowering. 7178 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7179 public: 7180 /// CallOperand - If this is the result output operand or a clobber 7181 /// this is null, otherwise it is the incoming operand to the CallInst. 7182 /// This gets modified as the asm is processed. 7183 SDValue CallOperand; 7184 7185 /// AssignedRegs - If this is a register or register class operand, this 7186 /// contains the set of register corresponding to the operand. 7187 RegsForValue AssignedRegs; 7188 7189 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7190 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7191 } 7192 7193 /// Whether or not this operand accesses memory 7194 bool hasMemory(const TargetLowering &TLI) const { 7195 // Indirect operand accesses access memory. 7196 if (isIndirect) 7197 return true; 7198 7199 for (const auto &Code : Codes) 7200 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7201 return true; 7202 7203 return false; 7204 } 7205 7206 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7207 /// corresponds to. If there is no Value* for this operand, it returns 7208 /// MVT::Other. 7209 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7210 const DataLayout &DL) const { 7211 if (!CallOperandVal) return MVT::Other; 7212 7213 if (isa<BasicBlock>(CallOperandVal)) 7214 return TLI.getPointerTy(DL); 7215 7216 llvm::Type *OpTy = CallOperandVal->getType(); 7217 7218 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7219 // If this is an indirect operand, the operand is a pointer to the 7220 // accessed type. 7221 if (isIndirect) { 7222 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7223 if (!PtrTy) 7224 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7225 OpTy = PtrTy->getElementType(); 7226 } 7227 7228 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7229 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7230 if (STy->getNumElements() == 1) 7231 OpTy = STy->getElementType(0); 7232 7233 // If OpTy is not a single value, it may be a struct/union that we 7234 // can tile with integers. 7235 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7236 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7237 switch (BitSize) { 7238 default: break; 7239 case 1: 7240 case 8: 7241 case 16: 7242 case 32: 7243 case 64: 7244 case 128: 7245 OpTy = IntegerType::get(Context, BitSize); 7246 break; 7247 } 7248 } 7249 7250 return TLI.getValueType(DL, OpTy, true); 7251 } 7252 }; 7253 7254 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7255 7256 } // end anonymous namespace 7257 7258 /// Make sure that the output operand \p OpInfo and its corresponding input 7259 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7260 /// out). 7261 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7262 SDISelAsmOperandInfo &MatchingOpInfo, 7263 SelectionDAG &DAG) { 7264 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7265 return; 7266 7267 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7268 const auto &TLI = DAG.getTargetLoweringInfo(); 7269 7270 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7271 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7272 OpInfo.ConstraintVT); 7273 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7274 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7275 MatchingOpInfo.ConstraintVT); 7276 if ((OpInfo.ConstraintVT.isInteger() != 7277 MatchingOpInfo.ConstraintVT.isInteger()) || 7278 (MatchRC.second != InputRC.second)) { 7279 // FIXME: error out in a more elegant fashion 7280 report_fatal_error("Unsupported asm: input constraint" 7281 " with a matching output constraint of" 7282 " incompatible type!"); 7283 } 7284 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7285 } 7286 7287 /// Get a direct memory input to behave well as an indirect operand. 7288 /// This may introduce stores, hence the need for a \p Chain. 7289 /// \return The (possibly updated) chain. 7290 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7291 SDISelAsmOperandInfo &OpInfo, 7292 SelectionDAG &DAG) { 7293 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7294 7295 // If we don't have an indirect input, put it in the constpool if we can, 7296 // otherwise spill it to a stack slot. 7297 // TODO: This isn't quite right. We need to handle these according to 7298 // the addressing mode that the constraint wants. Also, this may take 7299 // an additional register for the computation and we don't want that 7300 // either. 7301 7302 // If the operand is a float, integer, or vector constant, spill to a 7303 // constant pool entry to get its address. 7304 const Value *OpVal = OpInfo.CallOperandVal; 7305 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7306 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7307 OpInfo.CallOperand = DAG.getConstantPool( 7308 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7309 return Chain; 7310 } 7311 7312 // Otherwise, create a stack slot and emit a store to it before the asm. 7313 Type *Ty = OpVal->getType(); 7314 auto &DL = DAG.getDataLayout(); 7315 uint64_t TySize = DL.getTypeAllocSize(Ty); 7316 unsigned Align = DL.getPrefTypeAlignment(Ty); 7317 MachineFunction &MF = DAG.getMachineFunction(); 7318 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7319 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7320 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7321 MachinePointerInfo::getFixedStack(MF, SSFI)); 7322 OpInfo.CallOperand = StackSlot; 7323 7324 return Chain; 7325 } 7326 7327 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7328 /// specified operand. We prefer to assign virtual registers, to allow the 7329 /// register allocator to handle the assignment process. However, if the asm 7330 /// uses features that we can't model on machineinstrs, we have SDISel do the 7331 /// allocation. This produces generally horrible, but correct, code. 7332 /// 7333 /// OpInfo describes the operand 7334 /// RefOpInfo describes the matching operand if any, the operand otherwise 7335 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7336 SDISelAsmOperandInfo &OpInfo, 7337 SDISelAsmOperandInfo &RefOpInfo) { 7338 LLVMContext &Context = *DAG.getContext(); 7339 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7340 7341 MachineFunction &MF = DAG.getMachineFunction(); 7342 SmallVector<unsigned, 4> Regs; 7343 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7344 7345 // No work to do for memory operations. 7346 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7347 return; 7348 7349 // If this is a constraint for a single physreg, or a constraint for a 7350 // register class, find it. 7351 unsigned AssignedReg; 7352 const TargetRegisterClass *RC; 7353 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7354 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7355 // RC is unset only on failure. Return immediately. 7356 if (!RC) 7357 return; 7358 7359 // Get the actual register value type. This is important, because the user 7360 // may have asked for (e.g.) the AX register in i32 type. We need to 7361 // remember that AX is actually i16 to get the right extension. 7362 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7363 7364 if (OpInfo.ConstraintVT != MVT::Other) { 7365 // If this is an FP operand in an integer register (or visa versa), or more 7366 // generally if the operand value disagrees with the register class we plan 7367 // to stick it in, fix the operand type. 7368 // 7369 // If this is an input value, the bitcast to the new type is done now. 7370 // Bitcast for output value is done at the end of visitInlineAsm(). 7371 if ((OpInfo.Type == InlineAsm::isOutput || 7372 OpInfo.Type == InlineAsm::isInput) && 7373 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7374 // Try to convert to the first EVT that the reg class contains. If the 7375 // types are identical size, use a bitcast to convert (e.g. two differing 7376 // vector types). Note: output bitcast is done at the end of 7377 // visitInlineAsm(). 7378 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7379 // Exclude indirect inputs while they are unsupported because the code 7380 // to perform the load is missing and thus OpInfo.CallOperand still 7381 // refers to the input address rather than the pointed-to value. 7382 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7383 OpInfo.CallOperand = 7384 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7385 OpInfo.ConstraintVT = RegVT; 7386 // If the operand is an FP value and we want it in integer registers, 7387 // use the corresponding integer type. This turns an f64 value into 7388 // i64, which can be passed with two i32 values on a 32-bit machine. 7389 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7390 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7391 if (OpInfo.Type == InlineAsm::isInput) 7392 OpInfo.CallOperand = 7393 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7394 OpInfo.ConstraintVT = VT; 7395 } 7396 } 7397 } 7398 7399 // No need to allocate a matching input constraint since the constraint it's 7400 // matching to has already been allocated. 7401 if (OpInfo.isMatchingInputConstraint()) 7402 return; 7403 7404 EVT ValueVT = OpInfo.ConstraintVT; 7405 if (OpInfo.ConstraintVT == MVT::Other) 7406 ValueVT = RegVT; 7407 7408 // Initialize NumRegs. 7409 unsigned NumRegs = 1; 7410 if (OpInfo.ConstraintVT != MVT::Other) 7411 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7412 7413 // If this is a constraint for a specific physical register, like {r17}, 7414 // assign it now. 7415 7416 // If this associated to a specific register, initialize iterator to correct 7417 // place. If virtual, make sure we have enough registers 7418 7419 // Initialize iterator if necessary 7420 TargetRegisterClass::iterator I = RC->begin(); 7421 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7422 7423 // Do not check for single registers. 7424 if (AssignedReg) { 7425 for (; *I != AssignedReg; ++I) 7426 assert(I != RC->end() && "AssignedReg should be member of RC"); 7427 } 7428 7429 for (; NumRegs; --NumRegs, ++I) { 7430 assert(I != RC->end() && "Ran out of registers to allocate!"); 7431 auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC); 7432 Regs.push_back(R); 7433 } 7434 7435 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7436 } 7437 7438 static unsigned 7439 findMatchingInlineAsmOperand(unsigned OperandNo, 7440 const std::vector<SDValue> &AsmNodeOperands) { 7441 // Scan until we find the definition we already emitted of this operand. 7442 unsigned CurOp = InlineAsm::Op_FirstOperand; 7443 for (; OperandNo; --OperandNo) { 7444 // Advance to the next operand. 7445 unsigned OpFlag = 7446 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7447 assert((InlineAsm::isRegDefKind(OpFlag) || 7448 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7449 InlineAsm::isMemKind(OpFlag)) && 7450 "Skipped past definitions?"); 7451 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7452 } 7453 return CurOp; 7454 } 7455 7456 namespace { 7457 7458 class ExtraFlags { 7459 unsigned Flags = 0; 7460 7461 public: 7462 explicit ExtraFlags(ImmutableCallSite CS) { 7463 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7464 if (IA->hasSideEffects()) 7465 Flags |= InlineAsm::Extra_HasSideEffects; 7466 if (IA->isAlignStack()) 7467 Flags |= InlineAsm::Extra_IsAlignStack; 7468 if (CS.isConvergent()) 7469 Flags |= InlineAsm::Extra_IsConvergent; 7470 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7471 } 7472 7473 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7474 // Ideally, we would only check against memory constraints. However, the 7475 // meaning of an Other constraint can be target-specific and we can't easily 7476 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7477 // for Other constraints as well. 7478 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7479 OpInfo.ConstraintType == TargetLowering::C_Other) { 7480 if (OpInfo.Type == InlineAsm::isInput) 7481 Flags |= InlineAsm::Extra_MayLoad; 7482 else if (OpInfo.Type == InlineAsm::isOutput) 7483 Flags |= InlineAsm::Extra_MayStore; 7484 else if (OpInfo.Type == InlineAsm::isClobber) 7485 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7486 } 7487 } 7488 7489 unsigned get() const { return Flags; } 7490 }; 7491 7492 } // end anonymous namespace 7493 7494 /// visitInlineAsm - Handle a call to an InlineAsm object. 7495 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7496 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7497 7498 /// ConstraintOperands - Information about all of the constraints. 7499 SDISelAsmOperandInfoVector ConstraintOperands; 7500 7501 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7502 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7503 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7504 7505 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7506 // AsmDialect, MayLoad, MayStore). 7507 bool HasSideEffect = IA->hasSideEffects(); 7508 ExtraFlags ExtraInfo(CS); 7509 7510 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7511 unsigned ResNo = 0; // ResNo - The result number of the next output. 7512 for (auto &T : TargetConstraints) { 7513 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7514 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7515 7516 // Compute the value type for each operand. 7517 if (OpInfo.Type == InlineAsm::isInput || 7518 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7519 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7520 7521 // Process the call argument. BasicBlocks are labels, currently appearing 7522 // only in asm's. 7523 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7524 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7525 } else { 7526 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7527 } 7528 7529 OpInfo.ConstraintVT = 7530 OpInfo 7531 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7532 .getSimpleVT(); 7533 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7534 // The return value of the call is this value. As such, there is no 7535 // corresponding argument. 7536 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7537 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7538 OpInfo.ConstraintVT = TLI.getSimpleValueType( 7539 DAG.getDataLayout(), STy->getElementType(ResNo)); 7540 } else { 7541 assert(ResNo == 0 && "Asm only has one result!"); 7542 OpInfo.ConstraintVT = 7543 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7544 } 7545 ++ResNo; 7546 } else { 7547 OpInfo.ConstraintVT = MVT::Other; 7548 } 7549 7550 if (!HasSideEffect) 7551 HasSideEffect = OpInfo.hasMemory(TLI); 7552 7553 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7554 // FIXME: Could we compute this on OpInfo rather than T? 7555 7556 // Compute the constraint code and ConstraintType to use. 7557 TLI.ComputeConstraintToUse(T, SDValue()); 7558 7559 ExtraInfo.update(T); 7560 } 7561 7562 // We won't need to flush pending loads if this asm doesn't touch 7563 // memory and is nonvolatile. 7564 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 7565 7566 // Second pass over the constraints: compute which constraint option to use. 7567 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7568 // If this is an output operand with a matching input operand, look up the 7569 // matching input. If their types mismatch, e.g. one is an integer, the 7570 // other is floating point, or their sizes are different, flag it as an 7571 // error. 7572 if (OpInfo.hasMatchingInput()) { 7573 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7574 patchMatchingInput(OpInfo, Input, DAG); 7575 } 7576 7577 // Compute the constraint code and ConstraintType to use. 7578 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7579 7580 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7581 OpInfo.Type == InlineAsm::isClobber) 7582 continue; 7583 7584 // If this is a memory input, and if the operand is not indirect, do what we 7585 // need to provide an address for the memory input. 7586 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7587 !OpInfo.isIndirect) { 7588 assert((OpInfo.isMultipleAlternative || 7589 (OpInfo.Type == InlineAsm::isInput)) && 7590 "Can only indirectify direct input operands!"); 7591 7592 // Memory operands really want the address of the value. 7593 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7594 7595 // There is no longer a Value* corresponding to this operand. 7596 OpInfo.CallOperandVal = nullptr; 7597 7598 // It is now an indirect operand. 7599 OpInfo.isIndirect = true; 7600 } 7601 7602 } 7603 7604 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7605 std::vector<SDValue> AsmNodeOperands; 7606 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7607 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7608 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7609 7610 // If we have a !srcloc metadata node associated with it, we want to attach 7611 // this to the ultimately generated inline asm machineinstr. To do this, we 7612 // pass in the third operand as this (potentially null) inline asm MDNode. 7613 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7614 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7615 7616 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7617 // bits as operand 3. 7618 AsmNodeOperands.push_back(DAG.getTargetConstant( 7619 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7620 7621 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 7622 // this, assign virtual and physical registers for inputs and otput. 7623 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7624 // Assign Registers. 7625 SDISelAsmOperandInfo &RefOpInfo = 7626 OpInfo.isMatchingInputConstraint() 7627 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7628 : OpInfo; 7629 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 7630 7631 switch (OpInfo.Type) { 7632 case InlineAsm::isOutput: 7633 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 7634 OpInfo.ConstraintType != TargetLowering::C_Register) { 7635 // Memory output, or 'other' output (e.g. 'X' constraint). 7636 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 7637 7638 unsigned ConstraintID = 7639 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7640 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7641 "Failed to convert memory constraint code to constraint id."); 7642 7643 // Add information to the INLINEASM node to know about this output. 7644 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7645 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7646 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7647 MVT::i32)); 7648 AsmNodeOperands.push_back(OpInfo.CallOperand); 7649 break; 7650 } else if (OpInfo.ConstraintType == TargetLowering::C_Register || 7651 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 7652 // Otherwise, this is a register or register class output. 7653 7654 // Copy the output from the appropriate register. Find a register that 7655 // we can use. 7656 if (OpInfo.AssignedRegs.Regs.empty()) { 7657 emitInlineAsmError( 7658 CS, "couldn't allocate output register for constraint '" + 7659 Twine(OpInfo.ConstraintCode) + "'"); 7660 return; 7661 } 7662 7663 // Add information to the INLINEASM node to know that this register is 7664 // set. 7665 OpInfo.AssignedRegs.AddInlineAsmOperands( 7666 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 7667 : InlineAsm::Kind_RegDef, 7668 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7669 } 7670 break; 7671 7672 case InlineAsm::isInput: { 7673 SDValue InOperandVal = OpInfo.CallOperand; 7674 7675 if (OpInfo.isMatchingInputConstraint()) { 7676 // If this is required to match an output register we have already set, 7677 // just use its register. 7678 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7679 AsmNodeOperands); 7680 unsigned OpFlag = 7681 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7682 if (InlineAsm::isRegDefKind(OpFlag) || 7683 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7684 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7685 if (OpInfo.isIndirect) { 7686 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7687 emitInlineAsmError(CS, "inline asm not supported yet:" 7688 " don't know how to handle tied " 7689 "indirect register inputs"); 7690 return; 7691 } 7692 7693 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7694 SmallVector<unsigned, 4> Regs; 7695 7696 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 7697 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 7698 MachineRegisterInfo &RegInfo = 7699 DAG.getMachineFunction().getRegInfo(); 7700 for (unsigned i = 0; i != NumRegs; ++i) 7701 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7702 } else { 7703 emitInlineAsmError(CS, "inline asm error: This value type register " 7704 "class is not natively supported!"); 7705 return; 7706 } 7707 7708 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7709 7710 SDLoc dl = getCurSDLoc(); 7711 // Use the produced MatchedRegs object to 7712 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7713 CS.getInstruction()); 7714 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7715 true, OpInfo.getMatchedOperand(), dl, 7716 DAG, AsmNodeOperands); 7717 break; 7718 } 7719 7720 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7721 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7722 "Unexpected number of operands"); 7723 // Add information to the INLINEASM node to know about this input. 7724 // See InlineAsm.h isUseOperandTiedToDef. 7725 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7726 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7727 OpInfo.getMatchedOperand()); 7728 AsmNodeOperands.push_back(DAG.getTargetConstant( 7729 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7730 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7731 break; 7732 } 7733 7734 // Treat indirect 'X' constraint as memory. 7735 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7736 OpInfo.isIndirect) 7737 OpInfo.ConstraintType = TargetLowering::C_Memory; 7738 7739 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7740 std::vector<SDValue> Ops; 7741 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7742 Ops, DAG); 7743 if (Ops.empty()) { 7744 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7745 Twine(OpInfo.ConstraintCode) + "'"); 7746 return; 7747 } 7748 7749 // Add information to the INLINEASM node to know about this input. 7750 unsigned ResOpType = 7751 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7752 AsmNodeOperands.push_back(DAG.getTargetConstant( 7753 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7754 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7755 break; 7756 } 7757 7758 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7759 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7760 assert(InOperandVal.getValueType() == 7761 TLI.getPointerTy(DAG.getDataLayout()) && 7762 "Memory operands expect pointer values"); 7763 7764 unsigned ConstraintID = 7765 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7766 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7767 "Failed to convert memory constraint code to constraint id."); 7768 7769 // Add information to the INLINEASM node to know about this input. 7770 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7771 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7772 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7773 getCurSDLoc(), 7774 MVT::i32)); 7775 AsmNodeOperands.push_back(InOperandVal); 7776 break; 7777 } 7778 7779 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7780 OpInfo.ConstraintType == TargetLowering::C_Register) && 7781 "Unknown constraint type!"); 7782 7783 // TODO: Support this. 7784 if (OpInfo.isIndirect) { 7785 emitInlineAsmError( 7786 CS, "Don't know how to handle indirect register inputs yet " 7787 "for constraint '" + 7788 Twine(OpInfo.ConstraintCode) + "'"); 7789 return; 7790 } 7791 7792 // Copy the input into the appropriate registers. 7793 if (OpInfo.AssignedRegs.Regs.empty()) { 7794 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7795 Twine(OpInfo.ConstraintCode) + "'"); 7796 return; 7797 } 7798 7799 SDLoc dl = getCurSDLoc(); 7800 7801 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7802 Chain, &Flag, CS.getInstruction()); 7803 7804 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7805 dl, DAG, AsmNodeOperands); 7806 break; 7807 } 7808 case InlineAsm::isClobber: 7809 // Add the clobbered value to the operand list, so that the register 7810 // allocator is aware that the physreg got clobbered. 7811 if (!OpInfo.AssignedRegs.Regs.empty()) 7812 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7813 false, 0, getCurSDLoc(), DAG, 7814 AsmNodeOperands); 7815 break; 7816 } 7817 } 7818 7819 // Finish up input operands. Set the input chain and add the flag last. 7820 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7821 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7822 7823 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7824 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7825 Flag = Chain.getValue(1); 7826 7827 // Do additional work to generate outputs. 7828 7829 SmallVector<EVT, 1> ResultVTs; 7830 SmallVector<SDValue, 1> ResultValues; 7831 SmallVector<SDValue, 8> OutChains; 7832 7833 llvm::Type *CSResultType = CS.getType(); 7834 unsigned NumReturns = 0; 7835 ArrayRef<Type *> ResultTypes; 7836 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) { 7837 NumReturns = StructResult->getNumElements(); 7838 ResultTypes = StructResult->elements(); 7839 } else if (!CSResultType->isVoidTy()) { 7840 NumReturns = 1; 7841 ResultTypes = makeArrayRef(CSResultType); 7842 } 7843 7844 auto CurResultType = ResultTypes.begin(); 7845 auto handleRegAssign = [&](SDValue V) { 7846 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 7847 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 7848 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 7849 ++CurResultType; 7850 // If the type of the inline asm call site return value is different but has 7851 // same size as the type of the asm output bitcast it. One example of this 7852 // is for vectors with different width / number of elements. This can 7853 // happen for register classes that can contain multiple different value 7854 // types. The preg or vreg allocated may not have the same VT as was 7855 // expected. 7856 // 7857 // This can also happen for a return value that disagrees with the register 7858 // class it is put in, eg. a double in a general-purpose register on a 7859 // 32-bit machine. 7860 if (ResultVT != V.getValueType() && 7861 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 7862 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 7863 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 7864 V.getValueType().isInteger()) { 7865 // If a result value was tied to an input value, the computed result 7866 // may have a wider width than the expected result. Extract the 7867 // relevant portion. 7868 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 7869 } 7870 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 7871 ResultVTs.push_back(ResultVT); 7872 ResultValues.push_back(V); 7873 }; 7874 7875 // Deal with assembly output fixups. 7876 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7877 if (OpInfo.Type == InlineAsm::isOutput && 7878 (OpInfo.ConstraintType == TargetLowering::C_Register || 7879 OpInfo.ConstraintType == TargetLowering::C_RegisterClass)) { 7880 if (OpInfo.isIndirect) { 7881 // Register indirect are manifest as stores. 7882 const RegsForValue &OutRegs = OpInfo.AssignedRegs; 7883 const Value *Ptr = OpInfo.CallOperandVal; 7884 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7885 Chain, &Flag, IA); 7886 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), OutVal, getValue(Ptr), 7887 MachinePointerInfo(Ptr)); 7888 OutChains.push_back(Val); 7889 } else { 7890 // generate CopyFromRegs to associated registers. 7891 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7892 SDValue Val = OpInfo.AssignedRegs.getCopyFromRegs( 7893 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 7894 if (Val.getOpcode() == ISD::MERGE_VALUES) { 7895 for (const SDValue &V : Val->op_values()) 7896 handleRegAssign(V); 7897 } else 7898 handleRegAssign(Val); 7899 } 7900 } 7901 } 7902 7903 // Set results. 7904 if (!ResultValues.empty()) { 7905 assert(CurResultType == ResultTypes.end() && 7906 "Mismatch in number of ResultTypes"); 7907 assert(ResultValues.size() == NumReturns && 7908 "Mismatch in number of output operands in asm result"); 7909 7910 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 7911 DAG.getVTList(ResultVTs), ResultValues); 7912 setValue(CS.getInstruction(), V); 7913 } 7914 7915 // Collect store chains. 7916 if (!OutChains.empty()) 7917 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7918 7919 // Only Update Root if inline assembly has a memory effect. 7920 if (ResultValues.empty() || HasSideEffect || !OutChains.empty()) 7921 DAG.setRoot(Chain); 7922 } 7923 7924 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 7925 const Twine &Message) { 7926 LLVMContext &Ctx = *DAG.getContext(); 7927 Ctx.emitError(CS.getInstruction(), Message); 7928 7929 // Make sure we leave the DAG in a valid state 7930 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7931 SmallVector<EVT, 1> ValueVTs; 7932 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 7933 7934 if (ValueVTs.empty()) 7935 return; 7936 7937 SmallVector<SDValue, 1> Ops; 7938 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 7939 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 7940 7941 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 7942 } 7943 7944 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 7945 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 7946 MVT::Other, getRoot(), 7947 getValue(I.getArgOperand(0)), 7948 DAG.getSrcValue(I.getArgOperand(0)))); 7949 } 7950 7951 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 7952 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7953 const DataLayout &DL = DAG.getDataLayout(); 7954 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7955 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 7956 DAG.getSrcValue(I.getOperand(0)), 7957 DL.getABITypeAlignment(I.getType())); 7958 setValue(&I, V); 7959 DAG.setRoot(V.getValue(1)); 7960 } 7961 7962 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 7963 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 7964 MVT::Other, getRoot(), 7965 getValue(I.getArgOperand(0)), 7966 DAG.getSrcValue(I.getArgOperand(0)))); 7967 } 7968 7969 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 7970 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 7971 MVT::Other, getRoot(), 7972 getValue(I.getArgOperand(0)), 7973 getValue(I.getArgOperand(1)), 7974 DAG.getSrcValue(I.getArgOperand(0)), 7975 DAG.getSrcValue(I.getArgOperand(1)))); 7976 } 7977 7978 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 7979 const Instruction &I, 7980 SDValue Op) { 7981 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 7982 if (!Range) 7983 return Op; 7984 7985 ConstantRange CR = getConstantRangeFromMetadata(*Range); 7986 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 7987 return Op; 7988 7989 APInt Lo = CR.getUnsignedMin(); 7990 if (!Lo.isMinValue()) 7991 return Op; 7992 7993 APInt Hi = CR.getUnsignedMax(); 7994 unsigned Bits = std::max(Hi.getActiveBits(), 7995 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 7996 7997 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 7998 7999 SDLoc SL = getCurSDLoc(); 8000 8001 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8002 DAG.getValueType(SmallVT)); 8003 unsigned NumVals = Op.getNode()->getNumValues(); 8004 if (NumVals == 1) 8005 return ZExt; 8006 8007 SmallVector<SDValue, 4> Ops; 8008 8009 Ops.push_back(ZExt); 8010 for (unsigned I = 1; I != NumVals; ++I) 8011 Ops.push_back(Op.getValue(I)); 8012 8013 return DAG.getMergeValues(Ops, SL); 8014 } 8015 8016 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8017 /// the call being lowered. 8018 /// 8019 /// This is a helper for lowering intrinsics that follow a target calling 8020 /// convention or require stack pointer adjustment. Only a subset of the 8021 /// intrinsic's operands need to participate in the calling convention. 8022 void SelectionDAGBuilder::populateCallLoweringInfo( 8023 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 8024 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8025 bool IsPatchPoint) { 8026 TargetLowering::ArgListTy Args; 8027 Args.reserve(NumArgs); 8028 8029 // Populate the argument list. 8030 // Attributes for args start at offset 1, after the return attribute. 8031 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8032 ArgI != ArgE; ++ArgI) { 8033 const Value *V = CS->getOperand(ArgI); 8034 8035 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8036 8037 TargetLowering::ArgListEntry Entry; 8038 Entry.Node = getValue(V); 8039 Entry.Ty = V->getType(); 8040 Entry.setAttributes(&CS, ArgI); 8041 Args.push_back(Entry); 8042 } 8043 8044 CLI.setDebugLoc(getCurSDLoc()) 8045 .setChain(getRoot()) 8046 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 8047 .setDiscardResult(CS->use_empty()) 8048 .setIsPatchPoint(IsPatchPoint); 8049 } 8050 8051 /// Add a stack map intrinsic call's live variable operands to a stackmap 8052 /// or patchpoint target node's operand list. 8053 /// 8054 /// Constants are converted to TargetConstants purely as an optimization to 8055 /// avoid constant materialization and register allocation. 8056 /// 8057 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8058 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 8059 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8060 /// address materialization and register allocation, but may also be required 8061 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8062 /// alloca in the entry block, then the runtime may assume that the alloca's 8063 /// StackMap location can be read immediately after compilation and that the 8064 /// location is valid at any point during execution (this is similar to the 8065 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8066 /// only available in a register, then the runtime would need to trap when 8067 /// execution reaches the StackMap in order to read the alloca's location. 8068 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8069 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8070 SelectionDAGBuilder &Builder) { 8071 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8072 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8073 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8074 Ops.push_back( 8075 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8076 Ops.push_back( 8077 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8078 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8079 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8080 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8081 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8082 } else 8083 Ops.push_back(OpVal); 8084 } 8085 } 8086 8087 /// Lower llvm.experimental.stackmap directly to its target opcode. 8088 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8089 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8090 // [live variables...]) 8091 8092 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8093 8094 SDValue Chain, InFlag, Callee, NullPtr; 8095 SmallVector<SDValue, 32> Ops; 8096 8097 SDLoc DL = getCurSDLoc(); 8098 Callee = getValue(CI.getCalledValue()); 8099 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8100 8101 // The stackmap intrinsic only records the live variables (the arguemnts 8102 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8103 // intrinsic, this won't be lowered to a function call. This means we don't 8104 // have to worry about calling conventions and target specific lowering code. 8105 // Instead we perform the call lowering right here. 8106 // 8107 // chain, flag = CALLSEQ_START(chain, 0, 0) 8108 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8109 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8110 // 8111 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8112 InFlag = Chain.getValue(1); 8113 8114 // Add the <id> and <numBytes> constants. 8115 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8116 Ops.push_back(DAG.getTargetConstant( 8117 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8118 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8119 Ops.push_back(DAG.getTargetConstant( 8120 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8121 MVT::i32)); 8122 8123 // Push live variables for the stack map. 8124 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8125 8126 // We are not pushing any register mask info here on the operands list, 8127 // because the stackmap doesn't clobber anything. 8128 8129 // Push the chain and the glue flag. 8130 Ops.push_back(Chain); 8131 Ops.push_back(InFlag); 8132 8133 // Create the STACKMAP node. 8134 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8135 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8136 Chain = SDValue(SM, 0); 8137 InFlag = Chain.getValue(1); 8138 8139 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8140 8141 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8142 8143 // Set the root to the target-lowered call chain. 8144 DAG.setRoot(Chain); 8145 8146 // Inform the Frame Information that we have a stackmap in this function. 8147 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8148 } 8149 8150 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8151 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8152 const BasicBlock *EHPadBB) { 8153 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8154 // i32 <numBytes>, 8155 // i8* <target>, 8156 // i32 <numArgs>, 8157 // [Args...], 8158 // [live variables...]) 8159 8160 CallingConv::ID CC = CS.getCallingConv(); 8161 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8162 bool HasDef = !CS->getType()->isVoidTy(); 8163 SDLoc dl = getCurSDLoc(); 8164 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8165 8166 // Handle immediate and symbolic callees. 8167 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8168 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8169 /*isTarget=*/true); 8170 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8171 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8172 SDLoc(SymbolicCallee), 8173 SymbolicCallee->getValueType(0)); 8174 8175 // Get the real number of arguments participating in the call <numArgs> 8176 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8177 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8178 8179 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8180 // Intrinsics include all meta-operands up to but not including CC. 8181 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8182 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8183 "Not enough arguments provided to the patchpoint intrinsic"); 8184 8185 // For AnyRegCC the arguments are lowered later on manually. 8186 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8187 Type *ReturnTy = 8188 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8189 8190 TargetLowering::CallLoweringInfo CLI(DAG); 8191 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 8192 true); 8193 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8194 8195 SDNode *CallEnd = Result.second.getNode(); 8196 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8197 CallEnd = CallEnd->getOperand(0).getNode(); 8198 8199 /// Get a call instruction from the call sequence chain. 8200 /// Tail calls are not allowed. 8201 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8202 "Expected a callseq node."); 8203 SDNode *Call = CallEnd->getOperand(0).getNode(); 8204 bool HasGlue = Call->getGluedNode(); 8205 8206 // Replace the target specific call node with the patchable intrinsic. 8207 SmallVector<SDValue, 8> Ops; 8208 8209 // Add the <id> and <numBytes> constants. 8210 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8211 Ops.push_back(DAG.getTargetConstant( 8212 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8213 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8214 Ops.push_back(DAG.getTargetConstant( 8215 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8216 MVT::i32)); 8217 8218 // Add the callee. 8219 Ops.push_back(Callee); 8220 8221 // Adjust <numArgs> to account for any arguments that have been passed on the 8222 // stack instead. 8223 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8224 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8225 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8226 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8227 8228 // Add the calling convention 8229 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8230 8231 // Add the arguments we omitted previously. The register allocator should 8232 // place these in any free register. 8233 if (IsAnyRegCC) 8234 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8235 Ops.push_back(getValue(CS.getArgument(i))); 8236 8237 // Push the arguments from the call instruction up to the register mask. 8238 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8239 Ops.append(Call->op_begin() + 2, e); 8240 8241 // Push live variables for the stack map. 8242 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8243 8244 // Push the register mask info. 8245 if (HasGlue) 8246 Ops.push_back(*(Call->op_end()-2)); 8247 else 8248 Ops.push_back(*(Call->op_end()-1)); 8249 8250 // Push the chain (this is originally the first operand of the call, but 8251 // becomes now the last or second to last operand). 8252 Ops.push_back(*(Call->op_begin())); 8253 8254 // Push the glue flag (last operand). 8255 if (HasGlue) 8256 Ops.push_back(*(Call->op_end()-1)); 8257 8258 SDVTList NodeTys; 8259 if (IsAnyRegCC && HasDef) { 8260 // Create the return types based on the intrinsic definition 8261 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8262 SmallVector<EVT, 3> ValueVTs; 8263 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8264 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8265 8266 // There is always a chain and a glue type at the end 8267 ValueVTs.push_back(MVT::Other); 8268 ValueVTs.push_back(MVT::Glue); 8269 NodeTys = DAG.getVTList(ValueVTs); 8270 } else 8271 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8272 8273 // Replace the target specific call node with a PATCHPOINT node. 8274 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8275 dl, NodeTys, Ops); 8276 8277 // Update the NodeMap. 8278 if (HasDef) { 8279 if (IsAnyRegCC) 8280 setValue(CS.getInstruction(), SDValue(MN, 0)); 8281 else 8282 setValue(CS.getInstruction(), Result.first); 8283 } 8284 8285 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8286 // call sequence. Furthermore the location of the chain and glue can change 8287 // when the AnyReg calling convention is used and the intrinsic returns a 8288 // value. 8289 if (IsAnyRegCC && HasDef) { 8290 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8291 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8292 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8293 } else 8294 DAG.ReplaceAllUsesWith(Call, MN); 8295 DAG.DeleteNode(Call); 8296 8297 // Inform the Frame Information that we have a patchpoint in this function. 8298 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8299 } 8300 8301 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8302 unsigned Intrinsic) { 8303 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8304 SDValue Op1 = getValue(I.getArgOperand(0)); 8305 SDValue Op2; 8306 if (I.getNumArgOperands() > 1) 8307 Op2 = getValue(I.getArgOperand(1)); 8308 SDLoc dl = getCurSDLoc(); 8309 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8310 SDValue Res; 8311 FastMathFlags FMF; 8312 if (isa<FPMathOperator>(I)) 8313 FMF = I.getFastMathFlags(); 8314 8315 switch (Intrinsic) { 8316 case Intrinsic::experimental_vector_reduce_fadd: 8317 if (FMF.isFast()) 8318 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8319 else 8320 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8321 break; 8322 case Intrinsic::experimental_vector_reduce_fmul: 8323 if (FMF.isFast()) 8324 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8325 else 8326 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8327 break; 8328 case Intrinsic::experimental_vector_reduce_add: 8329 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8330 break; 8331 case Intrinsic::experimental_vector_reduce_mul: 8332 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8333 break; 8334 case Intrinsic::experimental_vector_reduce_and: 8335 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8336 break; 8337 case Intrinsic::experimental_vector_reduce_or: 8338 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8339 break; 8340 case Intrinsic::experimental_vector_reduce_xor: 8341 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8342 break; 8343 case Intrinsic::experimental_vector_reduce_smax: 8344 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8345 break; 8346 case Intrinsic::experimental_vector_reduce_smin: 8347 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8348 break; 8349 case Intrinsic::experimental_vector_reduce_umax: 8350 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8351 break; 8352 case Intrinsic::experimental_vector_reduce_umin: 8353 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8354 break; 8355 case Intrinsic::experimental_vector_reduce_fmax: 8356 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8357 break; 8358 case Intrinsic::experimental_vector_reduce_fmin: 8359 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8360 break; 8361 default: 8362 llvm_unreachable("Unhandled vector reduce intrinsic"); 8363 } 8364 setValue(&I, Res); 8365 } 8366 8367 /// Returns an AttributeList representing the attributes applied to the return 8368 /// value of the given call. 8369 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8370 SmallVector<Attribute::AttrKind, 2> Attrs; 8371 if (CLI.RetSExt) 8372 Attrs.push_back(Attribute::SExt); 8373 if (CLI.RetZExt) 8374 Attrs.push_back(Attribute::ZExt); 8375 if (CLI.IsInReg) 8376 Attrs.push_back(Attribute::InReg); 8377 8378 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8379 Attrs); 8380 } 8381 8382 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8383 /// implementation, which just calls LowerCall. 8384 /// FIXME: When all targets are 8385 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8386 std::pair<SDValue, SDValue> 8387 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8388 // Handle the incoming return values from the call. 8389 CLI.Ins.clear(); 8390 Type *OrigRetTy = CLI.RetTy; 8391 SmallVector<EVT, 4> RetTys; 8392 SmallVector<uint64_t, 4> Offsets; 8393 auto &DL = CLI.DAG.getDataLayout(); 8394 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8395 8396 if (CLI.IsPostTypeLegalization) { 8397 // If we are lowering a libcall after legalization, split the return type. 8398 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8399 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8400 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8401 EVT RetVT = OldRetTys[i]; 8402 uint64_t Offset = OldOffsets[i]; 8403 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8404 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8405 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8406 RetTys.append(NumRegs, RegisterVT); 8407 for (unsigned j = 0; j != NumRegs; ++j) 8408 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8409 } 8410 } 8411 8412 SmallVector<ISD::OutputArg, 4> Outs; 8413 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8414 8415 bool CanLowerReturn = 8416 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8417 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8418 8419 SDValue DemoteStackSlot; 8420 int DemoteStackIdx = -100; 8421 if (!CanLowerReturn) { 8422 // FIXME: equivalent assert? 8423 // assert(!CS.hasInAllocaArgument() && 8424 // "sret demotion is incompatible with inalloca"); 8425 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8426 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8427 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8428 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8429 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8430 DL.getAllocaAddrSpace()); 8431 8432 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8433 ArgListEntry Entry; 8434 Entry.Node = DemoteStackSlot; 8435 Entry.Ty = StackSlotPtrType; 8436 Entry.IsSExt = false; 8437 Entry.IsZExt = false; 8438 Entry.IsInReg = false; 8439 Entry.IsSRet = true; 8440 Entry.IsNest = false; 8441 Entry.IsByVal = false; 8442 Entry.IsReturned = false; 8443 Entry.IsSwiftSelf = false; 8444 Entry.IsSwiftError = false; 8445 Entry.Alignment = Align; 8446 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8447 CLI.NumFixedArgs += 1; 8448 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8449 8450 // sret demotion isn't compatible with tail-calls, since the sret argument 8451 // points into the callers stack frame. 8452 CLI.IsTailCall = false; 8453 } else { 8454 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8455 EVT VT = RetTys[I]; 8456 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8457 CLI.CallConv, VT); 8458 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8459 CLI.CallConv, VT); 8460 for (unsigned i = 0; i != NumRegs; ++i) { 8461 ISD::InputArg MyFlags; 8462 MyFlags.VT = RegisterVT; 8463 MyFlags.ArgVT = VT; 8464 MyFlags.Used = CLI.IsReturnValueUsed; 8465 if (CLI.RetSExt) 8466 MyFlags.Flags.setSExt(); 8467 if (CLI.RetZExt) 8468 MyFlags.Flags.setZExt(); 8469 if (CLI.IsInReg) 8470 MyFlags.Flags.setInReg(); 8471 CLI.Ins.push_back(MyFlags); 8472 } 8473 } 8474 } 8475 8476 // We push in swifterror return as the last element of CLI.Ins. 8477 ArgListTy &Args = CLI.getArgs(); 8478 if (supportSwiftError()) { 8479 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8480 if (Args[i].IsSwiftError) { 8481 ISD::InputArg MyFlags; 8482 MyFlags.VT = getPointerTy(DL); 8483 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8484 MyFlags.Flags.setSwiftError(); 8485 CLI.Ins.push_back(MyFlags); 8486 } 8487 } 8488 } 8489 8490 // Handle all of the outgoing arguments. 8491 CLI.Outs.clear(); 8492 CLI.OutVals.clear(); 8493 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8494 SmallVector<EVT, 4> ValueVTs; 8495 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8496 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8497 Type *FinalType = Args[i].Ty; 8498 if (Args[i].IsByVal) 8499 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8500 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8501 FinalType, CLI.CallConv, CLI.IsVarArg); 8502 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8503 ++Value) { 8504 EVT VT = ValueVTs[Value]; 8505 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8506 SDValue Op = SDValue(Args[i].Node.getNode(), 8507 Args[i].Node.getResNo() + Value); 8508 ISD::ArgFlagsTy Flags; 8509 8510 // Certain targets (such as MIPS), may have a different ABI alignment 8511 // for a type depending on the context. Give the target a chance to 8512 // specify the alignment it wants. 8513 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8514 8515 if (Args[i].IsZExt) 8516 Flags.setZExt(); 8517 if (Args[i].IsSExt) 8518 Flags.setSExt(); 8519 if (Args[i].IsInReg) { 8520 // If we are using vectorcall calling convention, a structure that is 8521 // passed InReg - is surely an HVA 8522 if (CLI.CallConv == CallingConv::X86_VectorCall && 8523 isa<StructType>(FinalType)) { 8524 // The first value of a structure is marked 8525 if (0 == Value) 8526 Flags.setHvaStart(); 8527 Flags.setHva(); 8528 } 8529 // Set InReg Flag 8530 Flags.setInReg(); 8531 } 8532 if (Args[i].IsSRet) 8533 Flags.setSRet(); 8534 if (Args[i].IsSwiftSelf) 8535 Flags.setSwiftSelf(); 8536 if (Args[i].IsSwiftError) 8537 Flags.setSwiftError(); 8538 if (Args[i].IsByVal) 8539 Flags.setByVal(); 8540 if (Args[i].IsInAlloca) { 8541 Flags.setInAlloca(); 8542 // Set the byval flag for CCAssignFn callbacks that don't know about 8543 // inalloca. This way we can know how many bytes we should've allocated 8544 // and how many bytes a callee cleanup function will pop. If we port 8545 // inalloca to more targets, we'll have to add custom inalloca handling 8546 // in the various CC lowering callbacks. 8547 Flags.setByVal(); 8548 } 8549 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8550 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8551 Type *ElementTy = Ty->getElementType(); 8552 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8553 // For ByVal, alignment should come from FE. BE will guess if this 8554 // info is not there but there are cases it cannot get right. 8555 unsigned FrameAlign; 8556 if (Args[i].Alignment) 8557 FrameAlign = Args[i].Alignment; 8558 else 8559 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8560 Flags.setByValAlign(FrameAlign); 8561 } 8562 if (Args[i].IsNest) 8563 Flags.setNest(); 8564 if (NeedsRegBlock) 8565 Flags.setInConsecutiveRegs(); 8566 Flags.setOrigAlign(OriginalAlignment); 8567 8568 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8569 CLI.CallConv, VT); 8570 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8571 CLI.CallConv, VT); 8572 SmallVector<SDValue, 4> Parts(NumParts); 8573 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8574 8575 if (Args[i].IsSExt) 8576 ExtendKind = ISD::SIGN_EXTEND; 8577 else if (Args[i].IsZExt) 8578 ExtendKind = ISD::ZERO_EXTEND; 8579 8580 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8581 // for now. 8582 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8583 CanLowerReturn) { 8584 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8585 "unexpected use of 'returned'"); 8586 // Before passing 'returned' to the target lowering code, ensure that 8587 // either the register MVT and the actual EVT are the same size or that 8588 // the return value and argument are extended in the same way; in these 8589 // cases it's safe to pass the argument register value unchanged as the 8590 // return register value (although it's at the target's option whether 8591 // to do so) 8592 // TODO: allow code generation to take advantage of partially preserved 8593 // registers rather than clobbering the entire register when the 8594 // parameter extension method is not compatible with the return 8595 // extension method 8596 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8597 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8598 CLI.RetZExt == Args[i].IsZExt)) 8599 Flags.setReturned(); 8600 } 8601 8602 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8603 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 8604 8605 for (unsigned j = 0; j != NumParts; ++j) { 8606 // if it isn't first piece, alignment must be 1 8607 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8608 i < CLI.NumFixedArgs, 8609 i, j*Parts[j].getValueType().getStoreSize()); 8610 if (NumParts > 1 && j == 0) 8611 MyFlags.Flags.setSplit(); 8612 else if (j != 0) { 8613 MyFlags.Flags.setOrigAlign(1); 8614 if (j == NumParts - 1) 8615 MyFlags.Flags.setSplitEnd(); 8616 } 8617 8618 CLI.Outs.push_back(MyFlags); 8619 CLI.OutVals.push_back(Parts[j]); 8620 } 8621 8622 if (NeedsRegBlock && Value == NumValues - 1) 8623 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8624 } 8625 } 8626 8627 SmallVector<SDValue, 4> InVals; 8628 CLI.Chain = LowerCall(CLI, InVals); 8629 8630 // Update CLI.InVals to use outside of this function. 8631 CLI.InVals = InVals; 8632 8633 // Verify that the target's LowerCall behaved as expected. 8634 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8635 "LowerCall didn't return a valid chain!"); 8636 assert((!CLI.IsTailCall || InVals.empty()) && 8637 "LowerCall emitted a return value for a tail call!"); 8638 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8639 "LowerCall didn't emit the correct number of values!"); 8640 8641 // For a tail call, the return value is merely live-out and there aren't 8642 // any nodes in the DAG representing it. Return a special value to 8643 // indicate that a tail call has been emitted and no more Instructions 8644 // should be processed in the current block. 8645 if (CLI.IsTailCall) { 8646 CLI.DAG.setRoot(CLI.Chain); 8647 return std::make_pair(SDValue(), SDValue()); 8648 } 8649 8650 #ifndef NDEBUG 8651 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8652 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8653 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8654 "LowerCall emitted a value with the wrong type!"); 8655 } 8656 #endif 8657 8658 SmallVector<SDValue, 4> ReturnValues; 8659 if (!CanLowerReturn) { 8660 // The instruction result is the result of loading from the 8661 // hidden sret parameter. 8662 SmallVector<EVT, 1> PVTs; 8663 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8664 8665 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8666 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8667 EVT PtrVT = PVTs[0]; 8668 8669 unsigned NumValues = RetTys.size(); 8670 ReturnValues.resize(NumValues); 8671 SmallVector<SDValue, 4> Chains(NumValues); 8672 8673 // An aggregate return value cannot wrap around the address space, so 8674 // offsets to its parts don't wrap either. 8675 SDNodeFlags Flags; 8676 Flags.setNoUnsignedWrap(true); 8677 8678 for (unsigned i = 0; i < NumValues; ++i) { 8679 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8680 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8681 PtrVT), Flags); 8682 SDValue L = CLI.DAG.getLoad( 8683 RetTys[i], CLI.DL, CLI.Chain, Add, 8684 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8685 DemoteStackIdx, Offsets[i]), 8686 /* Alignment = */ 1); 8687 ReturnValues[i] = L; 8688 Chains[i] = L.getValue(1); 8689 } 8690 8691 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8692 } else { 8693 // Collect the legal value parts into potentially illegal values 8694 // that correspond to the original function's return values. 8695 Optional<ISD::NodeType> AssertOp; 8696 if (CLI.RetSExt) 8697 AssertOp = ISD::AssertSext; 8698 else if (CLI.RetZExt) 8699 AssertOp = ISD::AssertZext; 8700 unsigned CurReg = 0; 8701 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8702 EVT VT = RetTys[I]; 8703 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8704 CLI.CallConv, VT); 8705 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8706 CLI.CallConv, VT); 8707 8708 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8709 NumRegs, RegisterVT, VT, nullptr, 8710 CLI.CallConv, AssertOp)); 8711 CurReg += NumRegs; 8712 } 8713 8714 // For a function returning void, there is no return value. We can't create 8715 // such a node, so we just return a null return value in that case. In 8716 // that case, nothing will actually look at the value. 8717 if (ReturnValues.empty()) 8718 return std::make_pair(SDValue(), CLI.Chain); 8719 } 8720 8721 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8722 CLI.DAG.getVTList(RetTys), ReturnValues); 8723 return std::make_pair(Res, CLI.Chain); 8724 } 8725 8726 void TargetLowering::LowerOperationWrapper(SDNode *N, 8727 SmallVectorImpl<SDValue> &Results, 8728 SelectionDAG &DAG) const { 8729 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8730 Results.push_back(Res); 8731 } 8732 8733 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8734 llvm_unreachable("LowerOperation not implemented for this target!"); 8735 } 8736 8737 void 8738 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8739 SDValue Op = getNonRegisterValue(V); 8740 assert((Op.getOpcode() != ISD::CopyFromReg || 8741 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8742 "Copy from a reg to the same reg!"); 8743 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8744 8745 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8746 // If this is an InlineAsm we have to match the registers required, not the 8747 // notional registers required by the type. 8748 8749 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 8750 None); // This is not an ABI copy. 8751 SDValue Chain = DAG.getEntryNode(); 8752 8753 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8754 FuncInfo.PreferredExtendType.end()) 8755 ? ISD::ANY_EXTEND 8756 : FuncInfo.PreferredExtendType[V]; 8757 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8758 PendingExports.push_back(Chain); 8759 } 8760 8761 #include "llvm/CodeGen/SelectionDAGISel.h" 8762 8763 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8764 /// entry block, return true. This includes arguments used by switches, since 8765 /// the switch may expand into multiple basic blocks. 8766 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8767 // With FastISel active, we may be splitting blocks, so force creation 8768 // of virtual registers for all non-dead arguments. 8769 if (FastISel) 8770 return A->use_empty(); 8771 8772 const BasicBlock &Entry = A->getParent()->front(); 8773 for (const User *U : A->users()) 8774 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8775 return false; // Use not in entry block. 8776 8777 return true; 8778 } 8779 8780 using ArgCopyElisionMapTy = 8781 DenseMap<const Argument *, 8782 std::pair<const AllocaInst *, const StoreInst *>>; 8783 8784 /// Scan the entry block of the function in FuncInfo for arguments that look 8785 /// like copies into a local alloca. Record any copied arguments in 8786 /// ArgCopyElisionCandidates. 8787 static void 8788 findArgumentCopyElisionCandidates(const DataLayout &DL, 8789 FunctionLoweringInfo *FuncInfo, 8790 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8791 // Record the state of every static alloca used in the entry block. Argument 8792 // allocas are all used in the entry block, so we need approximately as many 8793 // entries as we have arguments. 8794 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8795 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8796 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8797 StaticAllocas.reserve(NumArgs * 2); 8798 8799 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8800 if (!V) 8801 return nullptr; 8802 V = V->stripPointerCasts(); 8803 const auto *AI = dyn_cast<AllocaInst>(V); 8804 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8805 return nullptr; 8806 auto Iter = StaticAllocas.insert({AI, Unknown}); 8807 return &Iter.first->second; 8808 }; 8809 8810 // Look for stores of arguments to static allocas. Look through bitcasts and 8811 // GEPs to handle type coercions, as long as the alloca is fully initialized 8812 // by the store. Any non-store use of an alloca escapes it and any subsequent 8813 // unanalyzed store might write it. 8814 // FIXME: Handle structs initialized with multiple stores. 8815 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8816 // Look for stores, and handle non-store uses conservatively. 8817 const auto *SI = dyn_cast<StoreInst>(&I); 8818 if (!SI) { 8819 // We will look through cast uses, so ignore them completely. 8820 if (I.isCast()) 8821 continue; 8822 // Ignore debug info intrinsics, they don't escape or store to allocas. 8823 if (isa<DbgInfoIntrinsic>(I)) 8824 continue; 8825 // This is an unknown instruction. Assume it escapes or writes to all 8826 // static alloca operands. 8827 for (const Use &U : I.operands()) { 8828 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8829 *Info = StaticAllocaInfo::Clobbered; 8830 } 8831 continue; 8832 } 8833 8834 // If the stored value is a static alloca, mark it as escaped. 8835 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8836 *Info = StaticAllocaInfo::Clobbered; 8837 8838 // Check if the destination is a static alloca. 8839 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8840 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8841 if (!Info) 8842 continue; 8843 const AllocaInst *AI = cast<AllocaInst>(Dst); 8844 8845 // Skip allocas that have been initialized or clobbered. 8846 if (*Info != StaticAllocaInfo::Unknown) 8847 continue; 8848 8849 // Check if the stored value is an argument, and that this store fully 8850 // initializes the alloca. Don't elide copies from the same argument twice. 8851 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8852 const auto *Arg = dyn_cast<Argument>(Val); 8853 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8854 Arg->getType()->isEmptyTy() || 8855 DL.getTypeStoreSize(Arg->getType()) != 8856 DL.getTypeAllocSize(AI->getAllocatedType()) || 8857 ArgCopyElisionCandidates.count(Arg)) { 8858 *Info = StaticAllocaInfo::Clobbered; 8859 continue; 8860 } 8861 8862 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 8863 << '\n'); 8864 8865 // Mark this alloca and store for argument copy elision. 8866 *Info = StaticAllocaInfo::Elidable; 8867 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8868 8869 // Stop scanning if we've seen all arguments. This will happen early in -O0 8870 // builds, which is useful, because -O0 builds have large entry blocks and 8871 // many allocas. 8872 if (ArgCopyElisionCandidates.size() == NumArgs) 8873 break; 8874 } 8875 } 8876 8877 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8878 /// ArgVal is a load from a suitable fixed stack object. 8879 static void tryToElideArgumentCopy( 8880 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8881 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8882 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8883 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8884 SDValue ArgVal, bool &ArgHasUses) { 8885 // Check if this is a load from a fixed stack object. 8886 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8887 if (!LNode) 8888 return; 8889 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 8890 if (!FINode) 8891 return; 8892 8893 // Check that the fixed stack object is the right size and alignment. 8894 // Look at the alignment that the user wrote on the alloca instead of looking 8895 // at the stack object. 8896 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 8897 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 8898 const AllocaInst *AI = ArgCopyIter->second.first; 8899 int FixedIndex = FINode->getIndex(); 8900 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 8901 int OldIndex = AllocaIndex; 8902 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 8903 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 8904 LLVM_DEBUG( 8905 dbgs() << " argument copy elision failed due to bad fixed stack " 8906 "object size\n"); 8907 return; 8908 } 8909 unsigned RequiredAlignment = AI->getAlignment(); 8910 if (!RequiredAlignment) { 8911 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 8912 AI->getAllocatedType()); 8913 } 8914 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 8915 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 8916 "greater than stack argument alignment (" 8917 << RequiredAlignment << " vs " 8918 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 8919 return; 8920 } 8921 8922 // Perform the elision. Delete the old stack object and replace its only use 8923 // in the variable info map. Mark the stack object as mutable. 8924 LLVM_DEBUG({ 8925 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 8926 << " Replacing frame index " << OldIndex << " with " << FixedIndex 8927 << '\n'; 8928 }); 8929 MFI.RemoveStackObject(OldIndex); 8930 MFI.setIsImmutableObjectIndex(FixedIndex, false); 8931 AllocaIndex = FixedIndex; 8932 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 8933 Chains.push_back(ArgVal.getValue(1)); 8934 8935 // Avoid emitting code for the store implementing the copy. 8936 const StoreInst *SI = ArgCopyIter->second.second; 8937 ElidedArgCopyInstrs.insert(SI); 8938 8939 // Check for uses of the argument again so that we can avoid exporting ArgVal 8940 // if it is't used by anything other than the store. 8941 for (const Value *U : Arg.users()) { 8942 if (U != SI) { 8943 ArgHasUses = true; 8944 break; 8945 } 8946 } 8947 } 8948 8949 void SelectionDAGISel::LowerArguments(const Function &F) { 8950 SelectionDAG &DAG = SDB->DAG; 8951 SDLoc dl = SDB->getCurSDLoc(); 8952 const DataLayout &DL = DAG.getDataLayout(); 8953 SmallVector<ISD::InputArg, 16> Ins; 8954 8955 if (!FuncInfo->CanLowerReturn) { 8956 // Put in an sret pointer parameter before all the other parameters. 8957 SmallVector<EVT, 1> ValueVTs; 8958 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8959 F.getReturnType()->getPointerTo( 8960 DAG.getDataLayout().getAllocaAddrSpace()), 8961 ValueVTs); 8962 8963 // NOTE: Assuming that a pointer will never break down to more than one VT 8964 // or one register. 8965 ISD::ArgFlagsTy Flags; 8966 Flags.setSRet(); 8967 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 8968 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 8969 ISD::InputArg::NoArgIndex, 0); 8970 Ins.push_back(RetArg); 8971 } 8972 8973 // Look for stores of arguments to static allocas. Mark such arguments with a 8974 // flag to ask the target to give us the memory location of that argument if 8975 // available. 8976 ArgCopyElisionMapTy ArgCopyElisionCandidates; 8977 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 8978 8979 // Set up the incoming argument description vector. 8980 for (const Argument &Arg : F.args()) { 8981 unsigned ArgNo = Arg.getArgNo(); 8982 SmallVector<EVT, 4> ValueVTs; 8983 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 8984 bool isArgValueUsed = !Arg.use_empty(); 8985 unsigned PartBase = 0; 8986 Type *FinalType = Arg.getType(); 8987 if (Arg.hasAttribute(Attribute::ByVal)) 8988 FinalType = cast<PointerType>(FinalType)->getElementType(); 8989 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 8990 FinalType, F.getCallingConv(), F.isVarArg()); 8991 for (unsigned Value = 0, NumValues = ValueVTs.size(); 8992 Value != NumValues; ++Value) { 8993 EVT VT = ValueVTs[Value]; 8994 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 8995 ISD::ArgFlagsTy Flags; 8996 8997 // Certain targets (such as MIPS), may have a different ABI alignment 8998 // for a type depending on the context. Give the target a chance to 8999 // specify the alignment it wants. 9000 unsigned OriginalAlignment = 9001 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 9002 9003 if (Arg.hasAttribute(Attribute::ZExt)) 9004 Flags.setZExt(); 9005 if (Arg.hasAttribute(Attribute::SExt)) 9006 Flags.setSExt(); 9007 if (Arg.hasAttribute(Attribute::InReg)) { 9008 // If we are using vectorcall calling convention, a structure that is 9009 // passed InReg - is surely an HVA 9010 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9011 isa<StructType>(Arg.getType())) { 9012 // The first value of a structure is marked 9013 if (0 == Value) 9014 Flags.setHvaStart(); 9015 Flags.setHva(); 9016 } 9017 // Set InReg Flag 9018 Flags.setInReg(); 9019 } 9020 if (Arg.hasAttribute(Attribute::StructRet)) 9021 Flags.setSRet(); 9022 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9023 Flags.setSwiftSelf(); 9024 if (Arg.hasAttribute(Attribute::SwiftError)) 9025 Flags.setSwiftError(); 9026 if (Arg.hasAttribute(Attribute::ByVal)) 9027 Flags.setByVal(); 9028 if (Arg.hasAttribute(Attribute::InAlloca)) { 9029 Flags.setInAlloca(); 9030 // Set the byval flag for CCAssignFn callbacks that don't know about 9031 // inalloca. This way we can know how many bytes we should've allocated 9032 // and how many bytes a callee cleanup function will pop. If we port 9033 // inalloca to more targets, we'll have to add custom inalloca handling 9034 // in the various CC lowering callbacks. 9035 Flags.setByVal(); 9036 } 9037 if (F.getCallingConv() == CallingConv::X86_INTR) { 9038 // IA Interrupt passes frame (1st parameter) by value in the stack. 9039 if (ArgNo == 0) 9040 Flags.setByVal(); 9041 } 9042 if (Flags.isByVal() || Flags.isInAlloca()) { 9043 PointerType *Ty = cast<PointerType>(Arg.getType()); 9044 Type *ElementTy = Ty->getElementType(); 9045 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9046 // For ByVal, alignment should be passed from FE. BE will guess if 9047 // this info is not there but there are cases it cannot get right. 9048 unsigned FrameAlign; 9049 if (Arg.getParamAlignment()) 9050 FrameAlign = Arg.getParamAlignment(); 9051 else 9052 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9053 Flags.setByValAlign(FrameAlign); 9054 } 9055 if (Arg.hasAttribute(Attribute::Nest)) 9056 Flags.setNest(); 9057 if (NeedsRegBlock) 9058 Flags.setInConsecutiveRegs(); 9059 Flags.setOrigAlign(OriginalAlignment); 9060 if (ArgCopyElisionCandidates.count(&Arg)) 9061 Flags.setCopyElisionCandidate(); 9062 9063 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9064 *CurDAG->getContext(), F.getCallingConv(), VT); 9065 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9066 *CurDAG->getContext(), F.getCallingConv(), VT); 9067 for (unsigned i = 0; i != NumRegs; ++i) { 9068 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9069 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9070 if (NumRegs > 1 && i == 0) 9071 MyFlags.Flags.setSplit(); 9072 // if it isn't first piece, alignment must be 1 9073 else if (i > 0) { 9074 MyFlags.Flags.setOrigAlign(1); 9075 if (i == NumRegs - 1) 9076 MyFlags.Flags.setSplitEnd(); 9077 } 9078 Ins.push_back(MyFlags); 9079 } 9080 if (NeedsRegBlock && Value == NumValues - 1) 9081 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9082 PartBase += VT.getStoreSize(); 9083 } 9084 } 9085 9086 // Call the target to set up the argument values. 9087 SmallVector<SDValue, 8> InVals; 9088 SDValue NewRoot = TLI->LowerFormalArguments( 9089 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9090 9091 // Verify that the target's LowerFormalArguments behaved as expected. 9092 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9093 "LowerFormalArguments didn't return a valid chain!"); 9094 assert(InVals.size() == Ins.size() && 9095 "LowerFormalArguments didn't emit the correct number of values!"); 9096 LLVM_DEBUG({ 9097 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9098 assert(InVals[i].getNode() && 9099 "LowerFormalArguments emitted a null value!"); 9100 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9101 "LowerFormalArguments emitted a value with the wrong type!"); 9102 } 9103 }); 9104 9105 // Update the DAG with the new chain value resulting from argument lowering. 9106 DAG.setRoot(NewRoot); 9107 9108 // Set up the argument values. 9109 unsigned i = 0; 9110 if (!FuncInfo->CanLowerReturn) { 9111 // Create a virtual register for the sret pointer, and put in a copy 9112 // from the sret argument into it. 9113 SmallVector<EVT, 1> ValueVTs; 9114 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9115 F.getReturnType()->getPointerTo( 9116 DAG.getDataLayout().getAllocaAddrSpace()), 9117 ValueVTs); 9118 MVT VT = ValueVTs[0].getSimpleVT(); 9119 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9120 Optional<ISD::NodeType> AssertOp = None; 9121 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9122 nullptr, F.getCallingConv(), AssertOp); 9123 9124 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9125 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9126 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9127 FuncInfo->DemoteRegister = SRetReg; 9128 NewRoot = 9129 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9130 DAG.setRoot(NewRoot); 9131 9132 // i indexes lowered arguments. Bump it past the hidden sret argument. 9133 ++i; 9134 } 9135 9136 SmallVector<SDValue, 4> Chains; 9137 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9138 for (const Argument &Arg : F.args()) { 9139 SmallVector<SDValue, 4> ArgValues; 9140 SmallVector<EVT, 4> ValueVTs; 9141 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9142 unsigned NumValues = ValueVTs.size(); 9143 if (NumValues == 0) 9144 continue; 9145 9146 bool ArgHasUses = !Arg.use_empty(); 9147 9148 // Elide the copying store if the target loaded this argument from a 9149 // suitable fixed stack object. 9150 if (Ins[i].Flags.isCopyElisionCandidate()) { 9151 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9152 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9153 InVals[i], ArgHasUses); 9154 } 9155 9156 // If this argument is unused then remember its value. It is used to generate 9157 // debugging information. 9158 bool isSwiftErrorArg = 9159 TLI->supportSwiftError() && 9160 Arg.hasAttribute(Attribute::SwiftError); 9161 if (!ArgHasUses && !isSwiftErrorArg) { 9162 SDB->setUnusedArgValue(&Arg, InVals[i]); 9163 9164 // Also remember any frame index for use in FastISel. 9165 if (FrameIndexSDNode *FI = 9166 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9167 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9168 } 9169 9170 for (unsigned Val = 0; Val != NumValues; ++Val) { 9171 EVT VT = ValueVTs[Val]; 9172 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9173 F.getCallingConv(), VT); 9174 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9175 *CurDAG->getContext(), F.getCallingConv(), VT); 9176 9177 // Even an apparant 'unused' swifterror argument needs to be returned. So 9178 // we do generate a copy for it that can be used on return from the 9179 // function. 9180 if (ArgHasUses || isSwiftErrorArg) { 9181 Optional<ISD::NodeType> AssertOp; 9182 if (Arg.hasAttribute(Attribute::SExt)) 9183 AssertOp = ISD::AssertSext; 9184 else if (Arg.hasAttribute(Attribute::ZExt)) 9185 AssertOp = ISD::AssertZext; 9186 9187 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9188 PartVT, VT, nullptr, 9189 F.getCallingConv(), AssertOp)); 9190 } 9191 9192 i += NumParts; 9193 } 9194 9195 // We don't need to do anything else for unused arguments. 9196 if (ArgValues.empty()) 9197 continue; 9198 9199 // Note down frame index. 9200 if (FrameIndexSDNode *FI = 9201 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9202 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9203 9204 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9205 SDB->getCurSDLoc()); 9206 9207 SDB->setValue(&Arg, Res); 9208 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9209 // We want to associate the argument with the frame index, among 9210 // involved operands, that correspond to the lowest address. The 9211 // getCopyFromParts function, called earlier, is swapping the order of 9212 // the operands to BUILD_PAIR depending on endianness. The result of 9213 // that swapping is that the least significant bits of the argument will 9214 // be in the first operand of the BUILD_PAIR node, and the most 9215 // significant bits will be in the second operand. 9216 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9217 if (LoadSDNode *LNode = 9218 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9219 if (FrameIndexSDNode *FI = 9220 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9221 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9222 } 9223 9224 // Update the SwiftErrorVRegDefMap. 9225 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9226 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9227 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9228 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9229 FuncInfo->SwiftErrorArg, Reg); 9230 } 9231 9232 // If this argument is live outside of the entry block, insert a copy from 9233 // wherever we got it to the vreg that other BB's will reference it as. 9234 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9235 // If we can, though, try to skip creating an unnecessary vreg. 9236 // FIXME: This isn't very clean... it would be nice to make this more 9237 // general. It's also subtly incompatible with the hacks FastISel 9238 // uses with vregs. 9239 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9240 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9241 FuncInfo->ValueMap[&Arg] = Reg; 9242 continue; 9243 } 9244 } 9245 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9246 FuncInfo->InitializeRegForValue(&Arg); 9247 SDB->CopyToExportRegsIfNeeded(&Arg); 9248 } 9249 } 9250 9251 if (!Chains.empty()) { 9252 Chains.push_back(NewRoot); 9253 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9254 } 9255 9256 DAG.setRoot(NewRoot); 9257 9258 assert(i == InVals.size() && "Argument register count mismatch!"); 9259 9260 // If any argument copy elisions occurred and we have debug info, update the 9261 // stale frame indices used in the dbg.declare variable info table. 9262 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9263 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9264 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9265 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9266 if (I != ArgCopyElisionFrameIndexMap.end()) 9267 VI.Slot = I->second; 9268 } 9269 } 9270 9271 // Finally, if the target has anything special to do, allow it to do so. 9272 EmitFunctionEntryCode(); 9273 } 9274 9275 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9276 /// ensure constants are generated when needed. Remember the virtual registers 9277 /// that need to be added to the Machine PHI nodes as input. We cannot just 9278 /// directly add them, because expansion might result in multiple MBB's for one 9279 /// BB. As such, the start of the BB might correspond to a different MBB than 9280 /// the end. 9281 void 9282 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9283 const Instruction *TI = LLVMBB->getTerminator(); 9284 9285 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9286 9287 // Check PHI nodes in successors that expect a value to be available from this 9288 // block. 9289 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9290 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9291 if (!isa<PHINode>(SuccBB->begin())) continue; 9292 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9293 9294 // If this terminator has multiple identical successors (common for 9295 // switches), only handle each succ once. 9296 if (!SuccsHandled.insert(SuccMBB).second) 9297 continue; 9298 9299 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9300 9301 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9302 // nodes and Machine PHI nodes, but the incoming operands have not been 9303 // emitted yet. 9304 for (const PHINode &PN : SuccBB->phis()) { 9305 // Ignore dead phi's. 9306 if (PN.use_empty()) 9307 continue; 9308 9309 // Skip empty types 9310 if (PN.getType()->isEmptyTy()) 9311 continue; 9312 9313 unsigned Reg; 9314 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9315 9316 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9317 unsigned &RegOut = ConstantsOut[C]; 9318 if (RegOut == 0) { 9319 RegOut = FuncInfo.CreateRegs(C->getType()); 9320 CopyValueToVirtualRegister(C, RegOut); 9321 } 9322 Reg = RegOut; 9323 } else { 9324 DenseMap<const Value *, unsigned>::iterator I = 9325 FuncInfo.ValueMap.find(PHIOp); 9326 if (I != FuncInfo.ValueMap.end()) 9327 Reg = I->second; 9328 else { 9329 assert(isa<AllocaInst>(PHIOp) && 9330 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9331 "Didn't codegen value into a register!??"); 9332 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9333 CopyValueToVirtualRegister(PHIOp, Reg); 9334 } 9335 } 9336 9337 // Remember that this register needs to added to the machine PHI node as 9338 // the input for this MBB. 9339 SmallVector<EVT, 4> ValueVTs; 9340 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9341 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9342 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9343 EVT VT = ValueVTs[vti]; 9344 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9345 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9346 FuncInfo.PHINodesToUpdate.push_back( 9347 std::make_pair(&*MBBI++, Reg + i)); 9348 Reg += NumRegisters; 9349 } 9350 } 9351 } 9352 9353 ConstantsOut.clear(); 9354 } 9355 9356 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9357 /// is 0. 9358 MachineBasicBlock * 9359 SelectionDAGBuilder::StackProtectorDescriptor:: 9360 AddSuccessorMBB(const BasicBlock *BB, 9361 MachineBasicBlock *ParentMBB, 9362 bool IsLikely, 9363 MachineBasicBlock *SuccMBB) { 9364 // If SuccBB has not been created yet, create it. 9365 if (!SuccMBB) { 9366 MachineFunction *MF = ParentMBB->getParent(); 9367 MachineFunction::iterator BBI(ParentMBB); 9368 SuccMBB = MF->CreateMachineBasicBlock(BB); 9369 MF->insert(++BBI, SuccMBB); 9370 } 9371 // Add it as a successor of ParentMBB. 9372 ParentMBB->addSuccessor( 9373 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9374 return SuccMBB; 9375 } 9376 9377 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9378 MachineFunction::iterator I(MBB); 9379 if (++I == FuncInfo.MF->end()) 9380 return nullptr; 9381 return &*I; 9382 } 9383 9384 /// During lowering new call nodes can be created (such as memset, etc.). 9385 /// Those will become new roots of the current DAG, but complications arise 9386 /// when they are tail calls. In such cases, the call lowering will update 9387 /// the root, but the builder still needs to know that a tail call has been 9388 /// lowered in order to avoid generating an additional return. 9389 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9390 // If the node is null, we do have a tail call. 9391 if (MaybeTC.getNode() != nullptr) 9392 DAG.setRoot(MaybeTC); 9393 else 9394 HasTailCall = true; 9395 } 9396 9397 uint64_t 9398 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9399 unsigned First, unsigned Last) const { 9400 assert(Last >= First); 9401 const APInt &LowCase = Clusters[First].Low->getValue(); 9402 const APInt &HighCase = Clusters[Last].High->getValue(); 9403 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9404 9405 // FIXME: A range of consecutive cases has 100% density, but only requires one 9406 // comparison to lower. We should discriminate against such consecutive ranges 9407 // in jump tables. 9408 9409 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9410 } 9411 9412 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9413 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9414 unsigned Last) const { 9415 assert(Last >= First); 9416 assert(TotalCases[Last] >= TotalCases[First]); 9417 uint64_t NumCases = 9418 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9419 return NumCases; 9420 } 9421 9422 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9423 unsigned First, unsigned Last, 9424 const SwitchInst *SI, 9425 MachineBasicBlock *DefaultMBB, 9426 CaseCluster &JTCluster) { 9427 assert(First <= Last); 9428 9429 auto Prob = BranchProbability::getZero(); 9430 unsigned NumCmps = 0; 9431 std::vector<MachineBasicBlock*> Table; 9432 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9433 9434 // Initialize probabilities in JTProbs. 9435 for (unsigned I = First; I <= Last; ++I) 9436 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9437 9438 for (unsigned I = First; I <= Last; ++I) { 9439 assert(Clusters[I].Kind == CC_Range); 9440 Prob += Clusters[I].Prob; 9441 const APInt &Low = Clusters[I].Low->getValue(); 9442 const APInt &High = Clusters[I].High->getValue(); 9443 NumCmps += (Low == High) ? 1 : 2; 9444 if (I != First) { 9445 // Fill the gap between this and the previous cluster. 9446 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9447 assert(PreviousHigh.slt(Low)); 9448 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9449 for (uint64_t J = 0; J < Gap; J++) 9450 Table.push_back(DefaultMBB); 9451 } 9452 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9453 for (uint64_t J = 0; J < ClusterSize; ++J) 9454 Table.push_back(Clusters[I].MBB); 9455 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9456 } 9457 9458 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9459 unsigned NumDests = JTProbs.size(); 9460 if (TLI.isSuitableForBitTests( 9461 NumDests, NumCmps, Clusters[First].Low->getValue(), 9462 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9463 // Clusters[First..Last] should be lowered as bit tests instead. 9464 return false; 9465 } 9466 9467 // Create the MBB that will load from and jump through the table. 9468 // Note: We create it here, but it's not inserted into the function yet. 9469 MachineFunction *CurMF = FuncInfo.MF; 9470 MachineBasicBlock *JumpTableMBB = 9471 CurMF->CreateMachineBasicBlock(SI->getParent()); 9472 9473 // Add successors. Note: use table order for determinism. 9474 SmallPtrSet<MachineBasicBlock *, 8> Done; 9475 for (MachineBasicBlock *Succ : Table) { 9476 if (Done.count(Succ)) 9477 continue; 9478 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9479 Done.insert(Succ); 9480 } 9481 JumpTableMBB->normalizeSuccProbs(); 9482 9483 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9484 ->createJumpTableIndex(Table); 9485 9486 // Set up the jump table info. 9487 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9488 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9489 Clusters[Last].High->getValue(), SI->getCondition(), 9490 nullptr, false); 9491 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9492 9493 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9494 JTCases.size() - 1, Prob); 9495 return true; 9496 } 9497 9498 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9499 const SwitchInst *SI, 9500 MachineBasicBlock *DefaultMBB) { 9501 #ifndef NDEBUG 9502 // Clusters must be non-empty, sorted, and only contain Range clusters. 9503 assert(!Clusters.empty()); 9504 for (CaseCluster &C : Clusters) 9505 assert(C.Kind == CC_Range); 9506 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9507 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9508 #endif 9509 9510 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9511 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9512 return; 9513 9514 const int64_t N = Clusters.size(); 9515 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9516 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9517 9518 if (N < 2 || N < MinJumpTableEntries) 9519 return; 9520 9521 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9522 SmallVector<unsigned, 8> TotalCases(N); 9523 for (unsigned i = 0; i < N; ++i) { 9524 const APInt &Hi = Clusters[i].High->getValue(); 9525 const APInt &Lo = Clusters[i].Low->getValue(); 9526 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9527 if (i != 0) 9528 TotalCases[i] += TotalCases[i - 1]; 9529 } 9530 9531 // Cheap case: the whole range may be suitable for jump table. 9532 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9533 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9534 assert(NumCases < UINT64_MAX / 100); 9535 assert(Range >= NumCases); 9536 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9537 CaseCluster JTCluster; 9538 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9539 Clusters[0] = JTCluster; 9540 Clusters.resize(1); 9541 return; 9542 } 9543 } 9544 9545 // The algorithm below is not suitable for -O0. 9546 if (TM.getOptLevel() == CodeGenOpt::None) 9547 return; 9548 9549 // Split Clusters into minimum number of dense partitions. The algorithm uses 9550 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9551 // for the Case Statement'" (1994), but builds the MinPartitions array in 9552 // reverse order to make it easier to reconstruct the partitions in ascending 9553 // order. In the choice between two optimal partitionings, it picks the one 9554 // which yields more jump tables. 9555 9556 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9557 SmallVector<unsigned, 8> MinPartitions(N); 9558 // LastElement[i] is the last element of the partition starting at i. 9559 SmallVector<unsigned, 8> LastElement(N); 9560 // PartitionsScore[i] is used to break ties when choosing between two 9561 // partitionings resulting in the same number of partitions. 9562 SmallVector<unsigned, 8> PartitionsScore(N); 9563 // For PartitionsScore, a small number of comparisons is considered as good as 9564 // a jump table and a single comparison is considered better than a jump 9565 // table. 9566 enum PartitionScores : unsigned { 9567 NoTable = 0, 9568 Table = 1, 9569 FewCases = 1, 9570 SingleCase = 2 9571 }; 9572 9573 // Base case: There is only one way to partition Clusters[N-1]. 9574 MinPartitions[N - 1] = 1; 9575 LastElement[N - 1] = N - 1; 9576 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9577 9578 // Note: loop indexes are signed to avoid underflow. 9579 for (int64_t i = N - 2; i >= 0; i--) { 9580 // Find optimal partitioning of Clusters[i..N-1]. 9581 // Baseline: Put Clusters[i] into a partition on its own. 9582 MinPartitions[i] = MinPartitions[i + 1] + 1; 9583 LastElement[i] = i; 9584 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9585 9586 // Search for a solution that results in fewer partitions. 9587 for (int64_t j = N - 1; j > i; j--) { 9588 // Try building a partition from Clusters[i..j]. 9589 uint64_t Range = getJumpTableRange(Clusters, i, j); 9590 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9591 assert(NumCases < UINT64_MAX / 100); 9592 assert(Range >= NumCases); 9593 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9594 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9595 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9596 int64_t NumEntries = j - i + 1; 9597 9598 if (NumEntries == 1) 9599 Score += PartitionScores::SingleCase; 9600 else if (NumEntries <= SmallNumberOfEntries) 9601 Score += PartitionScores::FewCases; 9602 else if (NumEntries >= MinJumpTableEntries) 9603 Score += PartitionScores::Table; 9604 9605 // If this leads to fewer partitions, or to the same number of 9606 // partitions with better score, it is a better partitioning. 9607 if (NumPartitions < MinPartitions[i] || 9608 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9609 MinPartitions[i] = NumPartitions; 9610 LastElement[i] = j; 9611 PartitionsScore[i] = Score; 9612 } 9613 } 9614 } 9615 } 9616 9617 // Iterate over the partitions, replacing some with jump tables in-place. 9618 unsigned DstIndex = 0; 9619 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9620 Last = LastElement[First]; 9621 assert(Last >= First); 9622 assert(DstIndex <= First); 9623 unsigned NumClusters = Last - First + 1; 9624 9625 CaseCluster JTCluster; 9626 if (NumClusters >= MinJumpTableEntries && 9627 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9628 Clusters[DstIndex++] = JTCluster; 9629 } else { 9630 for (unsigned I = First; I <= Last; ++I) 9631 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9632 } 9633 } 9634 Clusters.resize(DstIndex); 9635 } 9636 9637 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9638 unsigned First, unsigned Last, 9639 const SwitchInst *SI, 9640 CaseCluster &BTCluster) { 9641 assert(First <= Last); 9642 if (First == Last) 9643 return false; 9644 9645 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9646 unsigned NumCmps = 0; 9647 for (int64_t I = First; I <= Last; ++I) { 9648 assert(Clusters[I].Kind == CC_Range); 9649 Dests.set(Clusters[I].MBB->getNumber()); 9650 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9651 } 9652 unsigned NumDests = Dests.count(); 9653 9654 APInt Low = Clusters[First].Low->getValue(); 9655 APInt High = Clusters[Last].High->getValue(); 9656 assert(Low.slt(High)); 9657 9658 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9659 const DataLayout &DL = DAG.getDataLayout(); 9660 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9661 return false; 9662 9663 APInt LowBound; 9664 APInt CmpRange; 9665 9666 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9667 assert(TLI.rangeFitsInWord(Low, High, DL) && 9668 "Case range must fit in bit mask!"); 9669 9670 // Check if the clusters cover a contiguous range such that no value in the 9671 // range will jump to the default statement. 9672 bool ContiguousRange = true; 9673 for (int64_t I = First + 1; I <= Last; ++I) { 9674 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9675 ContiguousRange = false; 9676 break; 9677 } 9678 } 9679 9680 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9681 // Optimize the case where all the case values fit in a word without having 9682 // to subtract minValue. In this case, we can optimize away the subtraction. 9683 LowBound = APInt::getNullValue(Low.getBitWidth()); 9684 CmpRange = High; 9685 ContiguousRange = false; 9686 } else { 9687 LowBound = Low; 9688 CmpRange = High - Low; 9689 } 9690 9691 CaseBitsVector CBV; 9692 auto TotalProb = BranchProbability::getZero(); 9693 for (unsigned i = First; i <= Last; ++i) { 9694 // Find the CaseBits for this destination. 9695 unsigned j; 9696 for (j = 0; j < CBV.size(); ++j) 9697 if (CBV[j].BB == Clusters[i].MBB) 9698 break; 9699 if (j == CBV.size()) 9700 CBV.push_back( 9701 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9702 CaseBits *CB = &CBV[j]; 9703 9704 // Update Mask, Bits and ExtraProb. 9705 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9706 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9707 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9708 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9709 CB->Bits += Hi - Lo + 1; 9710 CB->ExtraProb += Clusters[i].Prob; 9711 TotalProb += Clusters[i].Prob; 9712 } 9713 9714 BitTestInfo BTI; 9715 llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) { 9716 // Sort by probability first, number of bits second, bit mask third. 9717 if (a.ExtraProb != b.ExtraProb) 9718 return a.ExtraProb > b.ExtraProb; 9719 if (a.Bits != b.Bits) 9720 return a.Bits > b.Bits; 9721 return a.Mask < b.Mask; 9722 }); 9723 9724 for (auto &CB : CBV) { 9725 MachineBasicBlock *BitTestBB = 9726 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9727 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9728 } 9729 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9730 SI->getCondition(), -1U, MVT::Other, false, 9731 ContiguousRange, nullptr, nullptr, std::move(BTI), 9732 TotalProb); 9733 9734 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9735 BitTestCases.size() - 1, TotalProb); 9736 return true; 9737 } 9738 9739 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9740 const SwitchInst *SI) { 9741 // Partition Clusters into as few subsets as possible, where each subset has a 9742 // range that fits in a machine word and has <= 3 unique destinations. 9743 9744 #ifndef NDEBUG 9745 // Clusters must be sorted and contain Range or JumpTable clusters. 9746 assert(!Clusters.empty()); 9747 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9748 for (const CaseCluster &C : Clusters) 9749 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9750 for (unsigned i = 1; i < Clusters.size(); ++i) 9751 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9752 #endif 9753 9754 // The algorithm below is not suitable for -O0. 9755 if (TM.getOptLevel() == CodeGenOpt::None) 9756 return; 9757 9758 // If target does not have legal shift left, do not emit bit tests at all. 9759 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9760 const DataLayout &DL = DAG.getDataLayout(); 9761 9762 EVT PTy = TLI.getPointerTy(DL); 9763 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9764 return; 9765 9766 int BitWidth = PTy.getSizeInBits(); 9767 const int64_t N = Clusters.size(); 9768 9769 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9770 SmallVector<unsigned, 8> MinPartitions(N); 9771 // LastElement[i] is the last element of the partition starting at i. 9772 SmallVector<unsigned, 8> LastElement(N); 9773 9774 // FIXME: This might not be the best algorithm for finding bit test clusters. 9775 9776 // Base case: There is only one way to partition Clusters[N-1]. 9777 MinPartitions[N - 1] = 1; 9778 LastElement[N - 1] = N - 1; 9779 9780 // Note: loop indexes are signed to avoid underflow. 9781 for (int64_t i = N - 2; i >= 0; --i) { 9782 // Find optimal partitioning of Clusters[i..N-1]. 9783 // Baseline: Put Clusters[i] into a partition on its own. 9784 MinPartitions[i] = MinPartitions[i + 1] + 1; 9785 LastElement[i] = i; 9786 9787 // Search for a solution that results in fewer partitions. 9788 // Note: the search is limited by BitWidth, reducing time complexity. 9789 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9790 // Try building a partition from Clusters[i..j]. 9791 9792 // Check the range. 9793 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9794 Clusters[j].High->getValue(), DL)) 9795 continue; 9796 9797 // Check nbr of destinations and cluster types. 9798 // FIXME: This works, but doesn't seem very efficient. 9799 bool RangesOnly = true; 9800 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9801 for (int64_t k = i; k <= j; k++) { 9802 if (Clusters[k].Kind != CC_Range) { 9803 RangesOnly = false; 9804 break; 9805 } 9806 Dests.set(Clusters[k].MBB->getNumber()); 9807 } 9808 if (!RangesOnly || Dests.count() > 3) 9809 break; 9810 9811 // Check if it's a better partition. 9812 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9813 if (NumPartitions < MinPartitions[i]) { 9814 // Found a better partition. 9815 MinPartitions[i] = NumPartitions; 9816 LastElement[i] = j; 9817 } 9818 } 9819 } 9820 9821 // Iterate over the partitions, replacing with bit-test clusters in-place. 9822 unsigned DstIndex = 0; 9823 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9824 Last = LastElement[First]; 9825 assert(First <= Last); 9826 assert(DstIndex <= First); 9827 9828 CaseCluster BitTestCluster; 9829 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9830 Clusters[DstIndex++] = BitTestCluster; 9831 } else { 9832 size_t NumClusters = Last - First + 1; 9833 std::memmove(&Clusters[DstIndex], &Clusters[First], 9834 sizeof(Clusters[0]) * NumClusters); 9835 DstIndex += NumClusters; 9836 } 9837 } 9838 Clusters.resize(DstIndex); 9839 } 9840 9841 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9842 MachineBasicBlock *SwitchMBB, 9843 MachineBasicBlock *DefaultMBB) { 9844 MachineFunction *CurMF = FuncInfo.MF; 9845 MachineBasicBlock *NextMBB = nullptr; 9846 MachineFunction::iterator BBI(W.MBB); 9847 if (++BBI != FuncInfo.MF->end()) 9848 NextMBB = &*BBI; 9849 9850 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9851 9852 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9853 9854 if (Size == 2 && W.MBB == SwitchMBB) { 9855 // If any two of the cases has the same destination, and if one value 9856 // is the same as the other, but has one bit unset that the other has set, 9857 // use bit manipulation to do two compares at once. For example: 9858 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9859 // TODO: This could be extended to merge any 2 cases in switches with 3 9860 // cases. 9861 // TODO: Handle cases where W.CaseBB != SwitchBB. 9862 CaseCluster &Small = *W.FirstCluster; 9863 CaseCluster &Big = *W.LastCluster; 9864 9865 if (Small.Low == Small.High && Big.Low == Big.High && 9866 Small.MBB == Big.MBB) { 9867 const APInt &SmallValue = Small.Low->getValue(); 9868 const APInt &BigValue = Big.Low->getValue(); 9869 9870 // Check that there is only one bit different. 9871 APInt CommonBit = BigValue ^ SmallValue; 9872 if (CommonBit.isPowerOf2()) { 9873 SDValue CondLHS = getValue(Cond); 9874 EVT VT = CondLHS.getValueType(); 9875 SDLoc DL = getCurSDLoc(); 9876 9877 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9878 DAG.getConstant(CommonBit, DL, VT)); 9879 SDValue Cond = DAG.getSetCC( 9880 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9881 ISD::SETEQ); 9882 9883 // Update successor info. 9884 // Both Small and Big will jump to Small.BB, so we sum up the 9885 // probabilities. 9886 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9887 if (BPI) 9888 addSuccessorWithProb( 9889 SwitchMBB, DefaultMBB, 9890 // The default destination is the first successor in IR. 9891 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 9892 else 9893 addSuccessorWithProb(SwitchMBB, DefaultMBB); 9894 9895 // Insert the true branch. 9896 SDValue BrCond = 9897 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 9898 DAG.getBasicBlock(Small.MBB)); 9899 // Insert the false branch. 9900 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 9901 DAG.getBasicBlock(DefaultMBB)); 9902 9903 DAG.setRoot(BrCond); 9904 return; 9905 } 9906 } 9907 } 9908 9909 if (TM.getOptLevel() != CodeGenOpt::None) { 9910 // Here, we order cases by probability so the most likely case will be 9911 // checked first. However, two clusters can have the same probability in 9912 // which case their relative ordering is non-deterministic. So we use Low 9913 // as a tie-breaker as clusters are guaranteed to never overlap. 9914 llvm::sort(W.FirstCluster, W.LastCluster + 1, 9915 [](const CaseCluster &a, const CaseCluster &b) { 9916 return a.Prob != b.Prob ? 9917 a.Prob > b.Prob : 9918 a.Low->getValue().slt(b.Low->getValue()); 9919 }); 9920 9921 // Rearrange the case blocks so that the last one falls through if possible 9922 // without changing the order of probabilities. 9923 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 9924 --I; 9925 if (I->Prob > W.LastCluster->Prob) 9926 break; 9927 if (I->Kind == CC_Range && I->MBB == NextMBB) { 9928 std::swap(*I, *W.LastCluster); 9929 break; 9930 } 9931 } 9932 } 9933 9934 // Compute total probability. 9935 BranchProbability DefaultProb = W.DefaultProb; 9936 BranchProbability UnhandledProbs = DefaultProb; 9937 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 9938 UnhandledProbs += I->Prob; 9939 9940 MachineBasicBlock *CurMBB = W.MBB; 9941 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 9942 MachineBasicBlock *Fallthrough; 9943 if (I == W.LastCluster) { 9944 // For the last cluster, fall through to the default destination. 9945 Fallthrough = DefaultMBB; 9946 } else { 9947 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 9948 CurMF->insert(BBI, Fallthrough); 9949 // Put Cond in a virtual register to make it available from the new blocks. 9950 ExportFromCurrentBlock(Cond); 9951 } 9952 UnhandledProbs -= I->Prob; 9953 9954 switch (I->Kind) { 9955 case CC_JumpTable: { 9956 // FIXME: Optimize away range check based on pivot comparisons. 9957 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 9958 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 9959 9960 // The jump block hasn't been inserted yet; insert it here. 9961 MachineBasicBlock *JumpMBB = JT->MBB; 9962 CurMF->insert(BBI, JumpMBB); 9963 9964 auto JumpProb = I->Prob; 9965 auto FallthroughProb = UnhandledProbs; 9966 9967 // If the default statement is a target of the jump table, we evenly 9968 // distribute the default probability to successors of CurMBB. Also 9969 // update the probability on the edge from JumpMBB to Fallthrough. 9970 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 9971 SE = JumpMBB->succ_end(); 9972 SI != SE; ++SI) { 9973 if (*SI == DefaultMBB) { 9974 JumpProb += DefaultProb / 2; 9975 FallthroughProb -= DefaultProb / 2; 9976 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 9977 JumpMBB->normalizeSuccProbs(); 9978 break; 9979 } 9980 } 9981 9982 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 9983 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 9984 CurMBB->normalizeSuccProbs(); 9985 9986 // The jump table header will be inserted in our current block, do the 9987 // range check, and fall through to our fallthrough block. 9988 JTH->HeaderBB = CurMBB; 9989 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 9990 9991 // If we're in the right place, emit the jump table header right now. 9992 if (CurMBB == SwitchMBB) { 9993 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 9994 JTH->Emitted = true; 9995 } 9996 break; 9997 } 9998 case CC_BitTests: { 9999 // FIXME: Optimize away range check based on pivot comparisons. 10000 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 10001 10002 // The bit test blocks haven't been inserted yet; insert them here. 10003 for (BitTestCase &BTC : BTB->Cases) 10004 CurMF->insert(BBI, BTC.ThisBB); 10005 10006 // Fill in fields of the BitTestBlock. 10007 BTB->Parent = CurMBB; 10008 BTB->Default = Fallthrough; 10009 10010 BTB->DefaultProb = UnhandledProbs; 10011 // If the cases in bit test don't form a contiguous range, we evenly 10012 // distribute the probability on the edge to Fallthrough to two 10013 // successors of CurMBB. 10014 if (!BTB->ContiguousRange) { 10015 BTB->Prob += DefaultProb / 2; 10016 BTB->DefaultProb -= DefaultProb / 2; 10017 } 10018 10019 // If we're in the right place, emit the bit test header right now. 10020 if (CurMBB == SwitchMBB) { 10021 visitBitTestHeader(*BTB, SwitchMBB); 10022 BTB->Emitted = true; 10023 } 10024 break; 10025 } 10026 case CC_Range: { 10027 const Value *RHS, *LHS, *MHS; 10028 ISD::CondCode CC; 10029 if (I->Low == I->High) { 10030 // Check Cond == I->Low. 10031 CC = ISD::SETEQ; 10032 LHS = Cond; 10033 RHS=I->Low; 10034 MHS = nullptr; 10035 } else { 10036 // Check I->Low <= Cond <= I->High. 10037 CC = ISD::SETLE; 10038 LHS = I->Low; 10039 MHS = Cond; 10040 RHS = I->High; 10041 } 10042 10043 // The false probability is the sum of all unhandled cases. 10044 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10045 getCurSDLoc(), I->Prob, UnhandledProbs); 10046 10047 if (CurMBB == SwitchMBB) 10048 visitSwitchCase(CB, SwitchMBB); 10049 else 10050 SwitchCases.push_back(CB); 10051 10052 break; 10053 } 10054 } 10055 CurMBB = Fallthrough; 10056 } 10057 } 10058 10059 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10060 CaseClusterIt First, 10061 CaseClusterIt Last) { 10062 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10063 if (X.Prob != CC.Prob) 10064 return X.Prob > CC.Prob; 10065 10066 // Ties are broken by comparing the case value. 10067 return X.Low->getValue().slt(CC.Low->getValue()); 10068 }); 10069 } 10070 10071 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10072 const SwitchWorkListItem &W, 10073 Value *Cond, 10074 MachineBasicBlock *SwitchMBB) { 10075 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10076 "Clusters not sorted?"); 10077 10078 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10079 10080 // Balance the tree based on branch probabilities to create a near-optimal (in 10081 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10082 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10083 CaseClusterIt LastLeft = W.FirstCluster; 10084 CaseClusterIt FirstRight = W.LastCluster; 10085 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10086 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10087 10088 // Move LastLeft and FirstRight towards each other from opposite directions to 10089 // find a partitioning of the clusters which balances the probability on both 10090 // sides. If LeftProb and RightProb are equal, alternate which side is 10091 // taken to ensure 0-probability nodes are distributed evenly. 10092 unsigned I = 0; 10093 while (LastLeft + 1 < FirstRight) { 10094 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10095 LeftProb += (++LastLeft)->Prob; 10096 else 10097 RightProb += (--FirstRight)->Prob; 10098 I++; 10099 } 10100 10101 while (true) { 10102 // Our binary search tree differs from a typical BST in that ours can have up 10103 // to three values in each leaf. The pivot selection above doesn't take that 10104 // into account, which means the tree might require more nodes and be less 10105 // efficient. We compensate for this here. 10106 10107 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10108 unsigned NumRight = W.LastCluster - FirstRight + 1; 10109 10110 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10111 // If one side has less than 3 clusters, and the other has more than 3, 10112 // consider taking a cluster from the other side. 10113 10114 if (NumLeft < NumRight) { 10115 // Consider moving the first cluster on the right to the left side. 10116 CaseCluster &CC = *FirstRight; 10117 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10118 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10119 if (LeftSideRank <= RightSideRank) { 10120 // Moving the cluster to the left does not demote it. 10121 ++LastLeft; 10122 ++FirstRight; 10123 continue; 10124 } 10125 } else { 10126 assert(NumRight < NumLeft); 10127 // Consider moving the last element on the left to the right side. 10128 CaseCluster &CC = *LastLeft; 10129 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10130 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10131 if (RightSideRank <= LeftSideRank) { 10132 // Moving the cluster to the right does not demot it. 10133 --LastLeft; 10134 --FirstRight; 10135 continue; 10136 } 10137 } 10138 } 10139 break; 10140 } 10141 10142 assert(LastLeft + 1 == FirstRight); 10143 assert(LastLeft >= W.FirstCluster); 10144 assert(FirstRight <= W.LastCluster); 10145 10146 // Use the first element on the right as pivot since we will make less-than 10147 // comparisons against it. 10148 CaseClusterIt PivotCluster = FirstRight; 10149 assert(PivotCluster > W.FirstCluster); 10150 assert(PivotCluster <= W.LastCluster); 10151 10152 CaseClusterIt FirstLeft = W.FirstCluster; 10153 CaseClusterIt LastRight = W.LastCluster; 10154 10155 const ConstantInt *Pivot = PivotCluster->Low; 10156 10157 // New blocks will be inserted immediately after the current one. 10158 MachineFunction::iterator BBI(W.MBB); 10159 ++BBI; 10160 10161 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10162 // we can branch to its destination directly if it's squeezed exactly in 10163 // between the known lower bound and Pivot - 1. 10164 MachineBasicBlock *LeftMBB; 10165 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10166 FirstLeft->Low == W.GE && 10167 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10168 LeftMBB = FirstLeft->MBB; 10169 } else { 10170 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10171 FuncInfo.MF->insert(BBI, LeftMBB); 10172 WorkList.push_back( 10173 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10174 // Put Cond in a virtual register to make it available from the new blocks. 10175 ExportFromCurrentBlock(Cond); 10176 } 10177 10178 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10179 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10180 // directly if RHS.High equals the current upper bound. 10181 MachineBasicBlock *RightMBB; 10182 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10183 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10184 RightMBB = FirstRight->MBB; 10185 } else { 10186 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10187 FuncInfo.MF->insert(BBI, RightMBB); 10188 WorkList.push_back( 10189 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10190 // Put Cond in a virtual register to make it available from the new blocks. 10191 ExportFromCurrentBlock(Cond); 10192 } 10193 10194 // Create the CaseBlock record that will be used to lower the branch. 10195 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10196 getCurSDLoc(), LeftProb, RightProb); 10197 10198 if (W.MBB == SwitchMBB) 10199 visitSwitchCase(CB, SwitchMBB); 10200 else 10201 SwitchCases.push_back(CB); 10202 } 10203 10204 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10205 // from the swith statement. 10206 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10207 BranchProbability PeeledCaseProb) { 10208 if (PeeledCaseProb == BranchProbability::getOne()) 10209 return BranchProbability::getZero(); 10210 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10211 10212 uint32_t Numerator = CaseProb.getNumerator(); 10213 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10214 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10215 } 10216 10217 // Try to peel the top probability case if it exceeds the threshold. 10218 // Return current MachineBasicBlock for the switch statement if the peeling 10219 // does not occur. 10220 // If the peeling is performed, return the newly created MachineBasicBlock 10221 // for the peeled switch statement. Also update Clusters to remove the peeled 10222 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10223 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10224 const SwitchInst &SI, CaseClusterVector &Clusters, 10225 BranchProbability &PeeledCaseProb) { 10226 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10227 // Don't perform if there is only one cluster or optimizing for size. 10228 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10229 TM.getOptLevel() == CodeGenOpt::None || 10230 SwitchMBB->getParent()->getFunction().optForMinSize()) 10231 return SwitchMBB; 10232 10233 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10234 unsigned PeeledCaseIndex = 0; 10235 bool SwitchPeeled = false; 10236 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10237 CaseCluster &CC = Clusters[Index]; 10238 if (CC.Prob < TopCaseProb) 10239 continue; 10240 TopCaseProb = CC.Prob; 10241 PeeledCaseIndex = Index; 10242 SwitchPeeled = true; 10243 } 10244 if (!SwitchPeeled) 10245 return SwitchMBB; 10246 10247 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10248 << TopCaseProb << "\n"); 10249 10250 // Record the MBB for the peeled switch statement. 10251 MachineFunction::iterator BBI(SwitchMBB); 10252 ++BBI; 10253 MachineBasicBlock *PeeledSwitchMBB = 10254 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10255 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10256 10257 ExportFromCurrentBlock(SI.getCondition()); 10258 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10259 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10260 nullptr, nullptr, TopCaseProb.getCompl()}; 10261 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10262 10263 Clusters.erase(PeeledCaseIt); 10264 for (CaseCluster &CC : Clusters) { 10265 LLVM_DEBUG( 10266 dbgs() << "Scale the probablity for one cluster, before scaling: " 10267 << CC.Prob << "\n"); 10268 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10269 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10270 } 10271 PeeledCaseProb = TopCaseProb; 10272 return PeeledSwitchMBB; 10273 } 10274 10275 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10276 // Extract cases from the switch. 10277 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10278 CaseClusterVector Clusters; 10279 Clusters.reserve(SI.getNumCases()); 10280 for (auto I : SI.cases()) { 10281 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10282 const ConstantInt *CaseVal = I.getCaseValue(); 10283 BranchProbability Prob = 10284 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10285 : BranchProbability(1, SI.getNumCases() + 1); 10286 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10287 } 10288 10289 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10290 10291 // Cluster adjacent cases with the same destination. We do this at all 10292 // optimization levels because it's cheap to do and will make codegen faster 10293 // if there are many clusters. 10294 sortAndRangeify(Clusters); 10295 10296 if (TM.getOptLevel() != CodeGenOpt::None) { 10297 // Replace an unreachable default with the most popular destination. 10298 // FIXME: Exploit unreachable default more aggressively. 10299 bool UnreachableDefault = 10300 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 10301 if (UnreachableDefault && !Clusters.empty()) { 10302 DenseMap<const BasicBlock *, unsigned> Popularity; 10303 unsigned MaxPop = 0; 10304 const BasicBlock *MaxBB = nullptr; 10305 for (auto I : SI.cases()) { 10306 const BasicBlock *BB = I.getCaseSuccessor(); 10307 if (++Popularity[BB] > MaxPop) { 10308 MaxPop = Popularity[BB]; 10309 MaxBB = BB; 10310 } 10311 } 10312 // Set new default. 10313 assert(MaxPop > 0 && MaxBB); 10314 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 10315 10316 // Remove cases that were pointing to the destination that is now the 10317 // default. 10318 CaseClusterVector New; 10319 New.reserve(Clusters.size()); 10320 for (CaseCluster &CC : Clusters) { 10321 if (CC.MBB != DefaultMBB) 10322 New.push_back(CC); 10323 } 10324 Clusters = std::move(New); 10325 } 10326 } 10327 10328 // The branch probablity of the peeled case. 10329 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10330 MachineBasicBlock *PeeledSwitchMBB = 10331 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10332 10333 // If there is only the default destination, jump there directly. 10334 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10335 if (Clusters.empty()) { 10336 assert(PeeledSwitchMBB == SwitchMBB); 10337 SwitchMBB->addSuccessor(DefaultMBB); 10338 if (DefaultMBB != NextBlock(SwitchMBB)) { 10339 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10340 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10341 } 10342 return; 10343 } 10344 10345 findJumpTables(Clusters, &SI, DefaultMBB); 10346 findBitTestClusters(Clusters, &SI); 10347 10348 LLVM_DEBUG({ 10349 dbgs() << "Case clusters: "; 10350 for (const CaseCluster &C : Clusters) { 10351 if (C.Kind == CC_JumpTable) 10352 dbgs() << "JT:"; 10353 if (C.Kind == CC_BitTests) 10354 dbgs() << "BT:"; 10355 10356 C.Low->getValue().print(dbgs(), true); 10357 if (C.Low != C.High) { 10358 dbgs() << '-'; 10359 C.High->getValue().print(dbgs(), true); 10360 } 10361 dbgs() << ' '; 10362 } 10363 dbgs() << '\n'; 10364 }); 10365 10366 assert(!Clusters.empty()); 10367 SwitchWorkList WorkList; 10368 CaseClusterIt First = Clusters.begin(); 10369 CaseClusterIt Last = Clusters.end() - 1; 10370 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10371 // Scale the branchprobability for DefaultMBB if the peel occurs and 10372 // DefaultMBB is not replaced. 10373 if (PeeledCaseProb != BranchProbability::getZero() && 10374 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10375 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10376 WorkList.push_back( 10377 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10378 10379 while (!WorkList.empty()) { 10380 SwitchWorkListItem W = WorkList.back(); 10381 WorkList.pop_back(); 10382 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10383 10384 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10385 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10386 // For optimized builds, lower large range as a balanced binary tree. 10387 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10388 continue; 10389 } 10390 10391 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10392 } 10393 } 10394