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