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