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