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