1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 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 coordinates the per-function state used while generating code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodeGenFunction.h" 14 #include "CGBlocks.h" 15 #include "CGCUDARuntime.h" 16 #include "CGCXXABI.h" 17 #include "CGCleanup.h" 18 #include "CGDebugInfo.h" 19 #include "CGHLSLRuntime.h" 20 #include "CGOpenMPRuntime.h" 21 #include "CodeGenModule.h" 22 #include "CodeGenPGO.h" 23 #include "TargetInfo.h" 24 #include "clang/AST/ASTContext.h" 25 #include "clang/AST/ASTLambda.h" 26 #include "clang/AST/Attr.h" 27 #include "clang/AST/Decl.h" 28 #include "clang/AST/DeclCXX.h" 29 #include "clang/AST/Expr.h" 30 #include "clang/AST/StmtCXX.h" 31 #include "clang/AST/StmtObjC.h" 32 #include "clang/Basic/Builtins.h" 33 #include "clang/Basic/CodeGenOptions.h" 34 #include "clang/Basic/TargetBuiltins.h" 35 #include "clang/Basic/TargetInfo.h" 36 #include "clang/CodeGen/CGFunctionInfo.h" 37 #include "clang/Frontend/FrontendDiagnostic.h" 38 #include "llvm/ADT/ArrayRef.h" 39 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 40 #include "llvm/IR/DataLayout.h" 41 #include "llvm/IR/Dominators.h" 42 #include "llvm/IR/FPEnv.h" 43 #include "llvm/IR/IntrinsicInst.h" 44 #include "llvm/IR/Intrinsics.h" 45 #include "llvm/IR/MDBuilder.h" 46 #include "llvm/IR/Operator.h" 47 #include "llvm/Support/CRC.h" 48 #include "llvm/Support/xxhash.h" 49 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h" 50 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 51 #include <optional> 52 53 using namespace clang; 54 using namespace CodeGen; 55 56 namespace llvm { 57 extern cl::opt<bool> EnableSingleByteCoverage; 58 } // namespace llvm 59 60 /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time 61 /// markers. 62 static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts, 63 const LangOptions &LangOpts) { 64 if (CGOpts.DisableLifetimeMarkers) 65 return false; 66 67 // Sanitizers may use markers. 68 if (CGOpts.SanitizeAddressUseAfterScope || 69 LangOpts.Sanitize.has(SanitizerKind::HWAddress) || 70 LangOpts.Sanitize.has(SanitizerKind::Memory)) 71 return true; 72 73 // For now, only in optimized builds. 74 return CGOpts.OptimizationLevel != 0; 75 } 76 77 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext) 78 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()), 79 Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(), 80 CGBuilderInserterTy(this)), 81 SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()), 82 DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm), 83 ShouldEmitLifetimeMarkers( 84 shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) { 85 if (!suppressNewContext) 86 CGM.getCXXABI().getMangleContext().startNewFunction(); 87 EHStack.setCGF(this); 88 89 SetFastMathFlags(CurFPFeatures); 90 } 91 92 CodeGenFunction::~CodeGenFunction() { 93 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup"); 94 assert(DeferredDeactivationCleanupStack.empty() && 95 "missed to deactivate a cleanup"); 96 97 if (getLangOpts().OpenMP && CurFn) 98 CGM.getOpenMPRuntime().functionFinished(*this); 99 100 // If we have an OpenMPIRBuilder we want to finalize functions (incl. 101 // outlining etc) at some point. Doing it once the function codegen is done 102 // seems to be a reasonable spot. We do it here, as opposed to the deletion 103 // time of the CodeGenModule, because we have to ensure the IR has not yet 104 // been "emitted" to the outside, thus, modifications are still sensible. 105 if (CGM.getLangOpts().OpenMPIRBuilder && CurFn) 106 CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn); 107 } 108 109 // Map the LangOption for exception behavior into 110 // the corresponding enum in the IR. 111 llvm::fp::ExceptionBehavior 112 clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) { 113 114 switch (Kind) { 115 case LangOptions::FPE_Ignore: return llvm::fp::ebIgnore; 116 case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap; 117 case LangOptions::FPE_Strict: return llvm::fp::ebStrict; 118 default: 119 llvm_unreachable("Unsupported FP Exception Behavior"); 120 } 121 } 122 123 void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) { 124 llvm::FastMathFlags FMF; 125 FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate()); 126 FMF.setNoNaNs(FPFeatures.getNoHonorNaNs()); 127 FMF.setNoInfs(FPFeatures.getNoHonorInfs()); 128 FMF.setNoSignedZeros(FPFeatures.getNoSignedZero()); 129 FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal()); 130 FMF.setApproxFunc(FPFeatures.getAllowApproxFunc()); 131 FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement()); 132 Builder.setFastMathFlags(FMF); 133 } 134 135 CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF, 136 const Expr *E) 137 : CGF(CGF) { 138 ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts())); 139 } 140 141 CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF, 142 FPOptions FPFeatures) 143 : CGF(CGF) { 144 ConstructorHelper(FPFeatures); 145 } 146 147 void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) { 148 OldFPFeatures = CGF.CurFPFeatures; 149 CGF.CurFPFeatures = FPFeatures; 150 151 OldExcept = CGF.Builder.getDefaultConstrainedExcept(); 152 OldRounding = CGF.Builder.getDefaultConstrainedRounding(); 153 154 if (OldFPFeatures == FPFeatures) 155 return; 156 157 FMFGuard.emplace(CGF.Builder); 158 159 llvm::RoundingMode NewRoundingBehavior = FPFeatures.getRoundingMode(); 160 CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior); 161 auto NewExceptionBehavior = 162 ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind>( 163 FPFeatures.getExceptionMode())); 164 CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior); 165 166 CGF.SetFastMathFlags(FPFeatures); 167 168 assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() || 169 isa<CXXConstructorDecl>(CGF.CurFuncDecl) || 170 isa<CXXDestructorDecl>(CGF.CurFuncDecl) || 171 (NewExceptionBehavior == llvm::fp::ebIgnore && 172 NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) && 173 "FPConstrained should be enabled on entire function"); 174 175 auto mergeFnAttrValue = [&](StringRef Name, bool Value) { 176 auto OldValue = 177 CGF.CurFn->getFnAttribute(Name).getValueAsBool(); 178 auto NewValue = OldValue & Value; 179 if (OldValue != NewValue) 180 CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue)); 181 }; 182 mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs()); 183 mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs()); 184 mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero()); 185 mergeFnAttrValue( 186 "unsafe-fp-math", 187 FPFeatures.getAllowFPReassociate() && FPFeatures.getAllowReciprocal() && 188 FPFeatures.getAllowApproxFunc() && FPFeatures.getNoSignedZero() && 189 FPFeatures.allowFPContractAcrossStatement()); 190 } 191 192 CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() { 193 CGF.CurFPFeatures = OldFPFeatures; 194 CGF.Builder.setDefaultConstrainedExcept(OldExcept); 195 CGF.Builder.setDefaultConstrainedRounding(OldRounding); 196 } 197 198 static LValue 199 makeNaturalAlignAddrLValue(llvm::Value *V, QualType T, bool ForPointeeType, 200 bool MightBeSigned, CodeGenFunction &CGF, 201 KnownNonNull_t IsKnownNonNull = NotKnownNonNull) { 202 LValueBaseInfo BaseInfo; 203 TBAAAccessInfo TBAAInfo; 204 CharUnits Alignment = 205 CGF.CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo, ForPointeeType); 206 Address Addr = 207 MightBeSigned 208 ? CGF.makeNaturalAddressForPointer(V, T, Alignment, false, nullptr, 209 nullptr, IsKnownNonNull) 210 : Address(V, CGF.ConvertTypeForMem(T), Alignment, IsKnownNonNull); 211 return CGF.MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo); 212 } 213 214 LValue 215 CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, 216 KnownNonNull_t IsKnownNonNull) { 217 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false, 218 /*MightBeSigned*/ true, *this, 219 IsKnownNonNull); 220 } 221 222 LValue 223 CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) { 224 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true, 225 /*MightBeSigned*/ true, *this); 226 } 227 228 LValue CodeGenFunction::MakeNaturalAlignRawAddrLValue(llvm::Value *V, 229 QualType T) { 230 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false, 231 /*MightBeSigned*/ false, *this); 232 } 233 234 LValue CodeGenFunction::MakeNaturalAlignPointeeRawAddrLValue(llvm::Value *V, 235 QualType T) { 236 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true, 237 /*MightBeSigned*/ false, *this); 238 } 239 240 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 241 return CGM.getTypes().ConvertTypeForMem(T); 242 } 243 244 llvm::Type *CodeGenFunction::ConvertType(QualType T) { 245 return CGM.getTypes().ConvertType(T); 246 } 247 248 llvm::Type *CodeGenFunction::convertTypeForLoadStore(QualType ASTTy, 249 llvm::Type *LLVMTy) { 250 return CGM.getTypes().convertTypeForLoadStore(ASTTy, LLVMTy); 251 } 252 253 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) { 254 type = type.getCanonicalType(); 255 while (true) { 256 switch (type->getTypeClass()) { 257 #define TYPE(name, parent) 258 #define ABSTRACT_TYPE(name, parent) 259 #define NON_CANONICAL_TYPE(name, parent) case Type::name: 260 #define DEPENDENT_TYPE(name, parent) case Type::name: 261 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 262 #include "clang/AST/TypeNodes.inc" 263 llvm_unreachable("non-canonical or dependent type in IR-generation"); 264 265 case Type::Auto: 266 case Type::DeducedTemplateSpecialization: 267 llvm_unreachable("undeduced type in IR-generation"); 268 269 // Various scalar types. 270 case Type::Builtin: 271 case Type::Pointer: 272 case Type::BlockPointer: 273 case Type::LValueReference: 274 case Type::RValueReference: 275 case Type::MemberPointer: 276 case Type::Vector: 277 case Type::ExtVector: 278 case Type::ConstantMatrix: 279 case Type::FunctionProto: 280 case Type::FunctionNoProto: 281 case Type::Enum: 282 case Type::ObjCObjectPointer: 283 case Type::Pipe: 284 case Type::BitInt: 285 return TEK_Scalar; 286 287 // Complexes. 288 case Type::Complex: 289 return TEK_Complex; 290 291 // Arrays, records, and Objective-C objects. 292 case Type::ConstantArray: 293 case Type::IncompleteArray: 294 case Type::VariableArray: 295 case Type::Record: 296 case Type::ObjCObject: 297 case Type::ObjCInterface: 298 case Type::ArrayParameter: 299 return TEK_Aggregate; 300 301 // We operate on atomic values according to their underlying type. 302 case Type::Atomic: 303 type = cast<AtomicType>(type)->getValueType(); 304 continue; 305 } 306 llvm_unreachable("unknown type kind!"); 307 } 308 } 309 310 llvm::DebugLoc CodeGenFunction::EmitReturnBlock() { 311 // For cleanliness, we try to avoid emitting the return block for 312 // simple cases. 313 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 314 315 if (CurBB) { 316 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 317 318 // We have a valid insert point, reuse it if it is empty or there are no 319 // explicit jumps to the return block. 320 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 321 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 322 delete ReturnBlock.getBlock(); 323 ReturnBlock = JumpDest(); 324 } else 325 EmitBlock(ReturnBlock.getBlock()); 326 return llvm::DebugLoc(); 327 } 328 329 // Otherwise, if the return block is the target of a single direct 330 // branch then we can just put the code in that block instead. This 331 // cleans up functions which started with a unified return block. 332 if (ReturnBlock.getBlock()->hasOneUse()) { 333 llvm::BranchInst *BI = 334 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin()); 335 if (BI && BI->isUnconditional() && 336 BI->getSuccessor(0) == ReturnBlock.getBlock()) { 337 // Record/return the DebugLoc of the simple 'return' expression to be used 338 // later by the actual 'ret' instruction. 339 llvm::DebugLoc Loc = BI->getDebugLoc(); 340 Builder.SetInsertPoint(BI->getParent()); 341 BI->eraseFromParent(); 342 delete ReturnBlock.getBlock(); 343 ReturnBlock = JumpDest(); 344 return Loc; 345 } 346 } 347 348 // FIXME: We are at an unreachable point, there is no reason to emit the block 349 // unless it has uses. However, we still need a place to put the debug 350 // region.end for now. 351 352 EmitBlock(ReturnBlock.getBlock()); 353 return llvm::DebugLoc(); 354 } 355 356 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 357 if (!BB) return; 358 if (!BB->use_empty()) { 359 CGF.CurFn->insert(CGF.CurFn->end(), BB); 360 return; 361 } 362 delete BB; 363 } 364 365 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 366 assert(BreakContinueStack.empty() && 367 "mismatched push/pop in break/continue stack!"); 368 assert(LifetimeExtendedCleanupStack.empty() && 369 "mismatched push/pop of cleanups in EHStack!"); 370 assert(DeferredDeactivationCleanupStack.empty() && 371 "mismatched activate/deactivate of cleanups!"); 372 373 if (CGM.shouldEmitConvergenceTokens()) { 374 ConvergenceTokenStack.pop_back(); 375 assert(ConvergenceTokenStack.empty() && 376 "mismatched push/pop in convergence stack!"); 377 } 378 379 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0 380 && NumSimpleReturnExprs == NumReturnExprs 381 && ReturnBlock.getBlock()->use_empty(); 382 // Usually the return expression is evaluated before the cleanup 383 // code. If the function contains only a simple return statement, 384 // such as a constant, the location before the cleanup code becomes 385 // the last useful breakpoint in the function, because the simple 386 // return expression will be evaluated after the cleanup code. To be 387 // safe, set the debug location for cleanup code to the location of 388 // the return statement. Otherwise the cleanup code should be at the 389 // end of the function's lexical scope. 390 // 391 // If there are multiple branches to the return block, the branch 392 // instructions will get the location of the return statements and 393 // all will be fine. 394 if (CGDebugInfo *DI = getDebugInfo()) { 395 if (OnlySimpleReturnStmts) 396 DI->EmitLocation(Builder, LastStopPoint); 397 else 398 DI->EmitLocation(Builder, EndLoc); 399 } 400 401 // Pop any cleanups that might have been associated with the 402 // parameters. Do this in whatever block we're currently in; it's 403 // important to do this before we enter the return block or return 404 // edges will be *really* confused. 405 bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth; 406 bool HasOnlyLifetimeMarkers = 407 HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth); 408 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers; 409 410 std::optional<ApplyDebugLocation> OAL; 411 if (HasCleanups) { 412 // Make sure the line table doesn't jump back into the body for 413 // the ret after it's been at EndLoc. 414 if (CGDebugInfo *DI = getDebugInfo()) { 415 if (OnlySimpleReturnStmts) 416 DI->EmitLocation(Builder, EndLoc); 417 else 418 // We may not have a valid end location. Try to apply it anyway, and 419 // fall back to an artificial location if needed. 420 OAL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc); 421 } 422 423 PopCleanupBlocks(PrologueCleanupDepth); 424 } 425 426 // Emit function epilog (to return). 427 llvm::DebugLoc Loc = EmitReturnBlock(); 428 429 if (ShouldInstrumentFunction()) { 430 if (CGM.getCodeGenOpts().InstrumentFunctions) 431 CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit"); 432 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining) 433 CurFn->addFnAttr("instrument-function-exit-inlined", 434 "__cyg_profile_func_exit"); 435 } 436 437 // Emit debug descriptor for function end. 438 if (CGDebugInfo *DI = getDebugInfo()) 439 DI->EmitFunctionEnd(Builder, CurFn); 440 441 // Reset the debug location to that of the simple 'return' expression, if any 442 // rather than that of the end of the function's scope '}'. 443 ApplyDebugLocation AL(*this, Loc); 444 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc); 445 EmitEndEHSpec(CurCodeDecl); 446 447 assert(EHStack.empty() && 448 "did not remove all scopes from cleanup stack!"); 449 450 // If someone did an indirect goto, emit the indirect goto block at the end of 451 // the function. 452 if (IndirectBranch) { 453 EmitBlock(IndirectBranch->getParent()); 454 Builder.ClearInsertionPoint(); 455 } 456 457 // If some of our locals escaped, insert a call to llvm.localescape in the 458 // entry block. 459 if (!EscapedLocals.empty()) { 460 // Invert the map from local to index into a simple vector. There should be 461 // no holes. 462 SmallVector<llvm::Value *, 4> EscapeArgs; 463 EscapeArgs.resize(EscapedLocals.size()); 464 for (auto &Pair : EscapedLocals) 465 EscapeArgs[Pair.second] = Pair.first; 466 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration( 467 &CGM.getModule(), llvm::Intrinsic::localescape); 468 CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs); 469 } 470 471 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 472 llvm::Instruction *Ptr = AllocaInsertPt; 473 AllocaInsertPt = nullptr; 474 Ptr->eraseFromParent(); 475 476 // PostAllocaInsertPt, if created, was lazily created when it was required, 477 // remove it now since it was just created for our own convenience. 478 if (PostAllocaInsertPt) { 479 llvm::Instruction *PostPtr = PostAllocaInsertPt; 480 PostAllocaInsertPt = nullptr; 481 PostPtr->eraseFromParent(); 482 } 483 484 // If someone took the address of a label but never did an indirect goto, we 485 // made a zero entry PHI node, which is illegal, zap it now. 486 if (IndirectBranch) { 487 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 488 if (PN->getNumIncomingValues() == 0) { 489 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 490 PN->eraseFromParent(); 491 } 492 } 493 494 EmitIfUsed(*this, EHResumeBlock); 495 EmitIfUsed(*this, TerminateLandingPad); 496 EmitIfUsed(*this, TerminateHandler); 497 EmitIfUsed(*this, UnreachableBlock); 498 499 for (const auto &FuncletAndParent : TerminateFunclets) 500 EmitIfUsed(*this, FuncletAndParent.second); 501 502 if (CGM.getCodeGenOpts().EmitDeclMetadata) 503 EmitDeclMetadata(); 504 505 for (const auto &R : DeferredReplacements) { 506 if (llvm::Value *Old = R.first) { 507 Old->replaceAllUsesWith(R.second); 508 cast<llvm::Instruction>(Old)->eraseFromParent(); 509 } 510 } 511 DeferredReplacements.clear(); 512 513 // Eliminate CleanupDestSlot alloca by replacing it with SSA values and 514 // PHIs if the current function is a coroutine. We don't do it for all 515 // functions as it may result in slight increase in numbers of instructions 516 // if compiled with no optimizations. We do it for coroutine as the lifetime 517 // of CleanupDestSlot alloca make correct coroutine frame building very 518 // difficult. 519 if (NormalCleanupDest.isValid() && isCoroutine()) { 520 llvm::DominatorTree DT(*CurFn); 521 llvm::PromoteMemToReg( 522 cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT); 523 NormalCleanupDest = Address::invalid(); 524 } 525 526 // Scan function arguments for vector width. 527 for (llvm::Argument &A : CurFn->args()) 528 if (auto *VT = dyn_cast<llvm::VectorType>(A.getType())) 529 LargestVectorWidth = 530 std::max((uint64_t)LargestVectorWidth, 531 VT->getPrimitiveSizeInBits().getKnownMinValue()); 532 533 // Update vector width based on return type. 534 if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType())) 535 LargestVectorWidth = 536 std::max((uint64_t)LargestVectorWidth, 537 VT->getPrimitiveSizeInBits().getKnownMinValue()); 538 539 if (CurFnInfo->getMaxVectorWidth() > LargestVectorWidth) 540 LargestVectorWidth = CurFnInfo->getMaxVectorWidth(); 541 542 // Add the min-legal-vector-width attribute. This contains the max width from: 543 // 1. min-vector-width attribute used in the source program. 544 // 2. Any builtins used that have a vector width specified. 545 // 3. Values passed in and out of inline assembly. 546 // 4. Width of vector arguments and return types for this function. 547 // 5. Width of vector arguments and return types for functions called by this 548 // function. 549 if (getContext().getTargetInfo().getTriple().isX86()) 550 CurFn->addFnAttr("min-legal-vector-width", 551 llvm::utostr(LargestVectorWidth)); 552 553 // Add vscale_range attribute if appropriate. 554 std::optional<std::pair<unsigned, unsigned>> VScaleRange = 555 getContext().getTargetInfo().getVScaleRange(getLangOpts()); 556 if (VScaleRange) { 557 CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs( 558 getLLVMContext(), VScaleRange->first, VScaleRange->second)); 559 } 560 561 // If we generated an unreachable return block, delete it now. 562 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) { 563 Builder.ClearInsertionPoint(); 564 ReturnBlock.getBlock()->eraseFromParent(); 565 } 566 if (ReturnValue.isValid()) { 567 auto *RetAlloca = 568 dyn_cast<llvm::AllocaInst>(ReturnValue.emitRawPointer(*this)); 569 if (RetAlloca && RetAlloca->use_empty()) { 570 RetAlloca->eraseFromParent(); 571 ReturnValue = Address::invalid(); 572 } 573 } 574 } 575 576 /// ShouldInstrumentFunction - Return true if the current function should be 577 /// instrumented with __cyg_profile_func_* calls 578 bool CodeGenFunction::ShouldInstrumentFunction() { 579 if (!CGM.getCodeGenOpts().InstrumentFunctions && 580 !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining && 581 !CGM.getCodeGenOpts().InstrumentFunctionEntryBare) 582 return false; 583 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 584 return false; 585 return true; 586 } 587 588 bool CodeGenFunction::ShouldSkipSanitizerInstrumentation() { 589 if (!CurFuncDecl) 590 return false; 591 return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>(); 592 } 593 594 /// ShouldXRayInstrument - Return true if the current function should be 595 /// instrumented with XRay nop sleds. 596 bool CodeGenFunction::ShouldXRayInstrumentFunction() const { 597 return CGM.getCodeGenOpts().XRayInstrumentFunctions; 598 } 599 600 /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to 601 /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation. 602 bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const { 603 return CGM.getCodeGenOpts().XRayInstrumentFunctions && 604 (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents || 605 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask == 606 XRayInstrKind::Custom); 607 } 608 609 bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const { 610 return CGM.getCodeGenOpts().XRayInstrumentFunctions && 611 (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents || 612 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask == 613 XRayInstrKind::Typed); 614 } 615 616 llvm::ConstantInt * 617 CodeGenFunction::getUBSanFunctionTypeHash(QualType Ty) const { 618 // Remove any (C++17) exception specifications, to allow calling e.g. a 619 // noexcept function through a non-noexcept pointer. 620 if (!Ty->isFunctionNoProtoType()) 621 Ty = getContext().getFunctionTypeWithExceptionSpec(Ty, EST_None); 622 std::string Mangled; 623 llvm::raw_string_ostream Out(Mangled); 624 CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(Ty, Out, false); 625 return llvm::ConstantInt::get( 626 CGM.Int32Ty, static_cast<uint32_t>(llvm::xxh3_64bits(Mangled))); 627 } 628 629 void CodeGenFunction::EmitKernelMetadata(const FunctionDecl *FD, 630 llvm::Function *Fn) { 631 if (!FD->hasAttr<OpenCLKernelAttr>() && !FD->hasAttr<CUDAGlobalAttr>()) 632 return; 633 634 llvm::LLVMContext &Context = getLLVMContext(); 635 636 CGM.GenKernelArgMetadata(Fn, FD, this); 637 638 if (!getLangOpts().OpenCL) 639 return; 640 641 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) { 642 QualType HintQTy = A->getTypeHint(); 643 const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>(); 644 bool IsSignedInteger = 645 HintQTy->isSignedIntegerType() || 646 (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType()); 647 llvm::Metadata *AttrMDArgs[] = { 648 llvm::ConstantAsMetadata::get(llvm::UndefValue::get( 649 CGM.getTypes().ConvertType(A->getTypeHint()))), 650 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 651 llvm::IntegerType::get(Context, 32), 652 llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))}; 653 Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs)); 654 } 655 656 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) { 657 llvm::Metadata *AttrMDArgs[] = { 658 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 659 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 660 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 661 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs)); 662 } 663 664 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) { 665 llvm::Metadata *AttrMDArgs[] = { 666 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 667 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 668 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 669 Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs)); 670 } 671 672 if (const OpenCLIntelReqdSubGroupSizeAttr *A = 673 FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) { 674 llvm::Metadata *AttrMDArgs[] = { 675 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))}; 676 Fn->setMetadata("intel_reqd_sub_group_size", 677 llvm::MDNode::get(Context, AttrMDArgs)); 678 } 679 } 680 681 /// Determine whether the function F ends with a return stmt. 682 static bool endsWithReturn(const Decl* F) { 683 const Stmt *Body = nullptr; 684 if (auto *FD = dyn_cast_or_null<FunctionDecl>(F)) 685 Body = FD->getBody(); 686 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F)) 687 Body = OMD->getBody(); 688 689 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) { 690 auto LastStmt = CS->body_rbegin(); 691 if (LastStmt != CS->body_rend()) 692 return isa<ReturnStmt>(*LastStmt); 693 } 694 return false; 695 } 696 697 void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) { 698 if (SanOpts.has(SanitizerKind::Thread)) { 699 Fn->addFnAttr("sanitize_thread_no_checking_at_run_time"); 700 Fn->removeFnAttr(llvm::Attribute::SanitizeThread); 701 } 702 } 703 704 /// Check if the return value of this function requires sanitization. 705 bool CodeGenFunction::requiresReturnValueCheck() const { 706 return requiresReturnValueNullabilityCheck() || 707 (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl && 708 CurCodeDecl->getAttr<ReturnsNonNullAttr>()); 709 } 710 711 static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) { 712 auto *MD = dyn_cast_or_null<CXXMethodDecl>(D); 713 if (!MD || !MD->getDeclName().getAsIdentifierInfo() || 714 !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") || 715 (MD->getNumParams() != 1 && MD->getNumParams() != 2)) 716 return false; 717 718 if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType()) 719 return false; 720 721 if (MD->getNumParams() == 2) { 722 auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>(); 723 if (!PT || !PT->isVoidPointerType() || 724 !PT->getPointeeType().isConstQualified()) 725 return false; 726 } 727 728 return true; 729 } 730 731 bool CodeGenFunction::isInAllocaArgument(CGCXXABI &ABI, QualType Ty) { 732 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 733 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory; 734 } 735 736 bool CodeGenFunction::hasInAllocaArg(const CXXMethodDecl *MD) { 737 return getTarget().getTriple().getArch() == llvm::Triple::x86 && 738 getTarget().getCXXABI().isMicrosoft() && 739 llvm::any_of(MD->parameters(), [&](ParmVarDecl *P) { 740 return isInAllocaArgument(CGM.getCXXABI(), P->getType()); 741 }); 742 } 743 744 /// Return the UBSan prologue signature for \p FD if one is available. 745 static llvm::Constant *getPrologueSignature(CodeGenModule &CGM, 746 const FunctionDecl *FD) { 747 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 748 if (!MD->isStatic()) 749 return nullptr; 750 return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM); 751 } 752 753 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 754 llvm::Function *Fn, 755 const CGFunctionInfo &FnInfo, 756 const FunctionArgList &Args, 757 SourceLocation Loc, 758 SourceLocation StartLoc) { 759 assert(!CurFn && 760 "Do not use a CodeGenFunction object for more than one function"); 761 762 const Decl *D = GD.getDecl(); 763 764 DidCallStackSave = false; 765 CurCodeDecl = D; 766 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 767 if (FD && FD->usesSEHTry()) 768 CurSEHParent = GD; 769 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr); 770 FnRetTy = RetTy; 771 CurFn = Fn; 772 CurFnInfo = &FnInfo; 773 assert(CurFn->isDeclaration() && "Function already has body?"); 774 775 // If this function is ignored for any of the enabled sanitizers, 776 // disable the sanitizer for the function. 777 do { 778 #define SANITIZER(NAME, ID) \ 779 if (SanOpts.empty()) \ 780 break; \ 781 if (SanOpts.has(SanitizerKind::ID)) \ 782 if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)) \ 783 SanOpts.set(SanitizerKind::ID, false); 784 785 #include "clang/Basic/Sanitizers.def" 786 #undef SANITIZER 787 } while (false); 788 789 if (D) { 790 const bool SanitizeBounds = SanOpts.hasOneOf(SanitizerKind::Bounds); 791 SanitizerMask no_sanitize_mask; 792 bool NoSanitizeCoverage = false; 793 794 for (auto *Attr : D->specific_attrs<NoSanitizeAttr>()) { 795 no_sanitize_mask |= Attr->getMask(); 796 // SanitizeCoverage is not handled by SanOpts. 797 if (Attr->hasCoverage()) 798 NoSanitizeCoverage = true; 799 } 800 801 // Apply the no_sanitize* attributes to SanOpts. 802 SanOpts.Mask &= ~no_sanitize_mask; 803 if (no_sanitize_mask & SanitizerKind::Address) 804 SanOpts.set(SanitizerKind::KernelAddress, false); 805 if (no_sanitize_mask & SanitizerKind::KernelAddress) 806 SanOpts.set(SanitizerKind::Address, false); 807 if (no_sanitize_mask & SanitizerKind::HWAddress) 808 SanOpts.set(SanitizerKind::KernelHWAddress, false); 809 if (no_sanitize_mask & SanitizerKind::KernelHWAddress) 810 SanOpts.set(SanitizerKind::HWAddress, false); 811 812 if (SanitizeBounds && !SanOpts.hasOneOf(SanitizerKind::Bounds)) 813 Fn->addFnAttr(llvm::Attribute::NoSanitizeBounds); 814 815 if (NoSanitizeCoverage && CGM.getCodeGenOpts().hasSanitizeCoverage()) 816 Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage); 817 818 // Some passes need the non-negated no_sanitize attribute. Pass them on. 819 if (CGM.getCodeGenOpts().hasSanitizeBinaryMetadata()) { 820 if (no_sanitize_mask & SanitizerKind::Thread) 821 Fn->addFnAttr("no_sanitize_thread"); 822 } 823 } 824 825 if (ShouldSkipSanitizerInstrumentation()) { 826 CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation); 827 } else { 828 // Apply sanitizer attributes to the function. 829 if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress)) 830 Fn->addFnAttr(llvm::Attribute::SanitizeAddress); 831 if (SanOpts.hasOneOf(SanitizerKind::HWAddress | 832 SanitizerKind::KernelHWAddress)) 833 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress); 834 if (SanOpts.has(SanitizerKind::MemtagStack)) 835 Fn->addFnAttr(llvm::Attribute::SanitizeMemTag); 836 if (SanOpts.has(SanitizerKind::Thread)) 837 Fn->addFnAttr(llvm::Attribute::SanitizeThread); 838 if (SanOpts.has(SanitizerKind::NumericalStability)) 839 Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability); 840 if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory)) 841 Fn->addFnAttr(llvm::Attribute::SanitizeMemory); 842 } 843 if (SanOpts.has(SanitizerKind::SafeStack)) 844 Fn->addFnAttr(llvm::Attribute::SafeStack); 845 if (SanOpts.has(SanitizerKind::ShadowCallStack)) 846 Fn->addFnAttr(llvm::Attribute::ShadowCallStack); 847 848 // Apply fuzzing attribute to the function. 849 if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink)) 850 Fn->addFnAttr(llvm::Attribute::OptForFuzzing); 851 852 // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize, 853 // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time. 854 if (SanOpts.has(SanitizerKind::Thread)) { 855 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) { 856 const IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0); 857 if (OMD->getMethodFamily() == OMF_dealloc || 858 OMD->getMethodFamily() == OMF_initialize || 859 (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) { 860 markAsIgnoreThreadCheckingAtRuntime(Fn); 861 } 862 } 863 } 864 865 // Ignore unrelated casts in STL allocate() since the allocator must cast 866 // from void* to T* before object initialization completes. Don't match on the 867 // namespace because not all allocators are in std:: 868 if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) { 869 if (matchesStlAllocatorFn(D, getContext())) 870 SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast; 871 } 872 873 // Ignore null checks in coroutine functions since the coroutines passes 874 // are not aware of how to move the extra UBSan instructions across the split 875 // coroutine boundaries. 876 if (D && SanOpts.has(SanitizerKind::Null)) 877 if (FD && FD->getBody() && 878 FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass) 879 SanOpts.Mask &= ~SanitizerKind::Null; 880 881 // Add pointer authentication attributes. 882 const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts(); 883 if (CodeGenOpts.PointerAuth.ReturnAddresses) 884 Fn->addFnAttr("ptrauth-returns"); 885 if (CodeGenOpts.PointerAuth.FunctionPointers) 886 Fn->addFnAttr("ptrauth-calls"); 887 if (CodeGenOpts.PointerAuth.IndirectGotos) 888 Fn->addFnAttr("ptrauth-indirect-gotos"); 889 890 // Apply xray attributes to the function (as a string, for now) 891 bool AlwaysXRayAttr = false; 892 if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) { 893 if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 894 XRayInstrKind::FunctionEntry) || 895 CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 896 XRayInstrKind::FunctionExit)) { 897 if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) { 898 Fn->addFnAttr("function-instrument", "xray-always"); 899 AlwaysXRayAttr = true; 900 } 901 if (XRayAttr->neverXRayInstrument()) 902 Fn->addFnAttr("function-instrument", "xray-never"); 903 if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>()) 904 if (ShouldXRayInstrumentFunction()) 905 Fn->addFnAttr("xray-log-args", 906 llvm::utostr(LogArgs->getArgumentCount())); 907 } 908 } else { 909 if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc)) 910 Fn->addFnAttr( 911 "xray-instruction-threshold", 912 llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold)); 913 } 914 915 if (ShouldXRayInstrumentFunction()) { 916 if (CGM.getCodeGenOpts().XRayIgnoreLoops) 917 Fn->addFnAttr("xray-ignore-loops"); 918 919 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 920 XRayInstrKind::FunctionExit)) 921 Fn->addFnAttr("xray-skip-exit"); 922 923 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 924 XRayInstrKind::FunctionEntry)) 925 Fn->addFnAttr("xray-skip-entry"); 926 927 auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups; 928 if (FuncGroups > 1) { 929 auto FuncName = llvm::ArrayRef<uint8_t>(CurFn->getName().bytes_begin(), 930 CurFn->getName().bytes_end()); 931 auto Group = crc32(FuncName) % FuncGroups; 932 if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup && 933 !AlwaysXRayAttr) 934 Fn->addFnAttr("function-instrument", "xray-never"); 935 } 936 } 937 938 if (CGM.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone) { 939 switch (CGM.isFunctionBlockedFromProfileInstr(Fn, Loc)) { 940 case ProfileList::Skip: 941 Fn->addFnAttr(llvm::Attribute::SkipProfile); 942 break; 943 case ProfileList::Forbid: 944 Fn->addFnAttr(llvm::Attribute::NoProfile); 945 break; 946 case ProfileList::Allow: 947 break; 948 } 949 } 950 951 unsigned Count, Offset; 952 if (const auto *Attr = 953 D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) { 954 Count = Attr->getCount(); 955 Offset = Attr->getOffset(); 956 } else { 957 Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount; 958 Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset; 959 } 960 if (Count && Offset <= Count) { 961 Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset)); 962 if (Offset) 963 Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset)); 964 } 965 // Instruct that functions for COFF/CodeView targets should start with a 966 // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64 967 // backends as they don't need it -- instructions on these architectures are 968 // always atomically patchable at runtime. 969 if (CGM.getCodeGenOpts().HotPatch && 970 getContext().getTargetInfo().getTriple().isX86() && 971 getContext().getTargetInfo().getTriple().getEnvironment() != 972 llvm::Triple::CODE16) 973 Fn->addFnAttr("patchable-function", "prologue-short-redirect"); 974 975 // Add no-jump-tables value. 976 if (CGM.getCodeGenOpts().NoUseJumpTables) 977 Fn->addFnAttr("no-jump-tables", "true"); 978 979 // Add no-inline-line-tables value. 980 if (CGM.getCodeGenOpts().NoInlineLineTables) 981 Fn->addFnAttr("no-inline-line-tables"); 982 983 // Add profile-sample-accurate value. 984 if (CGM.getCodeGenOpts().ProfileSampleAccurate) 985 Fn->addFnAttr("profile-sample-accurate"); 986 987 if (!CGM.getCodeGenOpts().SampleProfileFile.empty()) 988 Fn->addFnAttr("use-sample-profile"); 989 990 if (D && D->hasAttr<CFICanonicalJumpTableAttr>()) 991 Fn->addFnAttr("cfi-canonical-jump-table"); 992 993 if (D && D->hasAttr<NoProfileFunctionAttr>()) 994 Fn->addFnAttr(llvm::Attribute::NoProfile); 995 996 if (D && D->hasAttr<HybridPatchableAttr>()) 997 Fn->addFnAttr(llvm::Attribute::HybridPatchable); 998 999 if (D) { 1000 // Function attributes take precedence over command line flags. 1001 if (auto *A = D->getAttr<FunctionReturnThunksAttr>()) { 1002 switch (A->getThunkType()) { 1003 case FunctionReturnThunksAttr::Kind::Keep: 1004 break; 1005 case FunctionReturnThunksAttr::Kind::Extern: 1006 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern); 1007 break; 1008 } 1009 } else if (CGM.getCodeGenOpts().FunctionReturnThunks) 1010 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern); 1011 } 1012 1013 if (FD && (getLangOpts().OpenCL || 1014 (getLangOpts().HIP && getLangOpts().CUDAIsDevice))) { 1015 // Add metadata for a kernel function. 1016 EmitKernelMetadata(FD, Fn); 1017 } 1018 1019 if (FD && FD->hasAttr<ClspvLibclcBuiltinAttr>()) { 1020 Fn->setMetadata("clspv_libclc_builtin", 1021 llvm::MDNode::get(getLLVMContext(), {})); 1022 } 1023 1024 // If we are checking function types, emit a function type signature as 1025 // prologue data. 1026 if (FD && SanOpts.has(SanitizerKind::Function)) { 1027 if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) { 1028 llvm::LLVMContext &Ctx = Fn->getContext(); 1029 llvm::MDBuilder MDB(Ctx); 1030 Fn->setMetadata( 1031 llvm::LLVMContext::MD_func_sanitize, 1032 MDB.createRTTIPointerPrologue( 1033 PrologueSig, getUBSanFunctionTypeHash(FD->getType()))); 1034 } 1035 } 1036 1037 // If we're checking nullability, we need to know whether we can check the 1038 // return value. Initialize the flag to 'true' and refine it in EmitParmDecl. 1039 if (SanOpts.has(SanitizerKind::NullabilityReturn)) { 1040 auto Nullability = FnRetTy->getNullability(); 1041 if (Nullability && *Nullability == NullabilityKind::NonNull && 1042 !FnRetTy->isRecordType()) { 1043 if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && 1044 CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>())) 1045 RetValNullabilityPrecondition = 1046 llvm::ConstantInt::getTrue(getLLVMContext()); 1047 } 1048 } 1049 1050 // If we're in C++ mode and the function name is "main", it is guaranteed 1051 // to be norecurse by the standard (3.6.1.3 "The function main shall not be 1052 // used within a program"). 1053 // 1054 // OpenCL C 2.0 v2.2-11 s6.9.i: 1055 // Recursion is not supported. 1056 // 1057 // SYCL v1.2.1 s3.10: 1058 // kernels cannot include RTTI information, exception classes, 1059 // recursive code, virtual functions or make use of C++ libraries that 1060 // are not compiled for the device. 1061 if (FD && ((getLangOpts().CPlusPlus && FD->isMain()) || 1062 getLangOpts().OpenCL || getLangOpts().SYCLIsDevice || 1063 (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>()))) 1064 Fn->addFnAttr(llvm::Attribute::NoRecurse); 1065 1066 llvm::RoundingMode RM = getLangOpts().getDefaultRoundingMode(); 1067 llvm::fp::ExceptionBehavior FPExceptionBehavior = 1068 ToConstrainedExceptMD(getLangOpts().getDefaultExceptionMode()); 1069 Builder.setDefaultConstrainedRounding(RM); 1070 Builder.setDefaultConstrainedExcept(FPExceptionBehavior); 1071 if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) || 1072 (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore || 1073 RM != llvm::RoundingMode::NearestTiesToEven))) { 1074 Builder.setIsFPConstrained(true); 1075 Fn->addFnAttr(llvm::Attribute::StrictFP); 1076 } 1077 1078 // If a custom alignment is used, force realigning to this alignment on 1079 // any main function which certainly will need it. 1080 if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) && 1081 CGM.getCodeGenOpts().StackAlignment)) 1082 Fn->addFnAttr("stackrealign"); 1083 1084 // "main" doesn't need to zero out call-used registers. 1085 if (FD && FD->isMain()) 1086 Fn->removeFnAttr("zero-call-used-regs"); 1087 1088 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 1089 1090 // Create a marker to make it easy to insert allocas into the entryblock 1091 // later. Don't create this with the builder, because we don't want it 1092 // folded. 1093 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 1094 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB); 1095 1096 ReturnBlock = getJumpDestInCurrentScope("return"); 1097 1098 Builder.SetInsertPoint(EntryBB); 1099 1100 // If we're checking the return value, allocate space for a pointer to a 1101 // precise source location of the checked return statement. 1102 if (requiresReturnValueCheck()) { 1103 ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr"); 1104 Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy), 1105 ReturnLocation); 1106 } 1107 1108 // Emit subprogram debug descriptor. 1109 if (CGDebugInfo *DI = getDebugInfo()) { 1110 // Reconstruct the type from the argument list so that implicit parameters, 1111 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling 1112 // convention. 1113 DI->emitFunctionStart(GD, Loc, StartLoc, 1114 DI->getFunctionType(FD, RetTy, Args), CurFn, 1115 CurFuncIsThunk); 1116 } 1117 1118 if (ShouldInstrumentFunction()) { 1119 if (CGM.getCodeGenOpts().InstrumentFunctions) 1120 CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter"); 1121 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining) 1122 CurFn->addFnAttr("instrument-function-entry-inlined", 1123 "__cyg_profile_func_enter"); 1124 if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare) 1125 CurFn->addFnAttr("instrument-function-entry-inlined", 1126 "__cyg_profile_func_enter_bare"); 1127 } 1128 1129 // Since emitting the mcount call here impacts optimizations such as function 1130 // inlining, we just add an attribute to insert a mcount call in backend. 1131 // The attribute "counting-function" is set to mcount function name which is 1132 // architecture dependent. 1133 if (CGM.getCodeGenOpts().InstrumentForProfiling) { 1134 // Calls to fentry/mcount should not be generated if function has 1135 // the no_instrument_function attribute. 1136 if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) { 1137 if (CGM.getCodeGenOpts().CallFEntry) 1138 Fn->addFnAttr("fentry-call", "true"); 1139 else { 1140 Fn->addFnAttr("instrument-function-entry-inlined", 1141 getTarget().getMCountName()); 1142 } 1143 if (CGM.getCodeGenOpts().MNopMCount) { 1144 if (!CGM.getCodeGenOpts().CallFEntry) 1145 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt) 1146 << "-mnop-mcount" << "-mfentry"; 1147 Fn->addFnAttr("mnop-mcount"); 1148 } 1149 1150 if (CGM.getCodeGenOpts().RecordMCount) { 1151 if (!CGM.getCodeGenOpts().CallFEntry) 1152 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt) 1153 << "-mrecord-mcount" << "-mfentry"; 1154 Fn->addFnAttr("mrecord-mcount"); 1155 } 1156 } 1157 } 1158 1159 if (CGM.getCodeGenOpts().PackedStack) { 1160 if (getContext().getTargetInfo().getTriple().getArch() != 1161 llvm::Triple::systemz) 1162 CGM.getDiags().Report(diag::err_opt_not_valid_on_target) 1163 << "-mpacked-stack"; 1164 Fn->addFnAttr("packed-stack"); 1165 } 1166 1167 if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX && 1168 !CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc)) 1169 Fn->addFnAttr("warn-stack-size", 1170 std::to_string(CGM.getCodeGenOpts().WarnStackSize)); 1171 1172 if (RetTy->isVoidType()) { 1173 // Void type; nothing to return. 1174 ReturnValue = Address::invalid(); 1175 1176 // Count the implicit return. 1177 if (!endsWithReturn(D)) 1178 ++NumReturnExprs; 1179 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) { 1180 // Indirect return; emit returned value directly into sret slot. 1181 // This reduces code size, and affects correctness in C++. 1182 auto AI = CurFn->arg_begin(); 1183 if (CurFnInfo->getReturnInfo().isSRetAfterThis()) 1184 ++AI; 1185 ReturnValue = makeNaturalAddressForPointer( 1186 &*AI, RetTy, CurFnInfo->getReturnInfo().getIndirectAlign(), false, 1187 nullptr, nullptr, KnownNonNull); 1188 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) { 1189 ReturnValuePointer = 1190 CreateDefaultAlignTempAlloca(ReturnValue.getType(), "result.ptr"); 1191 Builder.CreateStore(ReturnValue.emitRawPointer(*this), 1192 ReturnValuePointer); 1193 } 1194 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca && 1195 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 1196 // Load the sret pointer from the argument struct and return into that. 1197 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex(); 1198 llvm::Function::arg_iterator EI = CurFn->arg_end(); 1199 --EI; 1200 llvm::Value *Addr = Builder.CreateStructGEP( 1201 CurFnInfo->getArgStruct(), &*EI, Idx); 1202 llvm::Type *Ty = 1203 cast<llvm::GetElementPtrInst>(Addr)->getResultElementType(); 1204 ReturnValuePointer = Address(Addr, Ty, getPointerAlign()); 1205 Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result"); 1206 ReturnValue = Address(Addr, ConvertType(RetTy), 1207 CGM.getNaturalTypeAlignment(RetTy), KnownNonNull); 1208 } else { 1209 ReturnValue = CreateIRTemp(RetTy, "retval"); 1210 1211 // Tell the epilog emitter to autorelease the result. We do this 1212 // now so that various specialized functions can suppress it 1213 // during their IR-generation. 1214 if (getLangOpts().ObjCAutoRefCount && 1215 !CurFnInfo->isReturnsRetained() && 1216 RetTy->isObjCRetainableType()) 1217 AutoreleaseResult = true; 1218 } 1219 1220 EmitStartEHSpec(CurCodeDecl); 1221 1222 PrologueCleanupDepth = EHStack.stable_begin(); 1223 1224 // Emit OpenMP specific initialization of the device functions. 1225 if (getLangOpts().OpenMP && CurCodeDecl) 1226 CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl); 1227 1228 // Handle emitting HLSL entry functions. 1229 if (D && D->hasAttr<HLSLShaderAttr>()) 1230 CGM.getHLSLRuntime().emitEntryFunction(FD, Fn); 1231 1232 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 1233 1234 if (const CXXMethodDecl *MD = dyn_cast_if_present<CXXMethodDecl>(D); 1235 MD && !MD->isStatic()) { 1236 bool IsInLambda = 1237 MD->getParent()->isLambda() && MD->getOverloadedOperator() == OO_Call; 1238 if (MD->isImplicitObjectMemberFunction()) 1239 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 1240 if (IsInLambda) { 1241 // We're in a lambda; figure out the captures. 1242 MD->getParent()->getCaptureFields(LambdaCaptureFields, 1243 LambdaThisCaptureField); 1244 if (LambdaThisCaptureField) { 1245 // If the lambda captures the object referred to by '*this' - either by 1246 // value or by reference, make sure CXXThisValue points to the correct 1247 // object. 1248 1249 // Get the lvalue for the field (which is a copy of the enclosing object 1250 // or contains the address of the enclosing object). 1251 LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField); 1252 if (!LambdaThisCaptureField->getType()->isPointerType()) { 1253 // If the enclosing object was captured by value, just use its 1254 // address. Sign this pointer. 1255 CXXThisValue = ThisFieldLValue.getPointer(*this); 1256 } else { 1257 // Load the lvalue pointed to by the field, since '*this' was captured 1258 // by reference. 1259 CXXThisValue = 1260 EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal(); 1261 } 1262 } 1263 for (auto *FD : MD->getParent()->fields()) { 1264 if (FD->hasCapturedVLAType()) { 1265 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD), 1266 SourceLocation()).getScalarVal(); 1267 auto VAT = FD->getCapturedVLAType(); 1268 VLASizeMap[VAT->getSizeExpr()] = ExprArg; 1269 } 1270 } 1271 } else if (MD->isImplicitObjectMemberFunction()) { 1272 // Not in a lambda; just use 'this' from the method. 1273 // FIXME: Should we generate a new load for each use of 'this'? The 1274 // fast register allocator would be happier... 1275 CXXThisValue = CXXABIThisValue; 1276 } 1277 1278 // Check the 'this' pointer once per function, if it's available. 1279 if (CXXABIThisValue) { 1280 SanitizerSet SkippedChecks; 1281 SkippedChecks.set(SanitizerKind::ObjectSize, true); 1282 QualType ThisTy = MD->getThisType(); 1283 1284 // If this is the call operator of a lambda with no captures, it 1285 // may have a static invoker function, which may call this operator with 1286 // a null 'this' pointer. 1287 if (isLambdaCallOperator(MD) && MD->getParent()->isCapturelessLambda()) 1288 SkippedChecks.set(SanitizerKind::Null, true); 1289 1290 EmitTypeCheck( 1291 isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall : TCK_MemberCall, 1292 Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks); 1293 } 1294 } 1295 1296 // If any of the arguments have a variably modified type, make sure to 1297 // emit the type size, but only if the function is not naked. Naked functions 1298 // have no prolog to run this evaluation. 1299 if (!FD || !FD->hasAttr<NakedAttr>()) { 1300 for (const VarDecl *VD : Args) { 1301 // Dig out the type as written from ParmVarDecls; it's unclear whether 1302 // the standard (C99 6.9.1p10) requires this, but we're following the 1303 // precedent set by gcc. 1304 QualType Ty; 1305 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) 1306 Ty = PVD->getOriginalType(); 1307 else 1308 Ty = VD->getType(); 1309 1310 if (Ty->isVariablyModifiedType()) 1311 EmitVariablyModifiedType(Ty); 1312 } 1313 } 1314 // Emit a location at the end of the prologue. 1315 if (CGDebugInfo *DI = getDebugInfo()) 1316 DI->EmitLocation(Builder, StartLoc); 1317 // TODO: Do we need to handle this in two places like we do with 1318 // target-features/target-cpu? 1319 if (CurFuncDecl) 1320 if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>()) 1321 LargestVectorWidth = VecWidth->getVectorWidth(); 1322 1323 if (CGM.shouldEmitConvergenceTokens()) 1324 ConvergenceTokenStack.push_back(getOrEmitConvergenceEntryToken(CurFn)); 1325 } 1326 1327 void CodeGenFunction::EmitFunctionBody(const Stmt *Body) { 1328 incrementProfileCounter(Body); 1329 maybeCreateMCDCCondBitmap(); 1330 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body)) 1331 EmitCompoundStmtWithoutScope(*S); 1332 else 1333 EmitStmt(Body); 1334 } 1335 1336 /// When instrumenting to collect profile data, the counts for some blocks 1337 /// such as switch cases need to not include the fall-through counts, so 1338 /// emit a branch around the instrumentation code. When not instrumenting, 1339 /// this just calls EmitBlock(). 1340 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB, 1341 const Stmt *S) { 1342 llvm::BasicBlock *SkipCountBB = nullptr; 1343 // Do not skip over the instrumentation when single byte coverage mode is 1344 // enabled. 1345 if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr() && 1346 !llvm::EnableSingleByteCoverage) { 1347 // When instrumenting for profiling, the fallthrough to certain 1348 // statements needs to skip over the instrumentation code so that we 1349 // get an accurate count. 1350 SkipCountBB = createBasicBlock("skipcount"); 1351 EmitBranch(SkipCountBB); 1352 } 1353 EmitBlock(BB); 1354 uint64_t CurrentCount = getCurrentProfileCount(); 1355 incrementProfileCounter(S); 1356 setCurrentProfileCount(getCurrentProfileCount() + CurrentCount); 1357 if (SkipCountBB) 1358 EmitBlock(SkipCountBB); 1359 } 1360 1361 /// Tries to mark the given function nounwind based on the 1362 /// non-existence of any throwing calls within it. We believe this is 1363 /// lightweight enough to do at -O0. 1364 static void TryMarkNoThrow(llvm::Function *F) { 1365 // LLVM treats 'nounwind' on a function as part of the type, so we 1366 // can't do this on functions that can be overwritten. 1367 if (F->isInterposable()) return; 1368 1369 for (llvm::BasicBlock &BB : *F) 1370 for (llvm::Instruction &I : BB) 1371 if (I.mayThrow()) 1372 return; 1373 1374 F->setDoesNotThrow(); 1375 } 1376 1377 QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD, 1378 FunctionArgList &Args) { 1379 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 1380 QualType ResTy = FD->getReturnType(); 1381 1382 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 1383 if (MD && MD->isImplicitObjectMemberFunction()) { 1384 if (CGM.getCXXABI().HasThisReturn(GD)) 1385 ResTy = MD->getThisType(); 1386 else if (CGM.getCXXABI().hasMostDerivedReturn(GD)) 1387 ResTy = CGM.getContext().VoidPtrTy; 1388 CGM.getCXXABI().buildThisParam(*this, Args); 1389 } 1390 1391 // The base version of an inheriting constructor whose constructed base is a 1392 // virtual base is not passed any arguments (because it doesn't actually call 1393 // the inherited constructor). 1394 bool PassedParams = true; 1395 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 1396 if (auto Inherited = CD->getInheritedConstructor()) 1397 PassedParams = 1398 getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType()); 1399 1400 if (PassedParams) { 1401 for (auto *Param : FD->parameters()) { 1402 Args.push_back(Param); 1403 if (!Param->hasAttr<PassObjectSizeAttr>()) 1404 continue; 1405 1406 auto *Implicit = ImplicitParamDecl::Create( 1407 getContext(), Param->getDeclContext(), Param->getLocation(), 1408 /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamKind::Other); 1409 SizeArguments[Param] = Implicit; 1410 Args.push_back(Implicit); 1411 } 1412 } 1413 1414 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))) 1415 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args); 1416 1417 return ResTy; 1418 } 1419 1420 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1421 const CGFunctionInfo &FnInfo) { 1422 assert(Fn && "generating code for null Function"); 1423 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 1424 CurGD = GD; 1425 1426 FunctionArgList Args; 1427 QualType ResTy = BuildFunctionArgList(GD, Args); 1428 1429 CGM.getTargetCodeGenInfo().checkFunctionABI(CGM, FD); 1430 1431 if (FD->isInlineBuiltinDeclaration()) { 1432 // When generating code for a builtin with an inline declaration, use a 1433 // mangled name to hold the actual body, while keeping an external 1434 // definition in case the function pointer is referenced somewhere. 1435 std::string FDInlineName = (Fn->getName() + ".inline").str(); 1436 llvm::Module *M = Fn->getParent(); 1437 llvm::Function *Clone = M->getFunction(FDInlineName); 1438 if (!Clone) { 1439 Clone = llvm::Function::Create(Fn->getFunctionType(), 1440 llvm::GlobalValue::InternalLinkage, 1441 Fn->getAddressSpace(), FDInlineName, M); 1442 Clone->addFnAttr(llvm::Attribute::AlwaysInline); 1443 } 1444 Fn->setLinkage(llvm::GlobalValue::ExternalLinkage); 1445 Fn = Clone; 1446 } else { 1447 // Detect the unusual situation where an inline version is shadowed by a 1448 // non-inline version. In that case we should pick the external one 1449 // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way 1450 // to detect that situation before we reach codegen, so do some late 1451 // replacement. 1452 for (const FunctionDecl *PD = FD->getPreviousDecl(); PD; 1453 PD = PD->getPreviousDecl()) { 1454 if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) { 1455 std::string FDInlineName = (Fn->getName() + ".inline").str(); 1456 llvm::Module *M = Fn->getParent(); 1457 if (llvm::Function *Clone = M->getFunction(FDInlineName)) { 1458 Clone->replaceAllUsesWith(Fn); 1459 Clone->eraseFromParent(); 1460 } 1461 break; 1462 } 1463 } 1464 } 1465 1466 // Check if we should generate debug info for this function. 1467 if (FD->hasAttr<NoDebugAttr>()) { 1468 // Clear non-distinct debug info that was possibly attached to the function 1469 // due to an earlier declaration without the nodebug attribute 1470 Fn->setSubprogram(nullptr); 1471 // Disable debug info indefinitely for this function 1472 DebugInfo = nullptr; 1473 } 1474 1475 // The function might not have a body if we're generating thunks for a 1476 // function declaration. 1477 SourceRange BodyRange; 1478 if (Stmt *Body = FD->getBody()) 1479 BodyRange = Body->getSourceRange(); 1480 else 1481 BodyRange = FD->getLocation(); 1482 CurEHLocation = BodyRange.getEnd(); 1483 1484 // Use the location of the start of the function to determine where 1485 // the function definition is located. By default use the location 1486 // of the declaration as the location for the subprogram. A function 1487 // may lack a declaration in the source code if it is created by code 1488 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 1489 SourceLocation Loc = FD->getLocation(); 1490 1491 // If this is a function specialization then use the pattern body 1492 // as the location for the function. 1493 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern()) 1494 if (SpecDecl->hasBody(SpecDecl)) 1495 Loc = SpecDecl->getLocation(); 1496 1497 Stmt *Body = FD->getBody(); 1498 1499 if (Body) { 1500 // Coroutines always emit lifetime markers. 1501 if (isa<CoroutineBodyStmt>(Body)) 1502 ShouldEmitLifetimeMarkers = true; 1503 1504 // Initialize helper which will detect jumps which can cause invalid 1505 // lifetime markers. 1506 if (ShouldEmitLifetimeMarkers) 1507 Bypasses.Init(Body); 1508 } 1509 1510 // Emit the standard function prologue. 1511 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin()); 1512 1513 // Save parameters for coroutine function. 1514 if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body)) 1515 llvm::append_range(FnArgs, FD->parameters()); 1516 1517 // Ensure that the function adheres to the forward progress guarantee, which 1518 // is required by certain optimizations. 1519 // In C++11 and up, the attribute will be removed if the body contains a 1520 // trivial empty loop. 1521 if (checkIfFunctionMustProgress()) 1522 CurFn->addFnAttr(llvm::Attribute::MustProgress); 1523 1524 // Generate the body of the function. 1525 PGO.assignRegionCounters(GD, CurFn); 1526 if (isa<CXXDestructorDecl>(FD)) 1527 EmitDestructorBody(Args); 1528 else if (isa<CXXConstructorDecl>(FD)) 1529 EmitConstructorBody(Args); 1530 else if (getLangOpts().CUDA && 1531 !getLangOpts().CUDAIsDevice && 1532 FD->hasAttr<CUDAGlobalAttr>()) 1533 CGM.getCUDARuntime().emitDeviceStub(*this, Args); 1534 else if (isa<CXXMethodDecl>(FD) && 1535 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) { 1536 // The lambda static invoker function is special, because it forwards or 1537 // clones the body of the function call operator (but is actually static). 1538 EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD)); 1539 } else if (isa<CXXMethodDecl>(FD) && 1540 isLambdaCallOperator(cast<CXXMethodDecl>(FD)) && 1541 !FnInfo.isDelegateCall() && 1542 cast<CXXMethodDecl>(FD)->getParent()->getLambdaStaticInvoker() && 1543 hasInAllocaArg(cast<CXXMethodDecl>(FD))) { 1544 // If emitting a lambda with static invoker on X86 Windows, change 1545 // the call operator body. 1546 // Make sure that this is a call operator with an inalloca arg and check 1547 // for delegate call to make sure this is the original call op and not the 1548 // new forwarding function for the static invoker. 1549 EmitLambdaInAllocaCallOpBody(cast<CXXMethodDecl>(FD)); 1550 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) && 1551 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() || 1552 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) { 1553 // Implicit copy-assignment gets the same special treatment as implicit 1554 // copy-constructors. 1555 emitImplicitAssignmentOperatorBody(Args); 1556 } else if (Body) { 1557 EmitFunctionBody(Body); 1558 } else 1559 llvm_unreachable("no definition for emitted function"); 1560 1561 // C++11 [stmt.return]p2: 1562 // Flowing off the end of a function [...] results in undefined behavior in 1563 // a value-returning function. 1564 // C11 6.9.1p12: 1565 // If the '}' that terminates a function is reached, and the value of the 1566 // function call is used by the caller, the behavior is undefined. 1567 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock && 1568 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) { 1569 bool ShouldEmitUnreachable = 1570 CGM.getCodeGenOpts().StrictReturn || 1571 !CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType()); 1572 if (SanOpts.has(SanitizerKind::Return)) { 1573 SanitizerScope SanScope(this); 1574 llvm::Value *IsFalse = Builder.getFalse(); 1575 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return), 1576 SanitizerHandler::MissingReturn, 1577 EmitCheckSourceLocation(FD->getLocation()), std::nullopt); 1578 } else if (ShouldEmitUnreachable) { 1579 if (CGM.getCodeGenOpts().OptimizationLevel == 0) 1580 EmitTrapCall(llvm::Intrinsic::trap); 1581 } 1582 if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) { 1583 Builder.CreateUnreachable(); 1584 Builder.ClearInsertionPoint(); 1585 } 1586 } 1587 1588 // Emit the standard function epilogue. 1589 FinishFunction(BodyRange.getEnd()); 1590 1591 // If we haven't marked the function nothrow through other means, do 1592 // a quick pass now to see if we can. 1593 if (!CurFn->doesNotThrow()) 1594 TryMarkNoThrow(CurFn); 1595 } 1596 1597 /// ContainsLabel - Return true if the statement contains a label in it. If 1598 /// this statement is not executed normally, it not containing a label means 1599 /// that we can just remove the code. 1600 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 1601 // Null statement, not a label! 1602 if (!S) return false; 1603 1604 // If this is a label, we have to emit the code, consider something like: 1605 // if (0) { ... foo: bar(); } goto foo; 1606 // 1607 // TODO: If anyone cared, we could track __label__'s, since we know that you 1608 // can't jump to one from outside their declared region. 1609 if (isa<LabelStmt>(S)) 1610 return true; 1611 1612 // If this is a case/default statement, and we haven't seen a switch, we have 1613 // to emit the code. 1614 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 1615 return true; 1616 1617 // If this is a switch statement, we want to ignore cases below it. 1618 if (isa<SwitchStmt>(S)) 1619 IgnoreCaseStmts = true; 1620 1621 // Scan subexpressions for verboten labels. 1622 for (const Stmt *SubStmt : S->children()) 1623 if (ContainsLabel(SubStmt, IgnoreCaseStmts)) 1624 return true; 1625 1626 return false; 1627 } 1628 1629 /// containsBreak - Return true if the statement contains a break out of it. 1630 /// If the statement (recursively) contains a switch or loop with a break 1631 /// inside of it, this is fine. 1632 bool CodeGenFunction::containsBreak(const Stmt *S) { 1633 // Null statement, not a label! 1634 if (!S) return false; 1635 1636 // If this is a switch or loop that defines its own break scope, then we can 1637 // include it and anything inside of it. 1638 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || 1639 isa<ForStmt>(S)) 1640 return false; 1641 1642 if (isa<BreakStmt>(S)) 1643 return true; 1644 1645 // Scan subexpressions for verboten breaks. 1646 for (const Stmt *SubStmt : S->children()) 1647 if (containsBreak(SubStmt)) 1648 return true; 1649 1650 return false; 1651 } 1652 1653 bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) { 1654 if (!S) return false; 1655 1656 // Some statement kinds add a scope and thus never add a decl to the current 1657 // scope. Note, this list is longer than the list of statements that might 1658 // have an unscoped decl nested within them, but this way is conservatively 1659 // correct even if more statement kinds are added. 1660 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) || 1661 isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) || 1662 isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) || 1663 isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S)) 1664 return false; 1665 1666 if (isa<DeclStmt>(S)) 1667 return true; 1668 1669 for (const Stmt *SubStmt : S->children()) 1670 if (mightAddDeclToScope(SubStmt)) 1671 return true; 1672 1673 return false; 1674 } 1675 1676 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1677 /// to a constant, or if it does but contains a label, return false. If it 1678 /// constant folds return true and set the boolean result in Result. 1679 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1680 bool &ResultBool, 1681 bool AllowLabels) { 1682 // If MC/DC is enabled, disable folding so that we can instrument all 1683 // conditions to yield complete test vectors. We still keep track of 1684 // folded conditions during region mapping and visualization. 1685 if (!AllowLabels && CGM.getCodeGenOpts().hasProfileClangInstr() && 1686 CGM.getCodeGenOpts().MCDCCoverage) 1687 return false; 1688 1689 llvm::APSInt ResultInt; 1690 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels)) 1691 return false; 1692 1693 ResultBool = ResultInt.getBoolValue(); 1694 return true; 1695 } 1696 1697 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1698 /// to a constant, or if it does but contains a label, return false. If it 1699 /// constant folds return true and set the folded value. 1700 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1701 llvm::APSInt &ResultInt, 1702 bool AllowLabels) { 1703 // FIXME: Rename and handle conversion of other evaluatable things 1704 // to bool. 1705 Expr::EvalResult Result; 1706 if (!Cond->EvaluateAsInt(Result, getContext())) 1707 return false; // Not foldable, not integer or not fully evaluatable. 1708 1709 llvm::APSInt Int = Result.Val.getInt(); 1710 if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond)) 1711 return false; // Contains a label. 1712 1713 ResultInt = Int; 1714 return true; 1715 } 1716 1717 /// Strip parentheses and simplistic logical-NOT operators. 1718 const Expr *CodeGenFunction::stripCond(const Expr *C) { 1719 while (const UnaryOperator *Op = dyn_cast<UnaryOperator>(C->IgnoreParens())) { 1720 if (Op->getOpcode() != UO_LNot) 1721 break; 1722 C = Op->getSubExpr(); 1723 } 1724 return C->IgnoreParens(); 1725 } 1726 1727 /// Determine whether the given condition is an instrumentable condition 1728 /// (i.e. no "&&" or "||"). 1729 bool CodeGenFunction::isInstrumentedCondition(const Expr *C) { 1730 const BinaryOperator *BOp = dyn_cast<BinaryOperator>(stripCond(C)); 1731 return (!BOp || !BOp->isLogicalOp()); 1732 } 1733 1734 /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that 1735 /// increments a profile counter based on the semantics of the given logical 1736 /// operator opcode. This is used to instrument branch condition coverage for 1737 /// logical operators. 1738 void CodeGenFunction::EmitBranchToCounterBlock( 1739 const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock, 1740 llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */, 1741 Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) { 1742 // If not instrumenting, just emit a branch. 1743 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr(); 1744 if (!InstrumentRegions || !isInstrumentedCondition(Cond)) 1745 return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH); 1746 1747 llvm::BasicBlock *ThenBlock = nullptr; 1748 llvm::BasicBlock *ElseBlock = nullptr; 1749 llvm::BasicBlock *NextBlock = nullptr; 1750 1751 // Create the block we'll use to increment the appropriate counter. 1752 llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt"); 1753 1754 // Set block pointers according to Logical-AND (BO_LAnd) semantics. This 1755 // means we need to evaluate the condition and increment the counter on TRUE: 1756 // 1757 // if (Cond) 1758 // goto CounterIncrBlock; 1759 // else 1760 // goto FalseBlock; 1761 // 1762 // CounterIncrBlock: 1763 // Counter++; 1764 // goto TrueBlock; 1765 1766 if (LOp == BO_LAnd) { 1767 ThenBlock = CounterIncrBlock; 1768 ElseBlock = FalseBlock; 1769 NextBlock = TrueBlock; 1770 } 1771 1772 // Set block pointers according to Logical-OR (BO_LOr) semantics. This means 1773 // we need to evaluate the condition and increment the counter on FALSE: 1774 // 1775 // if (Cond) 1776 // goto TrueBlock; 1777 // else 1778 // goto CounterIncrBlock; 1779 // 1780 // CounterIncrBlock: 1781 // Counter++; 1782 // goto FalseBlock; 1783 1784 else if (LOp == BO_LOr) { 1785 ThenBlock = TrueBlock; 1786 ElseBlock = CounterIncrBlock; 1787 NextBlock = FalseBlock; 1788 } else { 1789 llvm_unreachable("Expected Opcode must be that of a Logical Operator"); 1790 } 1791 1792 // Emit Branch based on condition. 1793 EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH); 1794 1795 // Emit the block containing the counter increment(s). 1796 EmitBlock(CounterIncrBlock); 1797 1798 // Increment corresponding counter; if index not provided, use Cond as index. 1799 incrementProfileCounter(CntrIdx ? CntrIdx : Cond); 1800 1801 // Go to the next block. 1802 EmitBranch(NextBlock); 1803 } 1804 1805 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 1806 /// statement) to the specified blocks. Based on the condition, this might try 1807 /// to simplify the codegen of the conditional based on the branch. 1808 /// \param LH The value of the likelihood attribute on the True branch. 1809 /// \param ConditionalOp Used by MC/DC code coverage to track the result of the 1810 /// ConditionalOperator (ternary) through a recursive call for the operator's 1811 /// LHS and RHS nodes. 1812 void CodeGenFunction::EmitBranchOnBoolExpr( 1813 const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, 1814 uint64_t TrueCount, Stmt::Likelihood LH, const Expr *ConditionalOp) { 1815 Cond = Cond->IgnoreParens(); 1816 1817 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 1818 // Handle X && Y in a condition. 1819 if (CondBOp->getOpcode() == BO_LAnd) { 1820 MCDCLogOpStack.push_back(CondBOp); 1821 1822 // If we have "1 && X", simplify the code. "0 && X" would have constant 1823 // folded if the case was simple enough. 1824 bool ConstantBool = false; 1825 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1826 ConstantBool) { 1827 // br(1 && X) -> br(X). 1828 incrementProfileCounter(CondBOp); 1829 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock, 1830 FalseBlock, TrueCount, LH); 1831 MCDCLogOpStack.pop_back(); 1832 return; 1833 } 1834 1835 // If we have "X && 1", simplify the code to use an uncond branch. 1836 // "X && 0" would have been constant folded to 0. 1837 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1838 ConstantBool) { 1839 // br(X && 1) -> br(X). 1840 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock, 1841 FalseBlock, TrueCount, LH, CondBOp); 1842 MCDCLogOpStack.pop_back(); 1843 return; 1844 } 1845 1846 // Emit the LHS as a conditional. If the LHS conditional is false, we 1847 // want to jump to the FalseBlock. 1848 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 1849 // The counter tells us how often we evaluate RHS, and all of TrueCount 1850 // can be propagated to that branch. 1851 uint64_t RHSCount = getProfileCount(CondBOp->getRHS()); 1852 1853 ConditionalEvaluation eval(*this); 1854 { 1855 ApplyDebugLocation DL(*this, Cond); 1856 // Propagate the likelihood attribute like __builtin_expect 1857 // __builtin_expect(X && Y, 1) -> X and Y are likely 1858 // __builtin_expect(X && Y, 0) -> only Y is unlikely 1859 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount, 1860 LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH); 1861 EmitBlock(LHSTrue); 1862 } 1863 1864 incrementProfileCounter(CondBOp); 1865 setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1866 1867 // Any temporaries created here are conditional. 1868 eval.begin(*this); 1869 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock, 1870 FalseBlock, TrueCount, LH); 1871 eval.end(*this); 1872 MCDCLogOpStack.pop_back(); 1873 return; 1874 } 1875 1876 if (CondBOp->getOpcode() == BO_LOr) { 1877 MCDCLogOpStack.push_back(CondBOp); 1878 1879 // If we have "0 || X", simplify the code. "1 || X" would have constant 1880 // folded if the case was simple enough. 1881 bool ConstantBool = false; 1882 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1883 !ConstantBool) { 1884 // br(0 || X) -> br(X). 1885 incrementProfileCounter(CondBOp); 1886 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, 1887 FalseBlock, TrueCount, LH); 1888 MCDCLogOpStack.pop_back(); 1889 return; 1890 } 1891 1892 // If we have "X || 0", simplify the code to use an uncond branch. 1893 // "X || 1" would have been constant folded to 1. 1894 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1895 !ConstantBool) { 1896 // br(X || 0) -> br(X). 1897 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock, 1898 FalseBlock, TrueCount, LH, CondBOp); 1899 MCDCLogOpStack.pop_back(); 1900 return; 1901 } 1902 // Emit the LHS as a conditional. If the LHS conditional is true, we 1903 // want to jump to the TrueBlock. 1904 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 1905 // We have the count for entry to the RHS and for the whole expression 1906 // being true, so we can divy up True count between the short circuit and 1907 // the RHS. 1908 uint64_t LHSCount = 1909 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS()); 1910 uint64_t RHSCount = TrueCount - LHSCount; 1911 1912 ConditionalEvaluation eval(*this); 1913 { 1914 // Propagate the likelihood attribute like __builtin_expect 1915 // __builtin_expect(X || Y, 1) -> only Y is likely 1916 // __builtin_expect(X || Y, 0) -> both X and Y are unlikely 1917 ApplyDebugLocation DL(*this, Cond); 1918 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount, 1919 LH == Stmt::LH_Likely ? Stmt::LH_None : LH); 1920 EmitBlock(LHSFalse); 1921 } 1922 1923 incrementProfileCounter(CondBOp); 1924 setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1925 1926 // Any temporaries created here are conditional. 1927 eval.begin(*this); 1928 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock, 1929 RHSCount, LH); 1930 1931 eval.end(*this); 1932 MCDCLogOpStack.pop_back(); 1933 return; 1934 } 1935 } 1936 1937 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 1938 // br(!x, t, f) -> br(x, f, t) 1939 // Avoid doing this optimization when instrumenting a condition for MC/DC. 1940 // LNot is taken as part of the condition for simplicity, and changing its 1941 // sense negatively impacts test vector tracking. 1942 bool MCDCCondition = CGM.getCodeGenOpts().hasProfileClangInstr() && 1943 CGM.getCodeGenOpts().MCDCCoverage && 1944 isInstrumentedCondition(Cond); 1945 if (CondUOp->getOpcode() == UO_LNot && !MCDCCondition) { 1946 // Negate the count. 1947 uint64_t FalseCount = getCurrentProfileCount() - TrueCount; 1948 // The values of the enum are chosen to make this negation possible. 1949 LH = static_cast<Stmt::Likelihood>(-LH); 1950 // Negate the condition and swap the destination blocks. 1951 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock, 1952 FalseCount, LH); 1953 } 1954 } 1955 1956 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 1957 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 1958 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 1959 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 1960 1961 // The ConditionalOperator itself has no likelihood information for its 1962 // true and false branches. This matches the behavior of __builtin_expect. 1963 ConditionalEvaluation cond(*this); 1964 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, 1965 getProfileCount(CondOp), Stmt::LH_None); 1966 1967 // When computing PGO branch weights, we only know the overall count for 1968 // the true block. This code is essentially doing tail duplication of the 1969 // naive code-gen, introducing new edges for which counts are not 1970 // available. Divide the counts proportionally between the LHS and RHS of 1971 // the conditional operator. 1972 uint64_t LHSScaledTrueCount = 0; 1973 if (TrueCount) { 1974 double LHSRatio = 1975 getProfileCount(CondOp) / (double)getCurrentProfileCount(); 1976 LHSScaledTrueCount = TrueCount * LHSRatio; 1977 } 1978 1979 cond.begin(*this); 1980 EmitBlock(LHSBlock); 1981 incrementProfileCounter(CondOp); 1982 { 1983 ApplyDebugLocation DL(*this, Cond); 1984 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock, 1985 LHSScaledTrueCount, LH, CondOp); 1986 } 1987 cond.end(*this); 1988 1989 cond.begin(*this); 1990 EmitBlock(RHSBlock); 1991 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock, 1992 TrueCount - LHSScaledTrueCount, LH, CondOp); 1993 cond.end(*this); 1994 1995 return; 1996 } 1997 1998 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) { 1999 // Conditional operator handling can give us a throw expression as a 2000 // condition for a case like: 2001 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f) 2002 // Fold this to: 2003 // br(c, throw x, br(y, t, f)) 2004 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false); 2005 return; 2006 } 2007 2008 // Emit the code with the fully general case. 2009 llvm::Value *CondV; 2010 { 2011 ApplyDebugLocation DL(*this, Cond); 2012 CondV = EvaluateExprAsBool(Cond); 2013 } 2014 2015 // If not at the top of the logical operator nest, update MCDC temp with the 2016 // boolean result of the evaluated condition. 2017 if (!MCDCLogOpStack.empty()) { 2018 const Expr *MCDCBaseExpr = Cond; 2019 // When a nested ConditionalOperator (ternary) is encountered in a boolean 2020 // expression, MC/DC tracks the result of the ternary, and this is tied to 2021 // the ConditionalOperator expression and not the ternary's LHS or RHS. If 2022 // this is the case, the ConditionalOperator expression is passed through 2023 // the ConditionalOp parameter and then used as the MCDC base expression. 2024 if (ConditionalOp) 2025 MCDCBaseExpr = ConditionalOp; 2026 2027 maybeUpdateMCDCCondBitmap(MCDCBaseExpr, CondV); 2028 } 2029 2030 llvm::MDNode *Weights = nullptr; 2031 llvm::MDNode *Unpredictable = nullptr; 2032 2033 // If the branch has a condition wrapped by __builtin_unpredictable, 2034 // create metadata that specifies that the branch is unpredictable. 2035 // Don't bother if not optimizing because that metadata would not be used. 2036 auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts()); 2037 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) { 2038 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl()); 2039 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) { 2040 llvm::MDBuilder MDHelper(getLLVMContext()); 2041 Unpredictable = MDHelper.createUnpredictable(); 2042 } 2043 } 2044 2045 // If there is a Likelihood knowledge for the cond, lower it. 2046 // Note that if not optimizing this won't emit anything. 2047 llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH); 2048 if (CondV != NewCondV) 2049 CondV = NewCondV; 2050 else { 2051 // Otherwise, lower profile counts. Note that we do this even at -O0. 2052 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount); 2053 Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount); 2054 } 2055 2056 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable); 2057 } 2058 2059 /// ErrorUnsupported - Print out an error that codegen doesn't support the 2060 /// specified stmt yet. 2061 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) { 2062 CGM.ErrorUnsupported(S, Type); 2063 } 2064 2065 /// emitNonZeroVLAInit - Emit the "zero" initialization of a 2066 /// variable-length array whose elements have a non-zero bit-pattern. 2067 /// 2068 /// \param baseType the inner-most element type of the array 2069 /// \param src - a char* pointing to the bit-pattern for a single 2070 /// base element of the array 2071 /// \param sizeInChars - the total size of the VLA, in chars 2072 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 2073 Address dest, Address src, 2074 llvm::Value *sizeInChars) { 2075 CGBuilderTy &Builder = CGF.Builder; 2076 2077 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType); 2078 llvm::Value *baseSizeInChars 2079 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity()); 2080 2081 Address begin = dest.withElementType(CGF.Int8Ty); 2082 llvm::Value *end = Builder.CreateInBoundsGEP(begin.getElementType(), 2083 begin.emitRawPointer(CGF), 2084 sizeInChars, "vla.end"); 2085 2086 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 2087 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 2088 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 2089 2090 // Make a loop over the VLA. C99 guarantees that the VLA element 2091 // count must be nonzero. 2092 CGF.EmitBlock(loopBB); 2093 2094 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur"); 2095 cur->addIncoming(begin.emitRawPointer(CGF), originBB); 2096 2097 CharUnits curAlign = 2098 dest.getAlignment().alignmentOfArrayElement(baseSize); 2099 2100 // memcpy the individual element bit-pattern. 2101 Builder.CreateMemCpy(Address(cur, CGF.Int8Ty, curAlign), src, baseSizeInChars, 2102 /*volatile*/ false); 2103 2104 // Go to the next element. 2105 llvm::Value *next = 2106 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next"); 2107 2108 // Leave if that's the end of the VLA. 2109 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 2110 Builder.CreateCondBr(done, contBB, loopBB); 2111 cur->addIncoming(next, loopBB); 2112 2113 CGF.EmitBlock(contBB); 2114 } 2115 2116 void 2117 CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) { 2118 // Ignore empty classes in C++. 2119 if (getLangOpts().CPlusPlus) { 2120 if (const RecordType *RT = Ty->getAs<RecordType>()) { 2121 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 2122 return; 2123 } 2124 } 2125 2126 if (DestPtr.getElementType() != Int8Ty) 2127 DestPtr = DestPtr.withElementType(Int8Ty); 2128 2129 // Get size and alignment info for this aggregate. 2130 CharUnits size = getContext().getTypeSizeInChars(Ty); 2131 2132 llvm::Value *SizeVal; 2133 const VariableArrayType *vla; 2134 2135 // Don't bother emitting a zero-byte memset. 2136 if (size.isZero()) { 2137 // But note that getTypeInfo returns 0 for a VLA. 2138 if (const VariableArrayType *vlaType = 2139 dyn_cast_or_null<VariableArrayType>( 2140 getContext().getAsArrayType(Ty))) { 2141 auto VlaSize = getVLASize(vlaType); 2142 SizeVal = VlaSize.NumElts; 2143 CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type); 2144 if (!eltSize.isOne()) 2145 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize)); 2146 vla = vlaType; 2147 } else { 2148 return; 2149 } 2150 } else { 2151 SizeVal = CGM.getSize(size); 2152 vla = nullptr; 2153 } 2154 2155 // If the type contains a pointer to data member we can't memset it to zero. 2156 // Instead, create a null constant and copy it to the destination. 2157 // TODO: there are other patterns besides zero that we can usefully memset, 2158 // like -1, which happens to be the pattern used by member-pointers. 2159 if (!CGM.getTypes().isZeroInitializable(Ty)) { 2160 // For a VLA, emit a single element, then splat that over the VLA. 2161 if (vla) Ty = getContext().getBaseElementType(vla); 2162 2163 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 2164 2165 llvm::GlobalVariable *NullVariable = 2166 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 2167 /*isConstant=*/true, 2168 llvm::GlobalVariable::PrivateLinkage, 2169 NullConstant, Twine()); 2170 CharUnits NullAlign = DestPtr.getAlignment(); 2171 NullVariable->setAlignment(NullAlign.getAsAlign()); 2172 Address SrcPtr(NullVariable, Builder.getInt8Ty(), NullAlign); 2173 2174 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 2175 2176 // Get and call the appropriate llvm.memcpy overload. 2177 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false); 2178 return; 2179 } 2180 2181 // Otherwise, just memset the whole thing to zero. This is legal 2182 // because in LLVM, all default initializers (other than the ones we just 2183 // handled above) are guaranteed to have a bit pattern of all zeros. 2184 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false); 2185 } 2186 2187 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) { 2188 // Make sure that there is a block for the indirect goto. 2189 if (!IndirectBranch) 2190 GetIndirectGotoBlock(); 2191 2192 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 2193 2194 // Make sure the indirect branch includes all of the address-taken blocks. 2195 IndirectBranch->addDestination(BB); 2196 return llvm::BlockAddress::get(CurFn, BB); 2197 } 2198 2199 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 2200 // If we already made the indirect branch for indirect goto, return its block. 2201 if (IndirectBranch) return IndirectBranch->getParent(); 2202 2203 CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto")); 2204 2205 // Create the PHI node that indirect gotos will add entries to. 2206 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0, 2207 "indirect.goto.dest"); 2208 2209 // Create the indirect branch instruction. 2210 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 2211 return IndirectBranch->getParent(); 2212 } 2213 2214 /// Computes the length of an array in elements, as well as the base 2215 /// element type and a properly-typed first element pointer. 2216 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType, 2217 QualType &baseType, 2218 Address &addr) { 2219 const ArrayType *arrayType = origArrayType; 2220 2221 // If it's a VLA, we have to load the stored size. Note that 2222 // this is the size of the VLA in bytes, not its size in elements. 2223 llvm::Value *numVLAElements = nullptr; 2224 if (isa<VariableArrayType>(arrayType)) { 2225 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts; 2226 2227 // Walk into all VLAs. This doesn't require changes to addr, 2228 // which has type T* where T is the first non-VLA element type. 2229 do { 2230 QualType elementType = arrayType->getElementType(); 2231 arrayType = getContext().getAsArrayType(elementType); 2232 2233 // If we only have VLA components, 'addr' requires no adjustment. 2234 if (!arrayType) { 2235 baseType = elementType; 2236 return numVLAElements; 2237 } 2238 } while (isa<VariableArrayType>(arrayType)); 2239 2240 // We get out here only if we find a constant array type 2241 // inside the VLA. 2242 } 2243 2244 // We have some number of constant-length arrays, so addr should 2245 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks 2246 // down to the first element of addr. 2247 SmallVector<llvm::Value*, 8> gepIndices; 2248 2249 // GEP down to the array type. 2250 llvm::ConstantInt *zero = Builder.getInt32(0); 2251 gepIndices.push_back(zero); 2252 2253 uint64_t countFromCLAs = 1; 2254 QualType eltType; 2255 2256 llvm::ArrayType *llvmArrayType = 2257 dyn_cast<llvm::ArrayType>(addr.getElementType()); 2258 while (llvmArrayType) { 2259 assert(isa<ConstantArrayType>(arrayType)); 2260 assert(cast<ConstantArrayType>(arrayType)->getZExtSize() == 2261 llvmArrayType->getNumElements()); 2262 2263 gepIndices.push_back(zero); 2264 countFromCLAs *= llvmArrayType->getNumElements(); 2265 eltType = arrayType->getElementType(); 2266 2267 llvmArrayType = 2268 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType()); 2269 arrayType = getContext().getAsArrayType(arrayType->getElementType()); 2270 assert((!llvmArrayType || arrayType) && 2271 "LLVM and Clang types are out-of-synch"); 2272 } 2273 2274 if (arrayType) { 2275 // From this point onwards, the Clang array type has been emitted 2276 // as some other type (probably a packed struct). Compute the array 2277 // size, and just emit the 'begin' expression as a bitcast. 2278 while (arrayType) { 2279 countFromCLAs *= cast<ConstantArrayType>(arrayType)->getZExtSize(); 2280 eltType = arrayType->getElementType(); 2281 arrayType = getContext().getAsArrayType(eltType); 2282 } 2283 2284 llvm::Type *baseType = ConvertType(eltType); 2285 addr = addr.withElementType(baseType); 2286 } else { 2287 // Create the actual GEP. 2288 addr = Address(Builder.CreateInBoundsGEP(addr.getElementType(), 2289 addr.emitRawPointer(*this), 2290 gepIndices, "array.begin"), 2291 ConvertTypeForMem(eltType), addr.getAlignment()); 2292 } 2293 2294 baseType = eltType; 2295 2296 llvm::Value *numElements 2297 = llvm::ConstantInt::get(SizeTy, countFromCLAs); 2298 2299 // If we had any VLA dimensions, factor them in. 2300 if (numVLAElements) 2301 numElements = Builder.CreateNUWMul(numVLAElements, numElements); 2302 2303 return numElements; 2304 } 2305 2306 CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) { 2307 const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 2308 assert(vla && "type was not a variable array type!"); 2309 return getVLASize(vla); 2310 } 2311 2312 CodeGenFunction::VlaSizePair 2313 CodeGenFunction::getVLASize(const VariableArrayType *type) { 2314 // The number of elements so far; always size_t. 2315 llvm::Value *numElements = nullptr; 2316 2317 QualType elementType; 2318 do { 2319 elementType = type->getElementType(); 2320 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()]; 2321 assert(vlaSize && "no size for VLA!"); 2322 assert(vlaSize->getType() == SizeTy); 2323 2324 if (!numElements) { 2325 numElements = vlaSize; 2326 } else { 2327 // It's undefined behavior if this wraps around, so mark it that way. 2328 // FIXME: Teach -fsanitize=undefined to trap this. 2329 numElements = Builder.CreateNUWMul(numElements, vlaSize); 2330 } 2331 } while ((type = getContext().getAsVariableArrayType(elementType))); 2332 2333 return { numElements, elementType }; 2334 } 2335 2336 CodeGenFunction::VlaSizePair 2337 CodeGenFunction::getVLAElements1D(QualType type) { 2338 const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 2339 assert(vla && "type was not a variable array type!"); 2340 return getVLAElements1D(vla); 2341 } 2342 2343 CodeGenFunction::VlaSizePair 2344 CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) { 2345 llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()]; 2346 assert(VlaSize && "no size for VLA!"); 2347 assert(VlaSize->getType() == SizeTy); 2348 return { VlaSize, Vla->getElementType() }; 2349 } 2350 2351 void CodeGenFunction::EmitVariablyModifiedType(QualType type) { 2352 assert(type->isVariablyModifiedType() && 2353 "Must pass variably modified type to EmitVLASizes!"); 2354 2355 EnsureInsertPoint(); 2356 2357 // We're going to walk down into the type and look for VLA 2358 // expressions. 2359 do { 2360 assert(type->isVariablyModifiedType()); 2361 2362 const Type *ty = type.getTypePtr(); 2363 switch (ty->getTypeClass()) { 2364 2365 #define TYPE(Class, Base) 2366 #define ABSTRACT_TYPE(Class, Base) 2367 #define NON_CANONICAL_TYPE(Class, Base) 2368 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2369 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 2370 #include "clang/AST/TypeNodes.inc" 2371 llvm_unreachable("unexpected dependent type!"); 2372 2373 // These types are never variably-modified. 2374 case Type::Builtin: 2375 case Type::Complex: 2376 case Type::Vector: 2377 case Type::ExtVector: 2378 case Type::ConstantMatrix: 2379 case Type::Record: 2380 case Type::Enum: 2381 case Type::Using: 2382 case Type::TemplateSpecialization: 2383 case Type::ObjCTypeParam: 2384 case Type::ObjCObject: 2385 case Type::ObjCInterface: 2386 case Type::ObjCObjectPointer: 2387 case Type::BitInt: 2388 llvm_unreachable("type class is never variably-modified!"); 2389 2390 case Type::Elaborated: 2391 type = cast<ElaboratedType>(ty)->getNamedType(); 2392 break; 2393 2394 case Type::Adjusted: 2395 type = cast<AdjustedType>(ty)->getAdjustedType(); 2396 break; 2397 2398 case Type::Decayed: 2399 type = cast<DecayedType>(ty)->getPointeeType(); 2400 break; 2401 2402 case Type::Pointer: 2403 type = cast<PointerType>(ty)->getPointeeType(); 2404 break; 2405 2406 case Type::BlockPointer: 2407 type = cast<BlockPointerType>(ty)->getPointeeType(); 2408 break; 2409 2410 case Type::LValueReference: 2411 case Type::RValueReference: 2412 type = cast<ReferenceType>(ty)->getPointeeType(); 2413 break; 2414 2415 case Type::MemberPointer: 2416 type = cast<MemberPointerType>(ty)->getPointeeType(); 2417 break; 2418 2419 case Type::ArrayParameter: 2420 case Type::ConstantArray: 2421 case Type::IncompleteArray: 2422 // Losing element qualification here is fine. 2423 type = cast<ArrayType>(ty)->getElementType(); 2424 break; 2425 2426 case Type::VariableArray: { 2427 // Losing element qualification here is fine. 2428 const VariableArrayType *vat = cast<VariableArrayType>(ty); 2429 2430 // Unknown size indication requires no size computation. 2431 // Otherwise, evaluate and record it. 2432 if (const Expr *sizeExpr = vat->getSizeExpr()) { 2433 // It's possible that we might have emitted this already, 2434 // e.g. with a typedef and a pointer to it. 2435 llvm::Value *&entry = VLASizeMap[sizeExpr]; 2436 if (!entry) { 2437 llvm::Value *size = EmitScalarExpr(sizeExpr); 2438 2439 // C11 6.7.6.2p5: 2440 // If the size is an expression that is not an integer constant 2441 // expression [...] each time it is evaluated it shall have a value 2442 // greater than zero. 2443 if (SanOpts.has(SanitizerKind::VLABound)) { 2444 SanitizerScope SanScope(this); 2445 llvm::Value *Zero = llvm::Constant::getNullValue(size->getType()); 2446 clang::QualType SEType = sizeExpr->getType(); 2447 llvm::Value *CheckCondition = 2448 SEType->isSignedIntegerType() 2449 ? Builder.CreateICmpSGT(size, Zero) 2450 : Builder.CreateICmpUGT(size, Zero); 2451 llvm::Constant *StaticArgs[] = { 2452 EmitCheckSourceLocation(sizeExpr->getBeginLoc()), 2453 EmitCheckTypeDescriptor(SEType)}; 2454 EmitCheck(std::make_pair(CheckCondition, SanitizerKind::VLABound), 2455 SanitizerHandler::VLABoundNotPositive, StaticArgs, size); 2456 } 2457 2458 // Always zexting here would be wrong if it weren't 2459 // undefined behavior to have a negative bound. 2460 // FIXME: What about when size's type is larger than size_t? 2461 entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false); 2462 } 2463 } 2464 type = vat->getElementType(); 2465 break; 2466 } 2467 2468 case Type::FunctionProto: 2469 case Type::FunctionNoProto: 2470 type = cast<FunctionType>(ty)->getReturnType(); 2471 break; 2472 2473 case Type::Paren: 2474 case Type::TypeOf: 2475 case Type::UnaryTransform: 2476 case Type::Attributed: 2477 case Type::BTFTagAttributed: 2478 case Type::SubstTemplateTypeParm: 2479 case Type::MacroQualified: 2480 case Type::CountAttributed: 2481 // Keep walking after single level desugaring. 2482 type = type.getSingleStepDesugaredType(getContext()); 2483 break; 2484 2485 case Type::Typedef: 2486 case Type::Decltype: 2487 case Type::Auto: 2488 case Type::DeducedTemplateSpecialization: 2489 case Type::PackIndexing: 2490 // Stop walking: nothing to do. 2491 return; 2492 2493 case Type::TypeOfExpr: 2494 // Stop walking: emit typeof expression. 2495 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr()); 2496 return; 2497 2498 case Type::Atomic: 2499 type = cast<AtomicType>(ty)->getValueType(); 2500 break; 2501 2502 case Type::Pipe: 2503 type = cast<PipeType>(ty)->getElementType(); 2504 break; 2505 } 2506 } while (type->isVariablyModifiedType()); 2507 } 2508 2509 Address CodeGenFunction::EmitVAListRef(const Expr* E) { 2510 if (getContext().getBuiltinVaListType()->isArrayType()) 2511 return EmitPointerWithAlignment(E); 2512 return EmitLValue(E).getAddress(); 2513 } 2514 2515 Address CodeGenFunction::EmitMSVAListRef(const Expr *E) { 2516 return EmitLValue(E).getAddress(); 2517 } 2518 2519 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 2520 const APValue &Init) { 2521 assert(Init.hasValue() && "Invalid DeclRefExpr initializer!"); 2522 if (CGDebugInfo *Dbg = getDebugInfo()) 2523 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) 2524 Dbg->EmitGlobalVariable(E->getDecl(), Init); 2525 } 2526 2527 CodeGenFunction::PeepholeProtection 2528 CodeGenFunction::protectFromPeepholes(RValue rvalue) { 2529 // At the moment, the only aggressive peephole we do in IR gen 2530 // is trunc(zext) folding, but if we add more, we can easily 2531 // extend this protection. 2532 2533 if (!rvalue.isScalar()) return PeepholeProtection(); 2534 llvm::Value *value = rvalue.getScalarVal(); 2535 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection(); 2536 2537 // Just make an extra bitcast. 2538 assert(HaveInsertPoint()); 2539 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "", 2540 Builder.GetInsertBlock()); 2541 2542 PeepholeProtection protection; 2543 protection.Inst = inst; 2544 return protection; 2545 } 2546 2547 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) { 2548 if (!protection.Inst) return; 2549 2550 // In theory, we could try to duplicate the peepholes now, but whatever. 2551 protection.Inst->eraseFromParent(); 2552 } 2553 2554 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue, 2555 QualType Ty, SourceLocation Loc, 2556 SourceLocation AssumptionLoc, 2557 llvm::Value *Alignment, 2558 llvm::Value *OffsetValue) { 2559 if (Alignment->getType() != IntPtrTy) 2560 Alignment = 2561 Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align"); 2562 if (OffsetValue && OffsetValue->getType() != IntPtrTy) 2563 OffsetValue = 2564 Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset"); 2565 llvm::Value *TheCheck = nullptr; 2566 if (SanOpts.has(SanitizerKind::Alignment)) { 2567 llvm::Value *PtrIntValue = 2568 Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint"); 2569 2570 if (OffsetValue) { 2571 bool IsOffsetZero = false; 2572 if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue)) 2573 IsOffsetZero = CI->isZero(); 2574 2575 if (!IsOffsetZero) 2576 PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr"); 2577 } 2578 2579 llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0); 2580 llvm::Value *Mask = 2581 Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1)); 2582 llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr"); 2583 TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond"); 2584 } 2585 llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption( 2586 CGM.getDataLayout(), PtrValue, Alignment, OffsetValue); 2587 2588 if (!SanOpts.has(SanitizerKind::Alignment)) 2589 return; 2590 emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment, 2591 OffsetValue, TheCheck, Assumption); 2592 } 2593 2594 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue, 2595 const Expr *E, 2596 SourceLocation AssumptionLoc, 2597 llvm::Value *Alignment, 2598 llvm::Value *OffsetValue) { 2599 QualType Ty = E->getType(); 2600 SourceLocation Loc = E->getExprLoc(); 2601 2602 emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment, 2603 OffsetValue); 2604 } 2605 2606 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn, 2607 llvm::Value *AnnotatedVal, 2608 StringRef AnnotationStr, 2609 SourceLocation Location, 2610 const AnnotateAttr *Attr) { 2611 SmallVector<llvm::Value *, 5> Args = { 2612 AnnotatedVal, 2613 CGM.EmitAnnotationString(AnnotationStr), 2614 CGM.EmitAnnotationUnit(Location), 2615 CGM.EmitAnnotationLineNo(Location), 2616 }; 2617 if (Attr) 2618 Args.push_back(CGM.EmitAnnotationArgs(Attr)); 2619 return Builder.CreateCall(AnnotationFn, Args); 2620 } 2621 2622 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) { 2623 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2624 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2625 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation, 2626 {V->getType(), CGM.ConstGlobalsPtrTy}), 2627 V, I->getAnnotation(), D->getLocation(), I); 2628 } 2629 2630 Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D, 2631 Address Addr) { 2632 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2633 llvm::Value *V = Addr.emitRawPointer(*this); 2634 llvm::Type *VTy = V->getType(); 2635 auto *PTy = dyn_cast<llvm::PointerType>(VTy); 2636 unsigned AS = PTy ? PTy->getAddressSpace() : 0; 2637 llvm::PointerType *IntrinTy = 2638 llvm::PointerType::get(CGM.getLLVMContext(), AS); 2639 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, 2640 {IntrinTy, CGM.ConstGlobalsPtrTy}); 2641 2642 for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 2643 // FIXME Always emit the cast inst so we can differentiate between 2644 // annotation on the first field of a struct and annotation on the struct 2645 // itself. 2646 if (VTy != IntrinTy) 2647 V = Builder.CreateBitCast(V, IntrinTy); 2648 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I); 2649 V = Builder.CreateBitCast(V, VTy); 2650 } 2651 2652 return Address(V, Addr.getElementType(), Addr.getAlignment()); 2653 } 2654 2655 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { } 2656 2657 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF) 2658 : CGF(CGF) { 2659 assert(!CGF->IsSanitizerScope); 2660 CGF->IsSanitizerScope = true; 2661 } 2662 2663 CodeGenFunction::SanitizerScope::~SanitizerScope() { 2664 CGF->IsSanitizerScope = false; 2665 } 2666 2667 void CodeGenFunction::InsertHelper(llvm::Instruction *I, 2668 const llvm::Twine &Name, 2669 llvm::BasicBlock::iterator InsertPt) const { 2670 LoopStack.InsertHelper(I); 2671 if (IsSanitizerScope) 2672 I->setNoSanitizeMetadata(); 2673 } 2674 2675 void CGBuilderInserter::InsertHelper( 2676 llvm::Instruction *I, const llvm::Twine &Name, 2677 llvm::BasicBlock::iterator InsertPt) const { 2678 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt); 2679 if (CGF) 2680 CGF->InsertHelper(I, Name, InsertPt); 2681 } 2682 2683 // Emits an error if we don't have a valid set of target features for the 2684 // called function. 2685 void CodeGenFunction::checkTargetFeatures(const CallExpr *E, 2686 const FunctionDecl *TargetDecl) { 2687 // SemaChecking cannot handle below x86 builtins because they have different 2688 // parameter ranges with different TargetAttribute of caller. 2689 if (CGM.getContext().getTargetInfo().getTriple().isX86()) { 2690 unsigned BuiltinID = TargetDecl->getBuiltinID(); 2691 if (BuiltinID == X86::BI__builtin_ia32_cmpps || 2692 BuiltinID == X86::BI__builtin_ia32_cmpss || 2693 BuiltinID == X86::BI__builtin_ia32_cmppd || 2694 BuiltinID == X86::BI__builtin_ia32_cmpsd) { 2695 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl); 2696 llvm::StringMap<bool> TargetFetureMap; 2697 CGM.getContext().getFunctionFeatureMap(TargetFetureMap, FD); 2698 llvm::APSInt Result = 2699 *(E->getArg(2)->getIntegerConstantExpr(CGM.getContext())); 2700 if (Result.getSExtValue() > 7 && !TargetFetureMap.lookup("avx")) 2701 CGM.getDiags().Report(E->getBeginLoc(), diag::err_builtin_needs_feature) 2702 << TargetDecl->getDeclName() << "avx"; 2703 } 2704 } 2705 return checkTargetFeatures(E->getBeginLoc(), TargetDecl); 2706 } 2707 2708 // Emits an error if we don't have a valid set of target features for the 2709 // called function. 2710 void CodeGenFunction::checkTargetFeatures(SourceLocation Loc, 2711 const FunctionDecl *TargetDecl) { 2712 // Early exit if this is an indirect call. 2713 if (!TargetDecl) 2714 return; 2715 2716 // Get the current enclosing function if it exists. If it doesn't 2717 // we can't check the target features anyhow. 2718 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl); 2719 if (!FD) 2720 return; 2721 2722 // Grab the required features for the call. For a builtin this is listed in 2723 // the td file with the default cpu, for an always_inline function this is any 2724 // listed cpu and any listed features. 2725 unsigned BuiltinID = TargetDecl->getBuiltinID(); 2726 std::string MissingFeature; 2727 llvm::StringMap<bool> CallerFeatureMap; 2728 CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD); 2729 // When compiling in HipStdPar mode we have to be conservative in rejecting 2730 // target specific features in the FE, and defer the possible error to the 2731 // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is 2732 // referenced by an accelerator executable function, we emit an error. 2733 bool IsHipStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice; 2734 if (BuiltinID) { 2735 StringRef FeatureList(CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID)); 2736 if (!Builtin::evaluateRequiredTargetFeatures( 2737 FeatureList, CallerFeatureMap) && !IsHipStdPar) { 2738 CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature) 2739 << TargetDecl->getDeclName() 2740 << FeatureList; 2741 } 2742 } else if (!TargetDecl->isMultiVersion() && 2743 TargetDecl->hasAttr<TargetAttr>()) { 2744 // Get the required features for the callee. 2745 2746 const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>(); 2747 ParsedTargetAttr ParsedAttr = 2748 CGM.getContext().filterFunctionTargetAttrs(TD); 2749 2750 SmallVector<StringRef, 1> ReqFeatures; 2751 llvm::StringMap<bool> CalleeFeatureMap; 2752 CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl); 2753 2754 for (const auto &F : ParsedAttr.Features) { 2755 if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1))) 2756 ReqFeatures.push_back(StringRef(F).substr(1)); 2757 } 2758 2759 for (const auto &F : CalleeFeatureMap) { 2760 // Only positive features are "required". 2761 if (F.getValue()) 2762 ReqFeatures.push_back(F.getKey()); 2763 } 2764 if (!llvm::all_of(ReqFeatures, [&](StringRef Feature) { 2765 if (!CallerFeatureMap.lookup(Feature)) { 2766 MissingFeature = Feature.str(); 2767 return false; 2768 } 2769 return true; 2770 }) && !IsHipStdPar) 2771 CGM.getDiags().Report(Loc, diag::err_function_needs_feature) 2772 << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature; 2773 } else if (!FD->isMultiVersion() && FD->hasAttr<TargetAttr>()) { 2774 llvm::StringMap<bool> CalleeFeatureMap; 2775 CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl); 2776 2777 for (const auto &F : CalleeFeatureMap) { 2778 if (F.getValue() && (!CallerFeatureMap.lookup(F.getKey()) || 2779 !CallerFeatureMap.find(F.getKey())->getValue()) && 2780 !IsHipStdPar) 2781 CGM.getDiags().Report(Loc, diag::err_function_needs_feature) 2782 << FD->getDeclName() << TargetDecl->getDeclName() << F.getKey(); 2783 } 2784 } 2785 } 2786 2787 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) { 2788 if (!CGM.getCodeGenOpts().SanitizeStats) 2789 return; 2790 2791 llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint()); 2792 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation()); 2793 CGM.getSanStats().create(IRB, SSK); 2794 } 2795 2796 void CodeGenFunction::EmitKCFIOperandBundle( 2797 const CGCallee &Callee, SmallVectorImpl<llvm::OperandBundleDef> &Bundles) { 2798 const FunctionProtoType *FP = 2799 Callee.getAbstractInfo().getCalleeFunctionProtoType(); 2800 if (FP) 2801 Bundles.emplace_back("kcfi", CGM.CreateKCFITypeId(FP->desugar())); 2802 } 2803 2804 llvm::Value *CodeGenFunction::FormAArch64ResolverCondition( 2805 const MultiVersionResolverOption &RO) { 2806 llvm::SmallVector<StringRef, 8> CondFeatures; 2807 for (const StringRef &Feature : RO.Conditions.Features) 2808 CondFeatures.push_back(Feature); 2809 if (!CondFeatures.empty()) { 2810 return EmitAArch64CpuSupports(CondFeatures); 2811 } 2812 return nullptr; 2813 } 2814 2815 llvm::Value *CodeGenFunction::FormX86ResolverCondition( 2816 const MultiVersionResolverOption &RO) { 2817 llvm::Value *Condition = nullptr; 2818 2819 if (!RO.Conditions.Architecture.empty()) { 2820 StringRef Arch = RO.Conditions.Architecture; 2821 // If arch= specifies an x86-64 micro-architecture level, test the feature 2822 // with __builtin_cpu_supports, otherwise use __builtin_cpu_is. 2823 if (Arch.starts_with("x86-64")) 2824 Condition = EmitX86CpuSupports({Arch}); 2825 else 2826 Condition = EmitX86CpuIs(Arch); 2827 } 2828 2829 if (!RO.Conditions.Features.empty()) { 2830 llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features); 2831 Condition = 2832 Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond; 2833 } 2834 return Condition; 2835 } 2836 2837 static void CreateMultiVersionResolverReturn(CodeGenModule &CGM, 2838 llvm::Function *Resolver, 2839 CGBuilderTy &Builder, 2840 llvm::Function *FuncToReturn, 2841 bool SupportsIFunc) { 2842 if (SupportsIFunc) { 2843 Builder.CreateRet(FuncToReturn); 2844 return; 2845 } 2846 2847 llvm::SmallVector<llvm::Value *, 10> Args( 2848 llvm::make_pointer_range(Resolver->args())); 2849 2850 llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args); 2851 Result->setTailCallKind(llvm::CallInst::TCK_MustTail); 2852 2853 if (Resolver->getReturnType()->isVoidTy()) 2854 Builder.CreateRetVoid(); 2855 else 2856 Builder.CreateRet(Result); 2857 } 2858 2859 void CodeGenFunction::EmitMultiVersionResolver( 2860 llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) { 2861 2862 llvm::Triple::ArchType ArchType = 2863 getContext().getTargetInfo().getTriple().getArch(); 2864 2865 switch (ArchType) { 2866 case llvm::Triple::x86: 2867 case llvm::Triple::x86_64: 2868 EmitX86MultiVersionResolver(Resolver, Options); 2869 return; 2870 case llvm::Triple::aarch64: 2871 EmitAArch64MultiVersionResolver(Resolver, Options); 2872 return; 2873 2874 default: 2875 assert(false && "Only implemented for x86 and AArch64 targets"); 2876 } 2877 } 2878 2879 void CodeGenFunction::EmitAArch64MultiVersionResolver( 2880 llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) { 2881 assert(!Options.empty() && "No multiversion resolver options found"); 2882 assert(Options.back().Conditions.Features.size() == 0 && 2883 "Default case must be last"); 2884 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc(); 2885 assert(SupportsIFunc && 2886 "Multiversion resolver requires target IFUNC support"); 2887 bool AArch64CpuInitialized = false; 2888 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver); 2889 2890 for (const MultiVersionResolverOption &RO : Options) { 2891 Builder.SetInsertPoint(CurBlock); 2892 llvm::Value *Condition = FormAArch64ResolverCondition(RO); 2893 2894 // The 'default' or 'all features enabled' case. 2895 if (!Condition) { 2896 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function, 2897 SupportsIFunc); 2898 return; 2899 } 2900 2901 if (!AArch64CpuInitialized) { 2902 Builder.SetInsertPoint(CurBlock, CurBlock->begin()); 2903 EmitAArch64CpuInit(); 2904 AArch64CpuInitialized = true; 2905 Builder.SetInsertPoint(CurBlock); 2906 } 2907 2908 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver); 2909 CGBuilderTy RetBuilder(*this, RetBlock); 2910 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function, 2911 SupportsIFunc); 2912 CurBlock = createBasicBlock("resolver_else", Resolver); 2913 Builder.CreateCondBr(Condition, RetBlock, CurBlock); 2914 } 2915 2916 // If no default, emit an unreachable. 2917 Builder.SetInsertPoint(CurBlock); 2918 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap); 2919 TrapCall->setDoesNotReturn(); 2920 TrapCall->setDoesNotThrow(); 2921 Builder.CreateUnreachable(); 2922 Builder.ClearInsertionPoint(); 2923 } 2924 2925 void CodeGenFunction::EmitX86MultiVersionResolver( 2926 llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) { 2927 2928 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc(); 2929 2930 // Main function's basic block. 2931 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver); 2932 Builder.SetInsertPoint(CurBlock); 2933 EmitX86CpuInit(); 2934 2935 for (const MultiVersionResolverOption &RO : Options) { 2936 Builder.SetInsertPoint(CurBlock); 2937 llvm::Value *Condition = FormX86ResolverCondition(RO); 2938 2939 // The 'default' or 'generic' case. 2940 if (!Condition) { 2941 assert(&RO == Options.end() - 1 && 2942 "Default or Generic case must be last"); 2943 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function, 2944 SupportsIFunc); 2945 return; 2946 } 2947 2948 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver); 2949 CGBuilderTy RetBuilder(*this, RetBlock); 2950 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function, 2951 SupportsIFunc); 2952 CurBlock = createBasicBlock("resolver_else", Resolver); 2953 Builder.CreateCondBr(Condition, RetBlock, CurBlock); 2954 } 2955 2956 // If no generic/default, emit an unreachable. 2957 Builder.SetInsertPoint(CurBlock); 2958 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap); 2959 TrapCall->setDoesNotReturn(); 2960 TrapCall->setDoesNotThrow(); 2961 Builder.CreateUnreachable(); 2962 Builder.ClearInsertionPoint(); 2963 } 2964 2965 // Loc - where the diagnostic will point, where in the source code this 2966 // alignment has failed. 2967 // SecondaryLoc - if present (will be present if sufficiently different from 2968 // Loc), the diagnostic will additionally point a "Note:" to this location. 2969 // It should be the location where the __attribute__((assume_aligned)) 2970 // was written e.g. 2971 void CodeGenFunction::emitAlignmentAssumptionCheck( 2972 llvm::Value *Ptr, QualType Ty, SourceLocation Loc, 2973 SourceLocation SecondaryLoc, llvm::Value *Alignment, 2974 llvm::Value *OffsetValue, llvm::Value *TheCheck, 2975 llvm::Instruction *Assumption) { 2976 assert(isa_and_nonnull<llvm::CallInst>(Assumption) && 2977 cast<llvm::CallInst>(Assumption)->getCalledOperand() == 2978 llvm::Intrinsic::getDeclaration( 2979 Builder.GetInsertBlock()->getParent()->getParent(), 2980 llvm::Intrinsic::assume) && 2981 "Assumption should be a call to llvm.assume()."); 2982 assert(&(Builder.GetInsertBlock()->back()) == Assumption && 2983 "Assumption should be the last instruction of the basic block, " 2984 "since the basic block is still being generated."); 2985 2986 if (!SanOpts.has(SanitizerKind::Alignment)) 2987 return; 2988 2989 // Don't check pointers to volatile data. The behavior here is implementation- 2990 // defined. 2991 if (Ty->getPointeeType().isVolatileQualified()) 2992 return; 2993 2994 // We need to temorairly remove the assumption so we can insert the 2995 // sanitizer check before it, else the check will be dropped by optimizations. 2996 Assumption->removeFromParent(); 2997 2998 { 2999 SanitizerScope SanScope(this); 3000 3001 if (!OffsetValue) 3002 OffsetValue = Builder.getInt1(false); // no offset. 3003 3004 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc), 3005 EmitCheckSourceLocation(SecondaryLoc), 3006 EmitCheckTypeDescriptor(Ty)}; 3007 llvm::Value *DynamicData[] = {EmitCheckValue(Ptr), 3008 EmitCheckValue(Alignment), 3009 EmitCheckValue(OffsetValue)}; 3010 EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)}, 3011 SanitizerHandler::AlignmentAssumption, StaticData, DynamicData); 3012 } 3013 3014 // We are now in the (new, empty) "cont" basic block. 3015 // Reintroduce the assumption. 3016 Builder.Insert(Assumption); 3017 // FIXME: Assumption still has it's original basic block as it's Parent. 3018 } 3019 3020 llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) { 3021 if (CGDebugInfo *DI = getDebugInfo()) 3022 return DI->SourceLocToDebugLoc(Location); 3023 3024 return llvm::DebugLoc(); 3025 } 3026 3027 llvm::Value * 3028 CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond, 3029 Stmt::Likelihood LH) { 3030 switch (LH) { 3031 case Stmt::LH_None: 3032 return Cond; 3033 case Stmt::LH_Likely: 3034 case Stmt::LH_Unlikely: 3035 // Don't generate llvm.expect on -O0 as the backend won't use it for 3036 // anything. 3037 if (CGM.getCodeGenOpts().OptimizationLevel == 0) 3038 return Cond; 3039 llvm::Type *CondTy = Cond->getType(); 3040 assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean"); 3041 llvm::Function *FnExpect = 3042 CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy); 3043 llvm::Value *ExpectedValueOfCond = 3044 llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely); 3045 return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond}, 3046 Cond->getName() + ".expval"); 3047 } 3048 llvm_unreachable("Unknown Likelihood"); 3049 } 3050 3051 llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec, 3052 unsigned NumElementsDst, 3053 const llvm::Twine &Name) { 3054 auto *SrcTy = cast<llvm::FixedVectorType>(SrcVec->getType()); 3055 unsigned NumElementsSrc = SrcTy->getNumElements(); 3056 if (NumElementsSrc == NumElementsDst) 3057 return SrcVec; 3058 3059 std::vector<int> ShuffleMask(NumElementsDst, -1); 3060 for (unsigned MaskIdx = 0; 3061 MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); ++MaskIdx) 3062 ShuffleMask[MaskIdx] = MaskIdx; 3063 3064 return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name); 3065 } 3066 3067 void CodeGenFunction::EmitPointerAuthOperandBundle( 3068 const CGPointerAuthInfo &PointerAuth, 3069 SmallVectorImpl<llvm::OperandBundleDef> &Bundles) { 3070 if (!PointerAuth.isSigned()) 3071 return; 3072 3073 auto *Key = Builder.getInt32(PointerAuth.getKey()); 3074 3075 llvm::Value *Discriminator = PointerAuth.getDiscriminator(); 3076 if (!Discriminator) 3077 Discriminator = Builder.getSize(0); 3078 3079 llvm::Value *Args[] = {Key, Discriminator}; 3080 Bundles.emplace_back("ptrauth", Args); 3081 } 3082 3083 static llvm::Value *EmitPointerAuthCommon(CodeGenFunction &CGF, 3084 const CGPointerAuthInfo &PointerAuth, 3085 llvm::Value *Pointer, 3086 unsigned IntrinsicID) { 3087 if (!PointerAuth) 3088 return Pointer; 3089 3090 auto Key = CGF.Builder.getInt32(PointerAuth.getKey()); 3091 3092 llvm::Value *Discriminator = PointerAuth.getDiscriminator(); 3093 if (!Discriminator) { 3094 Discriminator = CGF.Builder.getSize(0); 3095 } 3096 3097 // Convert the pointer to intptr_t before signing it. 3098 auto OrigType = Pointer->getType(); 3099 Pointer = CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy); 3100 3101 // call i64 @llvm.ptrauth.sign.i64(i64 %pointer, i32 %key, i64 %discriminator) 3102 auto Intrinsic = CGF.CGM.getIntrinsic(IntrinsicID); 3103 Pointer = CGF.EmitRuntimeCall(Intrinsic, {Pointer, Key, Discriminator}); 3104 3105 // Convert back to the original type. 3106 Pointer = CGF.Builder.CreateIntToPtr(Pointer, OrigType); 3107 return Pointer; 3108 } 3109 3110 llvm::Value * 3111 CodeGenFunction::EmitPointerAuthSign(const CGPointerAuthInfo &PointerAuth, 3112 llvm::Value *Pointer) { 3113 if (!PointerAuth.shouldSign()) 3114 return Pointer; 3115 return EmitPointerAuthCommon(*this, PointerAuth, Pointer, 3116 llvm::Intrinsic::ptrauth_sign); 3117 } 3118 3119 static llvm::Value *EmitStrip(CodeGenFunction &CGF, 3120 const CGPointerAuthInfo &PointerAuth, 3121 llvm::Value *Pointer) { 3122 auto StripIntrinsic = CGF.CGM.getIntrinsic(llvm::Intrinsic::ptrauth_strip); 3123 3124 auto Key = CGF.Builder.getInt32(PointerAuth.getKey()); 3125 // Convert the pointer to intptr_t before signing it. 3126 auto OrigType = Pointer->getType(); 3127 Pointer = CGF.EmitRuntimeCall( 3128 StripIntrinsic, {CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy), Key}); 3129 return CGF.Builder.CreateIntToPtr(Pointer, OrigType); 3130 } 3131 3132 llvm::Value * 3133 CodeGenFunction::EmitPointerAuthAuth(const CGPointerAuthInfo &PointerAuth, 3134 llvm::Value *Pointer) { 3135 if (PointerAuth.shouldStrip()) { 3136 return EmitStrip(*this, PointerAuth, Pointer); 3137 } 3138 if (!PointerAuth.shouldAuth()) { 3139 return Pointer; 3140 } 3141 3142 return EmitPointerAuthCommon(*this, PointerAuth, Pointer, 3143 llvm::Intrinsic::ptrauth_auth); 3144 } 3145