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