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