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