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