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