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