1 //===-- InstrinsicInst.cpp - Intrinsic Instruction Wrappers ---------------===// 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 file implements methods that make it really easy to deal with intrinsic 10 // functions. 11 // 12 // All intrinsic function calls are instances of the call instruction, so these 13 // are all subclasses of the CallInst class. Note that none of these classes 14 // has state or virtual methods, which is an important part of this gross/neat 15 // hack working. 16 // 17 // In some cases, arguments to intrinsics need to be generic and are defined as 18 // type pointer to empty struct { }*. To access the real item of interest the 19 // cast instruction needs to be stripped away. 20 // 21 //===----------------------------------------------------------------------===// 22 23 #include "llvm/IR/IntrinsicInst.h" 24 #include "llvm/ADT/StringSwitch.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DebugInfoMetadata.h" 27 #include "llvm/IR/GlobalVariable.h" 28 #include "llvm/IR/Metadata.h" 29 #include "llvm/IR/Module.h" 30 #include "llvm/IR/Operator.h" 31 #include "llvm/IR/PatternMatch.h" 32 #include "llvm/IR/Statepoint.h" 33 34 #include "llvm/Support/raw_ostream.h" 35 using namespace llvm; 36 37 //===----------------------------------------------------------------------===// 38 /// DbgVariableIntrinsic - This is the common base class for debug info 39 /// intrinsics for variables. 40 /// 41 42 iterator_range<DbgVariableIntrinsic::location_op_iterator> 43 DbgVariableIntrinsic::location_ops() const { 44 auto *MD = getRawLocation(); 45 assert(MD && "First operand of DbgVariableIntrinsic should be non-null."); 46 47 // If operand is ValueAsMetadata, return a range over just that operand. 48 if (auto *VAM = dyn_cast<ValueAsMetadata>(MD)) { 49 return {location_op_iterator(VAM), location_op_iterator(VAM + 1)}; 50 } 51 // If operand is DIArgList, return a range over its args. 52 if (auto *AL = dyn_cast<DIArgList>(MD)) 53 return {location_op_iterator(AL->args_begin()), 54 location_op_iterator(AL->args_end())}; 55 // Operand must be an empty metadata tuple, so return empty iterator. 56 return {location_op_iterator(static_cast<ValueAsMetadata *>(nullptr)), 57 location_op_iterator(static_cast<ValueAsMetadata *>(nullptr))}; 58 } 59 60 Value *DbgVariableIntrinsic::getVariableLocationOp(unsigned OpIdx) const { 61 auto *MD = getRawLocation(); 62 assert(MD && "First operand of DbgVariableIntrinsic should be non-null."); 63 if (auto *AL = dyn_cast<DIArgList>(MD)) 64 return AL->getArgs()[OpIdx]->getValue(); 65 if (isa<MDNode>(MD)) 66 return nullptr; 67 assert( 68 isa<ValueAsMetadata>(MD) && 69 "Attempted to get location operand from DbgVariableIntrinsic with none."); 70 auto *V = cast<ValueAsMetadata>(MD); 71 assert(OpIdx == 0 && "Operand Index must be 0 for a debug intrinsic with a " 72 "single location operand."); 73 return V->getValue(); 74 } 75 76 static ValueAsMetadata *getAsMetadata(Value *V) { 77 return isa<MetadataAsValue>(V) ? dyn_cast<ValueAsMetadata>( 78 cast<MetadataAsValue>(V)->getMetadata()) 79 : ValueAsMetadata::get(V); 80 } 81 82 void DbgVariableIntrinsic::replaceVariableLocationOp(Value *OldValue, 83 Value *NewValue) { 84 assert(NewValue && "Values must be non-null"); 85 auto Locations = location_ops(); 86 auto OldIt = find(Locations, OldValue); 87 assert(OldIt != Locations.end() && "OldValue must be a current location"); 88 if (!hasArgList()) { 89 Value *NewOperand = isa<MetadataAsValue>(NewValue) 90 ? NewValue 91 : MetadataAsValue::get( 92 getContext(), ValueAsMetadata::get(NewValue)); 93 return setArgOperand(0, NewOperand); 94 } 95 SmallVector<ValueAsMetadata *, 4> MDs; 96 ValueAsMetadata *NewOperand = getAsMetadata(NewValue); 97 for (auto *VMD : Locations) 98 MDs.push_back(VMD == *OldIt ? NewOperand : getAsMetadata(VMD)); 99 setArgOperand( 100 0, MetadataAsValue::get(getContext(), DIArgList::get(getContext(), MDs))); 101 } 102 void DbgVariableIntrinsic::replaceVariableLocationOp(unsigned OpIdx, 103 Value *NewValue) { 104 assert(OpIdx < getNumVariableLocationOps() && "Invalid Operand Index"); 105 if (!hasArgList()) { 106 Value *NewOperand = isa<MetadataAsValue>(NewValue) 107 ? NewValue 108 : MetadataAsValue::get( 109 getContext(), ValueAsMetadata::get(NewValue)); 110 return setArgOperand(0, NewOperand); 111 } 112 SmallVector<ValueAsMetadata *, 4> MDs; 113 ValueAsMetadata *NewOperand = getAsMetadata(NewValue); 114 for (unsigned Idx = 0; Idx < getNumVariableLocationOps(); ++Idx) 115 MDs.push_back(Idx == OpIdx ? NewOperand 116 : getAsMetadata(getVariableLocationOp(Idx))); 117 setArgOperand( 118 0, MetadataAsValue::get(getContext(), DIArgList::get(getContext(), MDs))); 119 } 120 121 void DbgVariableIntrinsic::addVariableLocationOps(ArrayRef<Value *> NewValues, 122 DIExpression *NewExpr) { 123 assert(NewExpr->hasAllLocationOps(getNumVariableLocationOps() + 124 NewValues.size()) && 125 "NewExpr for debug variable intrinsic does not reference every " 126 "location operand."); 127 assert(!is_contained(NewValues, nullptr) && "New values must be non-null"); 128 setArgOperand(2, MetadataAsValue::get(getContext(), NewExpr)); 129 SmallVector<ValueAsMetadata *, 4> MDs; 130 for (auto *VMD : location_ops()) 131 MDs.push_back(getAsMetadata(VMD)); 132 for (auto *VMD : NewValues) 133 MDs.push_back(getAsMetadata(VMD)); 134 setArgOperand( 135 0, MetadataAsValue::get(getContext(), DIArgList::get(getContext(), MDs))); 136 } 137 138 Optional<uint64_t> DbgVariableIntrinsic::getFragmentSizeInBits() const { 139 if (auto Fragment = getExpression()->getFragmentInfo()) 140 return Fragment->SizeInBits; 141 return getVariable()->getSizeInBits(); 142 } 143 144 int llvm::Intrinsic::lookupLLVMIntrinsicByName(ArrayRef<const char *> NameTable, 145 StringRef Name) { 146 assert(Name.startswith("llvm.")); 147 148 // Do successive binary searches of the dotted name components. For 149 // "llvm.gc.experimental.statepoint.p1i8.p1i32", we will find the range of 150 // intrinsics starting with "llvm.gc", then "llvm.gc.experimental", then 151 // "llvm.gc.experimental.statepoint", and then we will stop as the range is 152 // size 1. During the search, we can skip the prefix that we already know is 153 // identical. By using strncmp we consider names with differing suffixes to 154 // be part of the equal range. 155 size_t CmpEnd = 4; // Skip the "llvm" component. 156 const char *const *Low = NameTable.begin(); 157 const char *const *High = NameTable.end(); 158 const char *const *LastLow = Low; 159 while (CmpEnd < Name.size() && High - Low > 0) { 160 size_t CmpStart = CmpEnd; 161 CmpEnd = Name.find('.', CmpStart + 1); 162 CmpEnd = CmpEnd == StringRef::npos ? Name.size() : CmpEnd; 163 auto Cmp = [CmpStart, CmpEnd](const char *LHS, const char *RHS) { 164 return strncmp(LHS + CmpStart, RHS + CmpStart, CmpEnd - CmpStart) < 0; 165 }; 166 LastLow = Low; 167 std::tie(Low, High) = std::equal_range(Low, High, Name.data(), Cmp); 168 } 169 if (High - Low > 0) 170 LastLow = Low; 171 172 if (LastLow == NameTable.end()) 173 return -1; 174 StringRef NameFound = *LastLow; 175 if (Name == NameFound || 176 (Name.startswith(NameFound) && Name[NameFound.size()] == '.')) 177 return LastLow - NameTable.begin(); 178 return -1; 179 } 180 181 Value *InstrProfIncrementInst::getStep() const { 182 if (InstrProfIncrementInstStep::classof(this)) { 183 return const_cast<Value *>(getArgOperand(4)); 184 } 185 const Module *M = getModule(); 186 LLVMContext &Context = M->getContext(); 187 return ConstantInt::get(Type::getInt64Ty(Context), 1); 188 } 189 190 Optional<RoundingMode> ConstrainedFPIntrinsic::getRoundingMode() const { 191 unsigned NumOperands = getNumArgOperands(); 192 Metadata *MD = 193 cast<MetadataAsValue>(getArgOperand(NumOperands - 2))->getMetadata(); 194 if (!MD || !isa<MDString>(MD)) 195 return None; 196 return StrToRoundingMode(cast<MDString>(MD)->getString()); 197 } 198 199 Optional<fp::ExceptionBehavior> 200 ConstrainedFPIntrinsic::getExceptionBehavior() const { 201 unsigned NumOperands = getNumArgOperands(); 202 Metadata *MD = 203 cast<MetadataAsValue>(getArgOperand(NumOperands - 1))->getMetadata(); 204 if (!MD || !isa<MDString>(MD)) 205 return None; 206 return StrToExceptionBehavior(cast<MDString>(MD)->getString()); 207 } 208 209 FCmpInst::Predicate ConstrainedFPCmpIntrinsic::getPredicate() const { 210 Metadata *MD = cast<MetadataAsValue>(getArgOperand(2))->getMetadata(); 211 if (!MD || !isa<MDString>(MD)) 212 return FCmpInst::BAD_FCMP_PREDICATE; 213 return StringSwitch<FCmpInst::Predicate>(cast<MDString>(MD)->getString()) 214 .Case("oeq", FCmpInst::FCMP_OEQ) 215 .Case("ogt", FCmpInst::FCMP_OGT) 216 .Case("oge", FCmpInst::FCMP_OGE) 217 .Case("olt", FCmpInst::FCMP_OLT) 218 .Case("ole", FCmpInst::FCMP_OLE) 219 .Case("one", FCmpInst::FCMP_ONE) 220 .Case("ord", FCmpInst::FCMP_ORD) 221 .Case("uno", FCmpInst::FCMP_UNO) 222 .Case("ueq", FCmpInst::FCMP_UEQ) 223 .Case("ugt", FCmpInst::FCMP_UGT) 224 .Case("uge", FCmpInst::FCMP_UGE) 225 .Case("ult", FCmpInst::FCMP_ULT) 226 .Case("ule", FCmpInst::FCMP_ULE) 227 .Case("une", FCmpInst::FCMP_UNE) 228 .Default(FCmpInst::BAD_FCMP_PREDICATE); 229 } 230 231 bool ConstrainedFPIntrinsic::isUnaryOp() const { 232 switch (getIntrinsicID()) { 233 default: 234 return false; 235 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 236 case Intrinsic::INTRINSIC: \ 237 return NARG == 1; 238 #include "llvm/IR/ConstrainedOps.def" 239 } 240 } 241 242 bool ConstrainedFPIntrinsic::isTernaryOp() const { 243 switch (getIntrinsicID()) { 244 default: 245 return false; 246 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 247 case Intrinsic::INTRINSIC: \ 248 return NARG == 3; 249 #include "llvm/IR/ConstrainedOps.def" 250 } 251 } 252 253 bool ConstrainedFPIntrinsic::classof(const IntrinsicInst *I) { 254 switch (I->getIntrinsicID()) { 255 #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \ 256 case Intrinsic::INTRINSIC: 257 #include "llvm/IR/ConstrainedOps.def" 258 return true; 259 default: 260 return false; 261 } 262 } 263 264 ElementCount VPIntrinsic::getStaticVectorLength() const { 265 auto GetVectorLengthOfType = [](const Type *T) -> ElementCount { 266 auto VT = cast<VectorType>(T); 267 auto ElemCount = VT->getElementCount(); 268 return ElemCount; 269 }; 270 271 auto VPMask = getMaskParam(); 272 return GetVectorLengthOfType(VPMask->getType()); 273 } 274 275 Value *VPIntrinsic::getMaskParam() const { 276 auto maskPos = GetMaskParamPos(getIntrinsicID()); 277 if (maskPos) 278 return getArgOperand(maskPos.getValue()); 279 return nullptr; 280 } 281 282 Value *VPIntrinsic::getVectorLengthParam() const { 283 auto vlenPos = GetVectorLengthParamPos(getIntrinsicID()); 284 if (vlenPos) 285 return getArgOperand(vlenPos.getValue()); 286 return nullptr; 287 } 288 289 Optional<int> VPIntrinsic::GetMaskParamPos(Intrinsic::ID IntrinsicID) { 290 switch (IntrinsicID) { 291 default: 292 return None; 293 294 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, MASKPOS, VLENPOS) \ 295 case Intrinsic::VPID: \ 296 return MASKPOS; 297 #include "llvm/IR/VPIntrinsics.def" 298 } 299 } 300 301 Optional<int> VPIntrinsic::GetVectorLengthParamPos(Intrinsic::ID IntrinsicID) { 302 switch (IntrinsicID) { 303 default: 304 return None; 305 306 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, MASKPOS, VLENPOS) \ 307 case Intrinsic::VPID: \ 308 return VLENPOS; 309 #include "llvm/IR/VPIntrinsics.def" 310 } 311 } 312 313 bool VPIntrinsic::IsVPIntrinsic(Intrinsic::ID ID) { 314 switch (ID) { 315 default: 316 return false; 317 318 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, MASKPOS, VLENPOS) \ 319 case Intrinsic::VPID: \ 320 break; 321 #include "llvm/IR/VPIntrinsics.def" 322 } 323 return true; 324 } 325 326 // Equivalent non-predicated opcode 327 unsigned VPIntrinsic::GetFunctionalOpcodeForVP(Intrinsic::ID ID) { 328 unsigned FunctionalOC = Instruction::Call; 329 switch (ID) { 330 default: 331 break; 332 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 333 #define HANDLE_VP_TO_OPC(OPC) FunctionalOC = Instruction::OPC; 334 #define END_REGISTER_VP_INTRINSIC(...) break; 335 #include "llvm/IR/VPIntrinsics.def" 336 } 337 338 return FunctionalOC; 339 } 340 341 Intrinsic::ID VPIntrinsic::GetForOpcode(unsigned IROPC) { 342 switch (IROPC) { 343 default: 344 return Intrinsic::not_intrinsic; 345 346 #define HANDLE_VP_TO_OPC(OPC) case Instruction::OPC: 347 #define END_REGISTER_VP_INTRINSIC(VPID) return Intrinsic::VPID; 348 #include "llvm/IR/VPIntrinsics.def" 349 } 350 } 351 352 bool VPIntrinsic::canIgnoreVectorLengthParam() const { 353 using namespace PatternMatch; 354 355 ElementCount EC = getStaticVectorLength(); 356 357 // No vlen param - no lanes masked-off by it. 358 auto *VLParam = getVectorLengthParam(); 359 if (!VLParam) 360 return true; 361 362 // Note that the VP intrinsic causes undefined behavior if the Explicit Vector 363 // Length parameter is strictly greater-than the number of vector elements of 364 // the operation. This function returns true when this is detected statically 365 // in the IR. 366 367 // Check whether "W == vscale * EC.getKnownMinValue()" 368 if (EC.isScalable()) { 369 // Undig the DL 370 auto ParMod = this->getModule(); 371 if (!ParMod) 372 return false; 373 const auto &DL = ParMod->getDataLayout(); 374 375 // Compare vscale patterns 376 uint64_t VScaleFactor; 377 if (match(VLParam, m_c_Mul(m_ConstantInt(VScaleFactor), m_VScale(DL)))) 378 return VScaleFactor >= EC.getKnownMinValue(); 379 return (EC.getKnownMinValue() == 1) && match(VLParam, m_VScale(DL)); 380 } 381 382 // standard SIMD operation 383 auto VLConst = dyn_cast<ConstantInt>(VLParam); 384 if (!VLConst) 385 return false; 386 387 uint64_t VLNum = VLConst->getZExtValue(); 388 if (VLNum >= EC.getKnownMinValue()) 389 return true; 390 391 return false; 392 } 393 394 Instruction::BinaryOps BinaryOpIntrinsic::getBinaryOp() const { 395 switch (getIntrinsicID()) { 396 case Intrinsic::uadd_with_overflow: 397 case Intrinsic::sadd_with_overflow: 398 case Intrinsic::uadd_sat: 399 case Intrinsic::sadd_sat: 400 return Instruction::Add; 401 case Intrinsic::usub_with_overflow: 402 case Intrinsic::ssub_with_overflow: 403 case Intrinsic::usub_sat: 404 case Intrinsic::ssub_sat: 405 return Instruction::Sub; 406 case Intrinsic::umul_with_overflow: 407 case Intrinsic::smul_with_overflow: 408 return Instruction::Mul; 409 default: 410 llvm_unreachable("Invalid intrinsic"); 411 } 412 } 413 414 bool BinaryOpIntrinsic::isSigned() const { 415 switch (getIntrinsicID()) { 416 case Intrinsic::sadd_with_overflow: 417 case Intrinsic::ssub_with_overflow: 418 case Intrinsic::smul_with_overflow: 419 case Intrinsic::sadd_sat: 420 case Intrinsic::ssub_sat: 421 return true; 422 default: 423 return false; 424 } 425 } 426 427 unsigned BinaryOpIntrinsic::getNoWrapKind() const { 428 if (isSigned()) 429 return OverflowingBinaryOperator::NoSignedWrap; 430 else 431 return OverflowingBinaryOperator::NoUnsignedWrap; 432 } 433 434 const GCStatepointInst *GCProjectionInst::getStatepoint() const { 435 const Value *Token = getArgOperand(0); 436 437 // This takes care both of relocates for call statepoints and relocates 438 // on normal path of invoke statepoint. 439 if (!isa<LandingPadInst>(Token)) 440 return cast<GCStatepointInst>(Token); 441 442 // This relocate is on exceptional path of an invoke statepoint 443 const BasicBlock *InvokeBB = 444 cast<Instruction>(Token)->getParent()->getUniquePredecessor(); 445 446 assert(InvokeBB && "safepoints should have unique landingpads"); 447 assert(InvokeBB->getTerminator() && 448 "safepoint block should be well formed"); 449 450 return cast<GCStatepointInst>(InvokeBB->getTerminator()); 451 } 452 453 Value *GCRelocateInst::getBasePtr() const { 454 if (auto Opt = getStatepoint()->getOperandBundle(LLVMContext::OB_gc_live)) 455 return *(Opt->Inputs.begin() + getBasePtrIndex()); 456 return *(getStatepoint()->arg_begin() + getBasePtrIndex()); 457 } 458 459 Value *GCRelocateInst::getDerivedPtr() const { 460 if (auto Opt = getStatepoint()->getOperandBundle(LLVMContext::OB_gc_live)) 461 return *(Opt->Inputs.begin() + getDerivedPtrIndex()); 462 return *(getStatepoint()->arg_begin() + getDerivedPtrIndex()); 463 } 464