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