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