1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 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-module state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenModule.h" 15 #include "CGCUDARuntime.h" 16 #include "CGCXXABI.h" 17 #include "CGCall.h" 18 #include "CGDebugInfo.h" 19 #include "CGObjCRuntime.h" 20 #include "CGOpenCLRuntime.h" 21 #include "CGOpenMPRuntime.h" 22 #include "CodeGenFunction.h" 23 #include "CodeGenPGO.h" 24 #include "CoverageMappingGen.h" 25 #include "CodeGenTBAA.h" 26 #include "TargetInfo.h" 27 #include "clang/AST/ASTContext.h" 28 #include "clang/AST/CharUnits.h" 29 #include "clang/AST/DeclCXX.h" 30 #include "clang/AST/DeclObjC.h" 31 #include "clang/AST/DeclTemplate.h" 32 #include "clang/AST/Mangle.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/RecursiveASTVisitor.h" 35 #include "clang/Basic/Builtins.h" 36 #include "clang/Basic/CharInfo.h" 37 #include "clang/Basic/Diagnostic.h" 38 #include "clang/Basic/Module.h" 39 #include "clang/Basic/SourceManager.h" 40 #include "clang/Basic/TargetInfo.h" 41 #include "clang/Basic/Version.h" 42 #include "clang/Frontend/CodeGenOptions.h" 43 #include "clang/Sema/SemaDiagnostic.h" 44 #include "llvm/ADT/APSInt.h" 45 #include "llvm/ADT/Triple.h" 46 #include "llvm/IR/CallSite.h" 47 #include "llvm/IR/CallingConv.h" 48 #include "llvm/IR/DataLayout.h" 49 #include "llvm/IR/Intrinsics.h" 50 #include "llvm/IR/LLVMContext.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/ProfileData/InstrProfReader.h" 53 #include "llvm/Support/ConvertUTF.h" 54 #include "llvm/Support/ErrorHandling.h" 55 56 using namespace clang; 57 using namespace CodeGen; 58 59 static const char AnnotationSection[] = "llvm.metadata"; 60 61 static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 62 switch (CGM.getTarget().getCXXABI().getKind()) { 63 case TargetCXXABI::GenericAArch64: 64 case TargetCXXABI::GenericARM: 65 case TargetCXXABI::iOS: 66 case TargetCXXABI::iOS64: 67 case TargetCXXABI::GenericItanium: 68 return CreateItaniumCXXABI(CGM); 69 case TargetCXXABI::Microsoft: 70 return CreateMicrosoftCXXABI(CGM); 71 } 72 73 llvm_unreachable("invalid C++ ABI kind"); 74 } 75 76 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 77 llvm::Module &M, const llvm::DataLayout &TD, 78 DiagnosticsEngine &diags, 79 CoverageSourceInfo *CoverageInfo) 80 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M), 81 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()), 82 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(nullptr), 83 TheTargetCodeGenInfo(nullptr), Types(*this), VTables(*this), 84 ObjCRuntime(nullptr), OpenCLRuntime(nullptr), OpenMPRuntime(nullptr), 85 CUDARuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr), 86 NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr), 87 CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr), 88 NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr), 89 NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr), 90 BlockObjectDispose(nullptr), BlockDescriptorType(nullptr), 91 GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr), 92 LifetimeEndFn(nullptr), SanitizerBL(llvm::SpecialCaseList::createOrDie( 93 CGO.SanitizerBlacklistFile)), 94 SanitizerMD(new SanitizerMetadata(*this)) { 95 96 // Initialize the type cache. 97 llvm::LLVMContext &LLVMContext = M.getContext(); 98 VoidTy = llvm::Type::getVoidTy(LLVMContext); 99 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 100 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 101 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 102 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 103 FloatTy = llvm::Type::getFloatTy(LLVMContext); 104 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 105 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 106 PointerAlignInBytes = 107 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 108 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 109 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 110 Int8PtrTy = Int8Ty->getPointerTo(0); 111 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 112 113 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 114 115 if (LangOpts.ObjC1) 116 createObjCRuntime(); 117 if (LangOpts.OpenCL) 118 createOpenCLRuntime(); 119 if (LangOpts.OpenMP) 120 createOpenMPRuntime(); 121 if (LangOpts.CUDA) 122 createCUDARuntime(); 123 124 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 125 if (LangOpts.Sanitize.Thread || 126 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 127 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 128 getCXXABI().getMangleContext()); 129 130 // If debug info or coverage generation is enabled, create the CGDebugInfo 131 // object. 132 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo || 133 CodeGenOpts.EmitGcovArcs || 134 CodeGenOpts.EmitGcovNotes) 135 DebugInfo = new CGDebugInfo(*this); 136 137 Block.GlobalUniqueCount = 0; 138 139 if (C.getLangOpts().ObjCAutoRefCount) 140 ARCData = new ARCEntrypoints(); 141 RRData = new RREntrypoints(); 142 143 if (!CodeGenOpts.InstrProfileInput.empty()) { 144 if (std::error_code EC = llvm::IndexedInstrProfReader::create( 145 CodeGenOpts.InstrProfileInput, PGOReader)) { 146 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 147 "Could not read profile: %0"); 148 getDiags().Report(DiagID) << EC.message(); 149 } 150 } 151 152 // If coverage mapping generation is enabled, create the 153 // CoverageMappingModuleGen object. 154 if (CodeGenOpts.CoverageMapping) 155 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 156 } 157 158 CodeGenModule::~CodeGenModule() { 159 delete ObjCRuntime; 160 delete OpenCLRuntime; 161 delete OpenMPRuntime; 162 delete CUDARuntime; 163 delete TheTargetCodeGenInfo; 164 delete TBAA; 165 delete DebugInfo; 166 delete ARCData; 167 delete RRData; 168 } 169 170 void CodeGenModule::createObjCRuntime() { 171 // This is just isGNUFamily(), but we want to force implementors of 172 // new ABIs to decide how best to do this. 173 switch (LangOpts.ObjCRuntime.getKind()) { 174 case ObjCRuntime::GNUstep: 175 case ObjCRuntime::GCC: 176 case ObjCRuntime::ObjFW: 177 ObjCRuntime = CreateGNUObjCRuntime(*this); 178 return; 179 180 case ObjCRuntime::FragileMacOSX: 181 case ObjCRuntime::MacOSX: 182 case ObjCRuntime::iOS: 183 ObjCRuntime = CreateMacObjCRuntime(*this); 184 return; 185 } 186 llvm_unreachable("bad runtime kind"); 187 } 188 189 void CodeGenModule::createOpenCLRuntime() { 190 OpenCLRuntime = new CGOpenCLRuntime(*this); 191 } 192 193 void CodeGenModule::createOpenMPRuntime() { 194 OpenMPRuntime = new CGOpenMPRuntime(*this); 195 } 196 197 void CodeGenModule::createCUDARuntime() { 198 CUDARuntime = CreateNVCUDARuntime(*this); 199 } 200 201 void CodeGenModule::applyReplacements() { 202 for (ReplacementsTy::iterator I = Replacements.begin(), 203 E = Replacements.end(); 204 I != E; ++I) { 205 StringRef MangledName = I->first(); 206 llvm::Constant *Replacement = I->second; 207 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 208 if (!Entry) 209 continue; 210 auto *OldF = cast<llvm::Function>(Entry); 211 auto *NewF = dyn_cast<llvm::Function>(Replacement); 212 if (!NewF) { 213 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 214 NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 215 } else { 216 auto *CE = cast<llvm::ConstantExpr>(Replacement); 217 assert(CE->getOpcode() == llvm::Instruction::BitCast || 218 CE->getOpcode() == llvm::Instruction::GetElementPtr); 219 NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 220 } 221 } 222 223 // Replace old with new, but keep the old order. 224 OldF->replaceAllUsesWith(Replacement); 225 if (NewF) { 226 NewF->removeFromParent(); 227 OldF->getParent()->getFunctionList().insertAfter(OldF, NewF); 228 } 229 OldF->eraseFromParent(); 230 } 231 } 232 233 // This is only used in aliases that we created and we know they have a 234 // linear structure. 235 static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) { 236 llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited; 237 const llvm::Constant *C = &GA; 238 for (;;) { 239 C = C->stripPointerCasts(); 240 if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 241 return GO; 242 // stripPointerCasts will not walk over weak aliases. 243 auto *GA2 = dyn_cast<llvm::GlobalAlias>(C); 244 if (!GA2) 245 return nullptr; 246 if (!Visited.insert(GA2)) 247 return nullptr; 248 C = GA2->getAliasee(); 249 } 250 } 251 252 void CodeGenModule::checkAliases() { 253 // Check if the constructed aliases are well formed. It is really unfortunate 254 // that we have to do this in CodeGen, but we only construct mangled names 255 // and aliases during codegen. 256 bool Error = false; 257 DiagnosticsEngine &Diags = getDiags(); 258 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(), 259 E = Aliases.end(); I != E; ++I) { 260 const GlobalDecl &GD = *I; 261 const auto *D = cast<ValueDecl>(GD.getDecl()); 262 const AliasAttr *AA = D->getAttr<AliasAttr>(); 263 StringRef MangledName = getMangledName(GD); 264 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 265 auto *Alias = cast<llvm::GlobalAlias>(Entry); 266 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 267 if (!GV) { 268 Error = true; 269 Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 270 } else if (GV->isDeclaration()) { 271 Error = true; 272 Diags.Report(AA->getLocation(), diag::err_alias_to_undefined); 273 } 274 275 llvm::Constant *Aliasee = Alias->getAliasee(); 276 llvm::GlobalValue *AliaseeGV; 277 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 278 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 279 else 280 AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 281 282 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 283 StringRef AliasSection = SA->getName(); 284 if (AliasSection != AliaseeGV->getSection()) 285 Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 286 << AliasSection; 287 } 288 289 // We have to handle alias to weak aliases in here. LLVM itself disallows 290 // this since the object semantics would not match the IL one. For 291 // compatibility with gcc we implement it by just pointing the alias 292 // to its aliasee's aliasee. We also warn, since the user is probably 293 // expecting the link to be weak. 294 if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 295 if (GA->mayBeOverridden()) { 296 Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias) 297 << GV->getName() << GA->getName(); 298 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 299 GA->getAliasee(), Alias->getType()); 300 Alias->setAliasee(Aliasee); 301 } 302 } 303 } 304 if (!Error) 305 return; 306 307 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(), 308 E = Aliases.end(); I != E; ++I) { 309 const GlobalDecl &GD = *I; 310 StringRef MangledName = getMangledName(GD); 311 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 312 auto *Alias = cast<llvm::GlobalAlias>(Entry); 313 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 314 Alias->eraseFromParent(); 315 } 316 } 317 318 void CodeGenModule::clear() { 319 DeferredDeclsToEmit.clear(); 320 } 321 322 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 323 StringRef MainFile) { 324 if (!hasDiagnostics()) 325 return; 326 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 327 if (MainFile.empty()) 328 MainFile = "<stdin>"; 329 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 330 } else 331 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing 332 << Mismatched; 333 } 334 335 void CodeGenModule::Release() { 336 EmitDeferred(); 337 applyReplacements(); 338 checkAliases(); 339 EmitCXXGlobalInitFunc(); 340 EmitCXXGlobalDtorFunc(); 341 EmitCXXThreadLocalInitFunc(); 342 if (ObjCRuntime) 343 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 344 AddGlobalCtor(ObjCInitFunction); 345 if (getCodeGenOpts().ProfileInstrGenerate) 346 if (llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this)) 347 AddGlobalCtor(PGOInit, 0); 348 if (PGOReader && PGOStats.hasDiagnostics()) 349 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 350 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 351 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 352 EmitGlobalAnnotations(); 353 EmitStaticExternCAliases(); 354 EmitDeferredUnusedCoverageMappings(); 355 if (CoverageMapping) 356 CoverageMapping->emit(); 357 emitLLVMUsed(); 358 359 if (CodeGenOpts.Autolink && 360 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 361 EmitModuleLinkOptions(); 362 } 363 if (CodeGenOpts.DwarfVersion) 364 // We actually want the latest version when there are conflicts. 365 // We can change from Warning to Latest if such mode is supported. 366 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 367 CodeGenOpts.DwarfVersion); 368 if (DebugInfo) 369 // We support a single version in the linked module. The LLVM 370 // parser will drop debug info with a different version number 371 // (and warn about it, too). 372 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 373 llvm::DEBUG_METADATA_VERSION); 374 375 // We need to record the widths of enums and wchar_t, so that we can generate 376 // the correct build attributes in the ARM backend. 377 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 378 if ( Arch == llvm::Triple::arm 379 || Arch == llvm::Triple::armeb 380 || Arch == llvm::Triple::thumb 381 || Arch == llvm::Triple::thumbeb) { 382 // Width of wchar_t in bytes 383 uint64_t WCharWidth = 384 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 385 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 386 387 // The minimum width of an enum in bytes 388 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 389 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 390 } 391 392 SimplifyPersonality(); 393 394 if (getCodeGenOpts().EmitDeclMetadata) 395 EmitDeclMetadata(); 396 397 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 398 EmitCoverageFile(); 399 400 if (DebugInfo) 401 DebugInfo->finalize(); 402 403 EmitVersionIdentMetadata(); 404 405 EmitTargetMetadata(); 406 } 407 408 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 409 // Make sure that this type is translated. 410 Types.UpdateCompletedType(TD); 411 } 412 413 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 414 if (!TBAA) 415 return nullptr; 416 return TBAA->getTBAAInfo(QTy); 417 } 418 419 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 420 if (!TBAA) 421 return nullptr; 422 return TBAA->getTBAAInfoForVTablePtr(); 423 } 424 425 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 426 if (!TBAA) 427 return nullptr; 428 return TBAA->getTBAAStructInfo(QTy); 429 } 430 431 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) { 432 if (!TBAA) 433 return nullptr; 434 return TBAA->getTBAAStructTypeInfo(QTy); 435 } 436 437 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 438 llvm::MDNode *AccessN, 439 uint64_t O) { 440 if (!TBAA) 441 return nullptr; 442 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 443 } 444 445 /// Decorate the instruction with a TBAA tag. For both scalar TBAA 446 /// and struct-path aware TBAA, the tag has the same format: 447 /// base type, access type and offset. 448 /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 449 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 450 llvm::MDNode *TBAAInfo, 451 bool ConvertTypeToTag) { 452 if (ConvertTypeToTag && TBAA) 453 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 454 TBAA->getTBAAScalarTagInfo(TBAAInfo)); 455 else 456 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 457 } 458 459 void CodeGenModule::Error(SourceLocation loc, StringRef message) { 460 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 461 getDiags().Report(Context.getFullLoc(loc), diagID) << message; 462 } 463 464 /// ErrorUnsupported - Print out an error that codegen doesn't support the 465 /// specified stmt yet. 466 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 467 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 468 "cannot compile this %0 yet"); 469 std::string Msg = Type; 470 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 471 << Msg << S->getSourceRange(); 472 } 473 474 /// ErrorUnsupported - Print out an error that codegen doesn't support the 475 /// specified decl yet. 476 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 477 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 478 "cannot compile this %0 yet"); 479 std::string Msg = Type; 480 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 481 } 482 483 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 484 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 485 } 486 487 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 488 const NamedDecl *D) const { 489 // Internal definitions always have default visibility. 490 if (GV->hasLocalLinkage()) { 491 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 492 return; 493 } 494 495 // Set visibility for definitions. 496 LinkageInfo LV = D->getLinkageAndVisibility(); 497 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 498 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 499 } 500 501 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 502 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 503 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 504 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 505 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 506 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 507 } 508 509 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 510 CodeGenOptions::TLSModel M) { 511 switch (M) { 512 case CodeGenOptions::GeneralDynamicTLSModel: 513 return llvm::GlobalVariable::GeneralDynamicTLSModel; 514 case CodeGenOptions::LocalDynamicTLSModel: 515 return llvm::GlobalVariable::LocalDynamicTLSModel; 516 case CodeGenOptions::InitialExecTLSModel: 517 return llvm::GlobalVariable::InitialExecTLSModel; 518 case CodeGenOptions::LocalExecTLSModel: 519 return llvm::GlobalVariable::LocalExecTLSModel; 520 } 521 llvm_unreachable("Invalid TLS model!"); 522 } 523 524 void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV, 525 const VarDecl &D) const { 526 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 527 528 llvm::GlobalVariable::ThreadLocalMode TLM; 529 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 530 531 // Override the TLS model if it is explicitly specified. 532 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 533 TLM = GetLLVMTLSModel(Attr->getModel()); 534 } 535 536 GV->setThreadLocalMode(TLM); 537 } 538 539 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 540 StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()]; 541 if (!FoundStr.empty()) 542 return FoundStr; 543 544 const auto *ND = cast<NamedDecl>(GD.getDecl()); 545 SmallString<256> Buffer; 546 StringRef Str; 547 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 548 llvm::raw_svector_ostream Out(Buffer); 549 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 550 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 551 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 552 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 553 else 554 getCXXABI().getMangleContext().mangleName(ND, Out); 555 Str = Out.str(); 556 } else { 557 IdentifierInfo *II = ND->getIdentifier(); 558 assert(II && "Attempt to mangle unnamed decl."); 559 Str = II->getName(); 560 } 561 562 // Keep the first result in the case of a mangling collision. 563 auto Result = Manglings.insert(std::make_pair(Str, GD)); 564 return FoundStr = Result.first->first(); 565 } 566 567 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 568 const BlockDecl *BD) { 569 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 570 const Decl *D = GD.getDecl(); 571 572 SmallString<256> Buffer; 573 llvm::raw_svector_ostream Out(Buffer); 574 if (!D) 575 MangleCtx.mangleGlobalBlock(BD, 576 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 577 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 578 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 579 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 580 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 581 else 582 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 583 584 auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 585 return Result.first->first(); 586 } 587 588 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 589 return getModule().getNamedValue(Name); 590 } 591 592 /// AddGlobalCtor - Add a function to the list that will be called before 593 /// main() runs. 594 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 595 llvm::Constant *AssociatedData) { 596 // FIXME: Type coercion of void()* types. 597 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 598 } 599 600 /// AddGlobalDtor - Add a function to the list that will be called 601 /// when the module is unloaded. 602 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 603 // FIXME: Type coercion of void()* types. 604 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 605 } 606 607 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 608 // Ctor function type is void()*. 609 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 610 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 611 612 // Get the type of a ctor entry, { i32, void ()*, i8* }. 613 llvm::StructType *CtorStructTy = llvm::StructType::get( 614 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, NULL); 615 616 // Construct the constructor and destructor arrays. 617 SmallVector<llvm::Constant*, 8> Ctors; 618 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 619 llvm::Constant *S[] = { 620 llvm::ConstantInt::get(Int32Ty, I->Priority, false), 621 llvm::ConstantExpr::getBitCast(I->Initializer, CtorPFTy), 622 (I->AssociatedData 623 ? llvm::ConstantExpr::getBitCast(I->AssociatedData, VoidPtrTy) 624 : llvm::Constant::getNullValue(VoidPtrTy)) 625 }; 626 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 627 } 628 629 if (!Ctors.empty()) { 630 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 631 new llvm::GlobalVariable(TheModule, AT, false, 632 llvm::GlobalValue::AppendingLinkage, 633 llvm::ConstantArray::get(AT, Ctors), 634 GlobalName); 635 } 636 } 637 638 llvm::GlobalValue::LinkageTypes 639 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 640 const auto *D = cast<FunctionDecl>(GD.getDecl()); 641 642 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 643 644 if (isa<CXXDestructorDecl>(D) && 645 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 646 GD.getDtorType())) { 647 // Destructor variants in the Microsoft C++ ABI are always internal or 648 // linkonce_odr thunks emitted on an as-needed basis. 649 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 650 : llvm::GlobalValue::LinkOnceODRLinkage; 651 } 652 653 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 654 } 655 656 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 657 llvm::Function *F) { 658 setNonAliasAttributes(D, F); 659 } 660 661 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 662 const CGFunctionInfo &Info, 663 llvm::Function *F) { 664 unsigned CallingConv; 665 AttributeListType AttributeList; 666 ConstructAttributeList(Info, D, AttributeList, CallingConv, false); 667 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList)); 668 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 669 } 670 671 /// Determines whether the language options require us to model 672 /// unwind exceptions. We treat -fexceptions as mandating this 673 /// except under the fragile ObjC ABI with only ObjC exceptions 674 /// enabled. This means, for example, that C with -fexceptions 675 /// enables this. 676 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 677 // If exceptions are completely disabled, obviously this is false. 678 if (!LangOpts.Exceptions) return false; 679 680 // If C++ exceptions are enabled, this is true. 681 if (LangOpts.CXXExceptions) return true; 682 683 // If ObjC exceptions are enabled, this depends on the ABI. 684 if (LangOpts.ObjCExceptions) { 685 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 686 } 687 688 return true; 689 } 690 691 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 692 llvm::Function *F) { 693 llvm::AttrBuilder B; 694 695 if (CodeGenOpts.UnwindTables) 696 B.addAttribute(llvm::Attribute::UWTable); 697 698 if (!hasUnwindExceptions(LangOpts)) 699 B.addAttribute(llvm::Attribute::NoUnwind); 700 701 if (D->hasAttr<NakedAttr>()) { 702 // Naked implies noinline: we should not be inlining such functions. 703 B.addAttribute(llvm::Attribute::Naked); 704 B.addAttribute(llvm::Attribute::NoInline); 705 } else if (D->hasAttr<OptimizeNoneAttr>()) { 706 // OptimizeNone implies noinline; we should not be inlining such functions. 707 B.addAttribute(llvm::Attribute::OptimizeNone); 708 B.addAttribute(llvm::Attribute::NoInline); 709 } else if (D->hasAttr<NoDuplicateAttr>()) { 710 B.addAttribute(llvm::Attribute::NoDuplicate); 711 } else if (D->hasAttr<NoInlineAttr>()) { 712 B.addAttribute(llvm::Attribute::NoInline); 713 } else if (D->hasAttr<AlwaysInlineAttr>() && 714 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex, 715 llvm::Attribute::NoInline)) { 716 // (noinline wins over always_inline, and we can't specify both in IR) 717 B.addAttribute(llvm::Attribute::AlwaysInline); 718 } 719 720 if (D->hasAttr<ColdAttr>()) { 721 B.addAttribute(llvm::Attribute::OptimizeForSize); 722 B.addAttribute(llvm::Attribute::Cold); 723 } 724 725 if (D->hasAttr<MinSizeAttr>()) 726 B.addAttribute(llvm::Attribute::MinSize); 727 728 if (D->hasAttr<OptimizeNoneAttr>()) { 729 // OptimizeNone wins over OptimizeForSize and MinSize. 730 B.removeAttribute(llvm::Attribute::OptimizeForSize); 731 B.removeAttribute(llvm::Attribute::MinSize); 732 } 733 734 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 735 B.addAttribute(llvm::Attribute::StackProtect); 736 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 737 B.addAttribute(llvm::Attribute::StackProtectStrong); 738 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 739 B.addAttribute(llvm::Attribute::StackProtectReq); 740 741 // Add sanitizer attributes if function is not blacklisted. 742 if (!SanitizerBL.isIn(*F)) { 743 // When AddressSanitizer is enabled, set SanitizeAddress attribute 744 // unless __attribute__((no_sanitize_address)) is used. 745 if (LangOpts.Sanitize.Address && !D->hasAttr<NoSanitizeAddressAttr>()) 746 B.addAttribute(llvm::Attribute::SanitizeAddress); 747 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread)) 748 if (LangOpts.Sanitize.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) 749 B.addAttribute(llvm::Attribute::SanitizeThread); 750 // Same for MemorySanitizer and __attribute__((no_sanitize_memory)) 751 if (LangOpts.Sanitize.Memory && !D->hasAttr<NoSanitizeMemoryAttr>()) 752 B.addAttribute(llvm::Attribute::SanitizeMemory); 753 } 754 755 F->addAttributes(llvm::AttributeSet::FunctionIndex, 756 llvm::AttributeSet::get( 757 F->getContext(), llvm::AttributeSet::FunctionIndex, B)); 758 759 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 760 F->setUnnamedAddr(true); 761 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) 762 if (MD->isVirtual()) 763 F->setUnnamedAddr(true); 764 765 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 766 if (alignment) 767 F->setAlignment(alignment); 768 769 // C++ ABI requires 2-byte alignment for member functions. 770 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 771 F->setAlignment(2); 772 } 773 774 void CodeGenModule::SetCommonAttributes(const Decl *D, 775 llvm::GlobalValue *GV) { 776 if (const auto *ND = dyn_cast<NamedDecl>(D)) 777 setGlobalVisibility(GV, ND); 778 else 779 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 780 781 if (D->hasAttr<UsedAttr>()) 782 addUsedGlobal(GV); 783 } 784 785 void CodeGenModule::setNonAliasAttributes(const Decl *D, 786 llvm::GlobalObject *GO) { 787 SetCommonAttributes(D, GO); 788 789 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 790 GO->setSection(SA->getName()); 791 792 getTargetCodeGenInfo().SetTargetAttributes(D, GO, *this); 793 } 794 795 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 796 llvm::Function *F, 797 const CGFunctionInfo &FI) { 798 SetLLVMFunctionAttributes(D, FI, F); 799 SetLLVMFunctionAttributesForDefinition(D, F); 800 801 F->setLinkage(llvm::Function::InternalLinkage); 802 803 setNonAliasAttributes(D, F); 804 } 805 806 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 807 const NamedDecl *ND) { 808 // Set linkage and visibility in case we never see a definition. 809 LinkageInfo LV = ND->getLinkageAndVisibility(); 810 if (LV.getLinkage() != ExternalLinkage) { 811 // Don't set internal linkage on declarations. 812 } else { 813 if (ND->hasAttr<DLLImportAttr>()) { 814 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 815 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 816 } else if (ND->hasAttr<DLLExportAttr>()) { 817 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 818 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 819 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 820 // "extern_weak" is overloaded in LLVM; we probably should have 821 // separate linkage types for this. 822 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 823 } 824 825 // Set visibility on a declaration only if it's explicit. 826 if (LV.isVisibilityExplicit()) 827 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 828 } 829 } 830 831 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 832 llvm::Function *F, 833 bool IsIncompleteFunction) { 834 if (unsigned IID = F->getIntrinsicID()) { 835 // If this is an intrinsic function, set the function's attributes 836 // to the intrinsic's attributes. 837 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), 838 (llvm::Intrinsic::ID)IID)); 839 return; 840 } 841 842 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 843 844 if (!IsIncompleteFunction) 845 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 846 847 // Add the Returned attribute for "this", except for iOS 5 and earlier 848 // where substantial code, including the libstdc++ dylib, was compiled with 849 // GCC and does not actually return "this". 850 if (getCXXABI().HasThisReturn(GD) && 851 !(getTarget().getTriple().isiOS() && 852 getTarget().getTriple().isOSVersionLT(6))) { 853 assert(!F->arg_empty() && 854 F->arg_begin()->getType() 855 ->canLosslesslyBitCastTo(F->getReturnType()) && 856 "unexpected this return"); 857 F->addAttribute(1, llvm::Attribute::Returned); 858 } 859 860 // Only a few attributes are set on declarations; these may later be 861 // overridden by a definition. 862 863 setLinkageAndVisibilityForGV(F, FD); 864 865 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 866 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 867 // Don't dllexport/import destructor thunks. 868 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 869 } 870 } 871 872 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 873 F->setSection(SA->getName()); 874 875 // A replaceable global allocation function does not act like a builtin by 876 // default, only if it is invoked by a new-expression or delete-expression. 877 if (FD->isReplaceableGlobalAllocationFunction()) 878 F->addAttribute(llvm::AttributeSet::FunctionIndex, 879 llvm::Attribute::NoBuiltin); 880 } 881 882 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 883 assert(!GV->isDeclaration() && 884 "Only globals with definition can force usage."); 885 LLVMUsed.push_back(GV); 886 } 887 888 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 889 assert(!GV->isDeclaration() && 890 "Only globals with definition can force usage."); 891 LLVMCompilerUsed.push_back(GV); 892 } 893 894 static void emitUsed(CodeGenModule &CGM, StringRef Name, 895 std::vector<llvm::WeakVH> &List) { 896 // Don't create llvm.used if there is no need. 897 if (List.empty()) 898 return; 899 900 // Convert List to what ConstantArray needs. 901 SmallVector<llvm::Constant*, 8> UsedArray; 902 UsedArray.resize(List.size()); 903 for (unsigned i = 0, e = List.size(); i != e; ++i) { 904 UsedArray[i] = 905 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]), 906 CGM.Int8PtrTy); 907 } 908 909 if (UsedArray.empty()) 910 return; 911 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 912 913 auto *GV = new llvm::GlobalVariable( 914 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 915 llvm::ConstantArray::get(ATy, UsedArray), Name); 916 917 GV->setSection("llvm.metadata"); 918 } 919 920 void CodeGenModule::emitLLVMUsed() { 921 emitUsed(*this, "llvm.used", LLVMUsed); 922 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 923 } 924 925 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 926 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 927 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 928 } 929 930 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 931 llvm::SmallString<32> Opt; 932 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 933 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 934 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 935 } 936 937 void CodeGenModule::AddDependentLib(StringRef Lib) { 938 llvm::SmallString<24> Opt; 939 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 940 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 941 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 942 } 943 944 /// \brief Add link options implied by the given module, including modules 945 /// it depends on, using a postorder walk. 946 static void addLinkOptionsPostorder(CodeGenModule &CGM, 947 Module *Mod, 948 SmallVectorImpl<llvm::Value *> &Metadata, 949 llvm::SmallPtrSet<Module *, 16> &Visited) { 950 // Import this module's parent. 951 if (Mod->Parent && Visited.insert(Mod->Parent)) { 952 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 953 } 954 955 // Import this module's dependencies. 956 for (unsigned I = Mod->Imports.size(); I > 0; --I) { 957 if (Visited.insert(Mod->Imports[I-1])) 958 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 959 } 960 961 // Add linker options to link against the libraries/frameworks 962 // described by this module. 963 llvm::LLVMContext &Context = CGM.getLLVMContext(); 964 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 965 // Link against a framework. Frameworks are currently Darwin only, so we 966 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 967 if (Mod->LinkLibraries[I-1].IsFramework) { 968 llvm::Value *Args[2] = { 969 llvm::MDString::get(Context, "-framework"), 970 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library) 971 }; 972 973 Metadata.push_back(llvm::MDNode::get(Context, Args)); 974 continue; 975 } 976 977 // Link against a library. 978 llvm::SmallString<24> Opt; 979 CGM.getTargetCodeGenInfo().getDependentLibraryOption( 980 Mod->LinkLibraries[I-1].Library, Opt); 981 llvm::Value *OptString = llvm::MDString::get(Context, Opt); 982 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 983 } 984 } 985 986 void CodeGenModule::EmitModuleLinkOptions() { 987 // Collect the set of all of the modules we want to visit to emit link 988 // options, which is essentially the imported modules and all of their 989 // non-explicit child modules. 990 llvm::SetVector<clang::Module *> LinkModules; 991 llvm::SmallPtrSet<clang::Module *, 16> Visited; 992 SmallVector<clang::Module *, 16> Stack; 993 994 // Seed the stack with imported modules. 995 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(), 996 MEnd = ImportedModules.end(); 997 M != MEnd; ++M) { 998 if (Visited.insert(*M)) 999 Stack.push_back(*M); 1000 } 1001 1002 // Find all of the modules to import, making a little effort to prune 1003 // non-leaf modules. 1004 while (!Stack.empty()) { 1005 clang::Module *Mod = Stack.pop_back_val(); 1006 1007 bool AnyChildren = false; 1008 1009 // Visit the submodules of this module. 1010 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1011 SubEnd = Mod->submodule_end(); 1012 Sub != SubEnd; ++Sub) { 1013 // Skip explicit children; they need to be explicitly imported to be 1014 // linked against. 1015 if ((*Sub)->IsExplicit) 1016 continue; 1017 1018 if (Visited.insert(*Sub)) { 1019 Stack.push_back(*Sub); 1020 AnyChildren = true; 1021 } 1022 } 1023 1024 // We didn't find any children, so add this module to the list of 1025 // modules to link against. 1026 if (!AnyChildren) { 1027 LinkModules.insert(Mod); 1028 } 1029 } 1030 1031 // Add link options for all of the imported modules in reverse topological 1032 // order. We don't do anything to try to order import link flags with respect 1033 // to linker options inserted by things like #pragma comment(). 1034 SmallVector<llvm::Value *, 16> MetadataArgs; 1035 Visited.clear(); 1036 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(), 1037 MEnd = LinkModules.end(); 1038 M != MEnd; ++M) { 1039 if (Visited.insert(*M)) 1040 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited); 1041 } 1042 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1043 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1044 1045 // Add the linker options metadata flag. 1046 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 1047 llvm::MDNode::get(getLLVMContext(), 1048 LinkerOptionsMetadata)); 1049 } 1050 1051 void CodeGenModule::EmitDeferred() { 1052 // Emit code for any potentially referenced deferred decls. Since a 1053 // previously unused static decl may become used during the generation of code 1054 // for a static function, iterate until no changes are made. 1055 1056 while (true) { 1057 if (!DeferredVTables.empty()) { 1058 EmitDeferredVTables(); 1059 1060 // Emitting a v-table doesn't directly cause more v-tables to 1061 // become deferred, although it can cause functions to be 1062 // emitted that then need those v-tables. 1063 assert(DeferredVTables.empty()); 1064 } 1065 1066 // Stop if we're out of both deferred v-tables and deferred declarations. 1067 if (DeferredDeclsToEmit.empty()) break; 1068 1069 DeferredGlobal &G = DeferredDeclsToEmit.back(); 1070 GlobalDecl D = G.GD; 1071 llvm::GlobalValue *GV = G.GV; 1072 DeferredDeclsToEmit.pop_back(); 1073 1074 assert(GV == GetGlobalValue(getMangledName(D))); 1075 // Check to see if we've already emitted this. This is necessary 1076 // for a couple of reasons: first, decls can end up in the 1077 // deferred-decls queue multiple times, and second, decls can end 1078 // up with definitions in unusual ways (e.g. by an extern inline 1079 // function acquiring a strong function redefinition). Just 1080 // ignore these cases. 1081 if(!GV->isDeclaration()) 1082 continue; 1083 1084 // Otherwise, emit the definition and move on to the next one. 1085 EmitGlobalDefinition(D, GV); 1086 } 1087 } 1088 1089 void CodeGenModule::EmitGlobalAnnotations() { 1090 if (Annotations.empty()) 1091 return; 1092 1093 // Create a new global variable for the ConstantStruct in the Module. 1094 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 1095 Annotations[0]->getType(), Annotations.size()), Annotations); 1096 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 1097 llvm::GlobalValue::AppendingLinkage, 1098 Array, "llvm.global.annotations"); 1099 gv->setSection(AnnotationSection); 1100 } 1101 1102 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1103 llvm::Constant *&AStr = AnnotationStrings[Str]; 1104 if (AStr) 1105 return AStr; 1106 1107 // Not found yet, create a new global. 1108 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 1109 auto *gv = 1110 new llvm::GlobalVariable(getModule(), s->getType(), true, 1111 llvm::GlobalValue::PrivateLinkage, s, ".str"); 1112 gv->setSection(AnnotationSection); 1113 gv->setUnnamedAddr(true); 1114 AStr = gv; 1115 return gv; 1116 } 1117 1118 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 1119 SourceManager &SM = getContext().getSourceManager(); 1120 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 1121 if (PLoc.isValid()) 1122 return EmitAnnotationString(PLoc.getFilename()); 1123 return EmitAnnotationString(SM.getBufferName(Loc)); 1124 } 1125 1126 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 1127 SourceManager &SM = getContext().getSourceManager(); 1128 PresumedLoc PLoc = SM.getPresumedLoc(L); 1129 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 1130 SM.getExpansionLineNumber(L); 1131 return llvm::ConstantInt::get(Int32Ty, LineNo); 1132 } 1133 1134 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1135 const AnnotateAttr *AA, 1136 SourceLocation L) { 1137 // Get the globals for file name, annotation, and the line number. 1138 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 1139 *UnitGV = EmitAnnotationUnit(L), 1140 *LineNoCst = EmitAnnotationLineNo(L); 1141 1142 // Create the ConstantStruct for the global annotation. 1143 llvm::Constant *Fields[4] = { 1144 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 1145 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 1146 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 1147 LineNoCst 1148 }; 1149 return llvm::ConstantStruct::getAnon(Fields); 1150 } 1151 1152 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 1153 llvm::GlobalValue *GV) { 1154 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1155 // Get the struct elements for these annotations. 1156 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1157 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 1158 } 1159 1160 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 1161 // Never defer when EmitAllDecls is specified. 1162 if (LangOpts.EmitAllDecls) 1163 return false; 1164 1165 return !getContext().DeclMustBeEmitted(Global); 1166 } 1167 1168 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor( 1169 const CXXUuidofExpr* E) { 1170 // Sema has verified that IIDSource has a __declspec(uuid()), and that its 1171 // well-formed. 1172 StringRef Uuid = E->getUuidAsStringRef(Context); 1173 std::string Name = "_GUID_" + Uuid.lower(); 1174 std::replace(Name.begin(), Name.end(), '-', '_'); 1175 1176 // Look for an existing global. 1177 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 1178 return GV; 1179 1180 llvm::Constant *Init = EmitUuidofInitializer(Uuid); 1181 assert(Init && "failed to initialize as constant"); 1182 1183 auto *GV = new llvm::GlobalVariable( 1184 getModule(), Init->getType(), 1185 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 1186 return GV; 1187 } 1188 1189 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1190 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1191 assert(AA && "No alias?"); 1192 1193 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1194 1195 // See if there is already something with the target's name in the module. 1196 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 1197 if (Entry) { 1198 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 1199 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 1200 } 1201 1202 llvm::Constant *Aliasee; 1203 if (isa<llvm::FunctionType>(DeclTy)) 1204 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 1205 GlobalDecl(cast<FunctionDecl>(VD)), 1206 /*ForVTable=*/false); 1207 else 1208 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1209 llvm::PointerType::getUnqual(DeclTy), 1210 nullptr); 1211 1212 auto *F = cast<llvm::GlobalValue>(Aliasee); 1213 F->setLinkage(llvm::Function::ExternalWeakLinkage); 1214 WeakRefReferences.insert(F); 1215 1216 return Aliasee; 1217 } 1218 1219 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 1220 const auto *Global = cast<ValueDecl>(GD.getDecl()); 1221 1222 // Weak references don't produce any output by themselves. 1223 if (Global->hasAttr<WeakRefAttr>()) 1224 return; 1225 1226 // If this is an alias definition (which otherwise looks like a declaration) 1227 // emit it now. 1228 if (Global->hasAttr<AliasAttr>()) 1229 return EmitAliasDefinition(GD); 1230 1231 // If this is CUDA, be selective about which declarations we emit. 1232 if (LangOpts.CUDA) { 1233 if (CodeGenOpts.CUDAIsDevice) { 1234 if (!Global->hasAttr<CUDADeviceAttr>() && 1235 !Global->hasAttr<CUDAGlobalAttr>() && 1236 !Global->hasAttr<CUDAConstantAttr>() && 1237 !Global->hasAttr<CUDASharedAttr>()) 1238 return; 1239 } else { 1240 if (!Global->hasAttr<CUDAHostAttr>() && ( 1241 Global->hasAttr<CUDADeviceAttr>() || 1242 Global->hasAttr<CUDAConstantAttr>() || 1243 Global->hasAttr<CUDASharedAttr>())) 1244 return; 1245 } 1246 } 1247 1248 // Ignore declarations, they will be emitted on their first use. 1249 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1250 // Forward declarations are emitted lazily on first use. 1251 if (!FD->doesThisDeclarationHaveABody()) { 1252 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1253 return; 1254 1255 StringRef MangledName = getMangledName(GD); 1256 1257 // Compute the function info and LLVM type. 1258 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 1259 llvm::Type *Ty = getTypes().GetFunctionType(FI); 1260 1261 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 1262 /*DontDefer=*/false); 1263 return; 1264 } 1265 } else { 1266 const auto *VD = cast<VarDecl>(Global); 1267 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1268 1269 if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 1270 !Context.isMSStaticDataMemberInlineDefinition(VD)) 1271 return; 1272 } 1273 1274 // Defer code generation when possible if this is a static definition, inline 1275 // function etc. These we only want to emit if they are used. 1276 if (!MayDeferGeneration(Global)) { 1277 // Emit the definition if it can't be deferred. 1278 EmitGlobalDefinition(GD); 1279 return; 1280 } 1281 1282 // If we're deferring emission of a C++ variable with an 1283 // initializer, remember the order in which it appeared in the file. 1284 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1285 cast<VarDecl>(Global)->hasInit()) { 1286 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 1287 CXXGlobalInits.push_back(nullptr); 1288 } 1289 1290 // If the value has already been used, add it directly to the 1291 // DeferredDeclsToEmit list. 1292 StringRef MangledName = getMangledName(GD); 1293 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) 1294 addDeferredDeclToEmit(GV, GD); 1295 else { 1296 // Otherwise, remember that we saw a deferred decl with this name. The 1297 // first use of the mangled name will cause it to move into 1298 // DeferredDeclsToEmit. 1299 DeferredDecls[MangledName] = GD; 1300 } 1301 } 1302 1303 namespace { 1304 struct FunctionIsDirectlyRecursive : 1305 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1306 const StringRef Name; 1307 const Builtin::Context &BI; 1308 bool Result; 1309 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1310 Name(N), BI(C), Result(false) { 1311 } 1312 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1313 1314 bool TraverseCallExpr(CallExpr *E) { 1315 const FunctionDecl *FD = E->getDirectCallee(); 1316 if (!FD) 1317 return true; 1318 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1319 if (Attr && Name == Attr->getLabel()) { 1320 Result = true; 1321 return false; 1322 } 1323 unsigned BuiltinID = FD->getBuiltinID(); 1324 if (!BuiltinID) 1325 return true; 1326 StringRef BuiltinName = BI.GetName(BuiltinID); 1327 if (BuiltinName.startswith("__builtin_") && 1328 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1329 Result = true; 1330 return false; 1331 } 1332 return true; 1333 } 1334 }; 1335 } 1336 1337 // isTriviallyRecursive - Check if this function calls another 1338 // decl that, because of the asm attribute or the other decl being a builtin, 1339 // ends up pointing to itself. 1340 bool 1341 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1342 StringRef Name; 1343 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1344 // asm labels are a special kind of mangling we have to support. 1345 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1346 if (!Attr) 1347 return false; 1348 Name = Attr->getLabel(); 1349 } else { 1350 Name = FD->getName(); 1351 } 1352 1353 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1354 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1355 return Walker.Result; 1356 } 1357 1358 bool 1359 CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1360 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1361 return true; 1362 const auto *F = cast<FunctionDecl>(GD.getDecl()); 1363 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1364 return false; 1365 // PR9614. Avoid cases where the source code is lying to us. An available 1366 // externally function should have an equivalent function somewhere else, 1367 // but a function that calls itself is clearly not equivalent to the real 1368 // implementation. 1369 // This happens in glibc's btowc and in some configure checks. 1370 return !isTriviallyRecursive(F); 1371 } 1372 1373 /// If the type for the method's class was generated by 1374 /// CGDebugInfo::createContextChain(), the cache contains only a 1375 /// limited DIType without any declarations. Since EmitFunctionStart() 1376 /// needs to find the canonical declaration for each method, we need 1377 /// to construct the complete type prior to emitting the method. 1378 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1379 if (!D->isInstance()) 1380 return; 1381 1382 if (CGDebugInfo *DI = getModuleDebugInfo()) 1383 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 1384 const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext())); 1385 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1386 } 1387 } 1388 1389 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 1390 const auto *D = cast<ValueDecl>(GD.getDecl()); 1391 1392 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1393 Context.getSourceManager(), 1394 "Generating code for declaration"); 1395 1396 if (isa<FunctionDecl>(D)) { 1397 // At -O0, don't generate IR for functions with available_externally 1398 // linkage. 1399 if (!shouldEmitFunction(GD)) 1400 return; 1401 1402 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 1403 CompleteDIClassType(Method); 1404 // Make sure to emit the definition(s) before we emit the thunks. 1405 // This is necessary for the generation of certain thunks. 1406 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 1407 emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 1408 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 1409 emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 1410 else 1411 EmitGlobalFunctionDefinition(GD, GV); 1412 1413 if (Method->isVirtual()) 1414 getVTables().EmitThunks(GD); 1415 1416 return; 1417 } 1418 1419 return EmitGlobalFunctionDefinition(GD, GV); 1420 } 1421 1422 if (const auto *VD = dyn_cast<VarDecl>(D)) 1423 return EmitGlobalVarDefinition(VD); 1424 1425 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1426 } 1427 1428 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1429 /// module, create and return an llvm Function with the specified type. If there 1430 /// is something in the module with the specified name, return it potentially 1431 /// bitcasted to the right type. 1432 /// 1433 /// If D is non-null, it specifies a decl that correspond to this. This is used 1434 /// to set the attributes on the function when it is first created. 1435 llvm::Constant * 1436 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 1437 llvm::Type *Ty, 1438 GlobalDecl GD, bool ForVTable, 1439 bool DontDefer, 1440 llvm::AttributeSet ExtraAttrs) { 1441 const Decl *D = GD.getDecl(); 1442 1443 // Lookup the entry, lazily creating it if necessary. 1444 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1445 if (Entry) { 1446 if (WeakRefReferences.erase(Entry)) { 1447 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1448 if (FD && !FD->hasAttr<WeakAttr>()) 1449 Entry->setLinkage(llvm::Function::ExternalLinkage); 1450 } 1451 1452 // Handle dropped DLL attributes. 1453 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 1454 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 1455 1456 if (Entry->getType()->getElementType() == Ty) 1457 return Entry; 1458 1459 // Make sure the result is of the correct type. 1460 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1461 } 1462 1463 // This function doesn't have a complete type (for example, the return 1464 // type is an incomplete struct). Use a fake type instead, and make 1465 // sure not to try to set attributes. 1466 bool IsIncompleteFunction = false; 1467 1468 llvm::FunctionType *FTy; 1469 if (isa<llvm::FunctionType>(Ty)) { 1470 FTy = cast<llvm::FunctionType>(Ty); 1471 } else { 1472 FTy = llvm::FunctionType::get(VoidTy, false); 1473 IsIncompleteFunction = true; 1474 } 1475 1476 llvm::Function *F = llvm::Function::Create(FTy, 1477 llvm::Function::ExternalLinkage, 1478 MangledName, &getModule()); 1479 assert(F->getName() == MangledName && "name was uniqued!"); 1480 if (D) 1481 SetFunctionAttributes(GD, F, IsIncompleteFunction); 1482 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1483 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1484 F->addAttributes(llvm::AttributeSet::FunctionIndex, 1485 llvm::AttributeSet::get(VMContext, 1486 llvm::AttributeSet::FunctionIndex, 1487 B)); 1488 } 1489 1490 if (!DontDefer) { 1491 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 1492 // each other bottoming out with the base dtor. Therefore we emit non-base 1493 // dtors on usage, even if there is no dtor definition in the TU. 1494 if (D && isa<CXXDestructorDecl>(D) && 1495 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 1496 GD.getDtorType())) 1497 addDeferredDeclToEmit(F, GD); 1498 1499 // This is the first use or definition of a mangled name. If there is a 1500 // deferred decl with this name, remember that we need to emit it at the end 1501 // of the file. 1502 auto DDI = DeferredDecls.find(MangledName); 1503 if (DDI != DeferredDecls.end()) { 1504 // Move the potentially referenced deferred decl to the 1505 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 1506 // don't need it anymore). 1507 addDeferredDeclToEmit(F, DDI->second); 1508 DeferredDecls.erase(DDI); 1509 1510 // Otherwise, if this is a sized deallocation function, emit a weak 1511 // definition 1512 // for it at the end of the translation unit. 1513 } else if (D && cast<FunctionDecl>(D) 1514 ->getCorrespondingUnsizedGlobalDeallocationFunction()) { 1515 addDeferredDeclToEmit(F, GD); 1516 1517 // Otherwise, there are cases we have to worry about where we're 1518 // using a declaration for which we must emit a definition but where 1519 // we might not find a top-level definition: 1520 // - member functions defined inline in their classes 1521 // - friend functions defined inline in some class 1522 // - special member functions with implicit definitions 1523 // If we ever change our AST traversal to walk into class methods, 1524 // this will be unnecessary. 1525 // 1526 // We also don't emit a definition for a function if it's going to be an 1527 // entry in a vtable, unless it's already marked as used. 1528 } else if (getLangOpts().CPlusPlus && D) { 1529 // Look for a declaration that's lexically in a record. 1530 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 1531 FD = FD->getPreviousDecl()) { 1532 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 1533 if (FD->doesThisDeclarationHaveABody()) { 1534 addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 1535 break; 1536 } 1537 } 1538 } 1539 } 1540 } 1541 1542 // Make sure the result is of the requested type. 1543 if (!IsIncompleteFunction) { 1544 assert(F->getType()->getElementType() == Ty); 1545 return F; 1546 } 1547 1548 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1549 return llvm::ConstantExpr::getBitCast(F, PTy); 1550 } 1551 1552 /// GetAddrOfFunction - Return the address of the given function. If Ty is 1553 /// non-null, then this function will use the specified type if it has to 1554 /// create it (this occurs when we see a definition of the function). 1555 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 1556 llvm::Type *Ty, 1557 bool ForVTable, 1558 bool DontDefer) { 1559 // If there was no specific requested type, just convert it now. 1560 if (!Ty) 1561 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 1562 1563 StringRef MangledName = getMangledName(GD); 1564 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer); 1565 } 1566 1567 /// CreateRuntimeFunction - Create a new runtime function with the specified 1568 /// type and name. 1569 llvm::Constant * 1570 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 1571 StringRef Name, 1572 llvm::AttributeSet ExtraAttrs) { 1573 llvm::Constant *C = 1574 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 1575 /*DontDefer=*/false, ExtraAttrs); 1576 if (auto *F = dyn_cast<llvm::Function>(C)) 1577 if (F->empty()) 1578 F->setCallingConv(getRuntimeCC()); 1579 return C; 1580 } 1581 1582 /// isTypeConstant - Determine whether an object of this type can be emitted 1583 /// as a constant. 1584 /// 1585 /// If ExcludeCtor is true, the duration when the object's constructor runs 1586 /// will not be considered. The caller will need to verify that the object is 1587 /// not written to during its construction. 1588 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1589 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1590 return false; 1591 1592 if (Context.getLangOpts().CPlusPlus) { 1593 if (const CXXRecordDecl *Record 1594 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1595 return ExcludeCtor && !Record->hasMutableFields() && 1596 Record->hasTrivialDestructor(); 1597 } 1598 1599 return true; 1600 } 1601 1602 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1603 /// create and return an llvm GlobalVariable with the specified type. If there 1604 /// is something in the module with the specified name, return it potentially 1605 /// bitcasted to the right type. 1606 /// 1607 /// If D is non-null, it specifies a decl that correspond to this. This is used 1608 /// to set the attributes on the global when it is first created. 1609 llvm::Constant * 1610 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 1611 llvm::PointerType *Ty, 1612 const VarDecl *D) { 1613 // Lookup the entry, lazily creating it if necessary. 1614 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1615 if (Entry) { 1616 if (WeakRefReferences.erase(Entry)) { 1617 if (D && !D->hasAttr<WeakAttr>()) 1618 Entry->setLinkage(llvm::Function::ExternalLinkage); 1619 } 1620 1621 // Handle dropped DLL attributes. 1622 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 1623 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 1624 1625 if (Entry->getType() == Ty) 1626 return Entry; 1627 1628 // Make sure the result is of the correct type. 1629 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 1630 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 1631 1632 return llvm::ConstantExpr::getBitCast(Entry, Ty); 1633 } 1634 1635 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 1636 auto *GV = new llvm::GlobalVariable( 1637 getModule(), Ty->getElementType(), false, 1638 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 1639 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 1640 1641 // This is the first use or definition of a mangled name. If there is a 1642 // deferred decl with this name, remember that we need to emit it at the end 1643 // of the file. 1644 auto DDI = DeferredDecls.find(MangledName); 1645 if (DDI != DeferredDecls.end()) { 1646 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1647 // list, and remove it from DeferredDecls (since we don't need it anymore). 1648 addDeferredDeclToEmit(GV, DDI->second); 1649 DeferredDecls.erase(DDI); 1650 } 1651 1652 // Handle things which are present even on external declarations. 1653 if (D) { 1654 // FIXME: This code is overly simple and should be merged with other global 1655 // handling. 1656 GV->setConstant(isTypeConstant(D->getType(), false)); 1657 1658 setLinkageAndVisibilityForGV(GV, D); 1659 1660 if (D->getTLSKind()) { 1661 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 1662 CXXThreadLocals.push_back(std::make_pair(D, GV)); 1663 setTLSMode(GV, *D); 1664 } 1665 1666 // If required by the ABI, treat declarations of static data members with 1667 // inline initializers as definitions. 1668 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 1669 EmitGlobalVarDefinition(D); 1670 } 1671 1672 // Handle XCore specific ABI requirements. 1673 if (getTarget().getTriple().getArch() == llvm::Triple::xcore && 1674 D->getLanguageLinkage() == CLanguageLinkage && 1675 D->getType().isConstant(Context) && 1676 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 1677 GV->setSection(".cp.rodata"); 1678 } 1679 1680 if (AddrSpace != Ty->getAddressSpace()) 1681 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 1682 1683 return GV; 1684 } 1685 1686 1687 llvm::GlobalVariable * 1688 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 1689 llvm::Type *Ty, 1690 llvm::GlobalValue::LinkageTypes Linkage) { 1691 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 1692 llvm::GlobalVariable *OldGV = nullptr; 1693 1694 if (GV) { 1695 // Check if the variable has the right type. 1696 if (GV->getType()->getElementType() == Ty) 1697 return GV; 1698 1699 // Because C++ name mangling, the only way we can end up with an already 1700 // existing global with the same name is if it has been declared extern "C". 1701 assert(GV->isDeclaration() && "Declaration has wrong type!"); 1702 OldGV = GV; 1703 } 1704 1705 // Create a new variable. 1706 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 1707 Linkage, nullptr, Name); 1708 1709 if (OldGV) { 1710 // Replace occurrences of the old variable if needed. 1711 GV->takeName(OldGV); 1712 1713 if (!OldGV->use_empty()) { 1714 llvm::Constant *NewPtrForOldDecl = 1715 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 1716 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 1717 } 1718 1719 OldGV->eraseFromParent(); 1720 } 1721 1722 return GV; 1723 } 1724 1725 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1726 /// given global variable. If Ty is non-null and if the global doesn't exist, 1727 /// then it will be created with the specified type instead of whatever the 1728 /// normal requested type would be. 1729 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1730 llvm::Type *Ty) { 1731 assert(D->hasGlobalStorage() && "Not a global variable"); 1732 QualType ASTTy = D->getType(); 1733 if (!Ty) 1734 Ty = getTypes().ConvertTypeForMem(ASTTy); 1735 1736 llvm::PointerType *PTy = 1737 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 1738 1739 StringRef MangledName = getMangledName(D); 1740 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1741 } 1742 1743 /// CreateRuntimeVariable - Create a new runtime global variable with the 1744 /// specified type and name. 1745 llvm::Constant * 1746 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 1747 StringRef Name) { 1748 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 1749 } 1750 1751 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1752 assert(!D->getInit() && "Cannot emit definite definitions here!"); 1753 1754 if (MayDeferGeneration(D)) { 1755 // If we have not seen a reference to this variable yet, place it 1756 // into the deferred declarations table to be emitted if needed 1757 // later. 1758 StringRef MangledName = getMangledName(D); 1759 if (!GetGlobalValue(MangledName)) { 1760 DeferredDecls[MangledName] = D; 1761 return; 1762 } 1763 } 1764 1765 // The tentative definition is the only definition. 1766 EmitGlobalVarDefinition(D); 1767 } 1768 1769 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 1770 return Context.toCharUnitsFromBits( 1771 TheDataLayout.getTypeStoreSizeInBits(Ty)); 1772 } 1773 1774 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 1775 unsigned AddrSpace) { 1776 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) { 1777 if (D->hasAttr<CUDAConstantAttr>()) 1778 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 1779 else if (D->hasAttr<CUDASharedAttr>()) 1780 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 1781 else 1782 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 1783 } 1784 1785 return AddrSpace; 1786 } 1787 1788 template<typename SomeDecl> 1789 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 1790 llvm::GlobalValue *GV) { 1791 if (!getLangOpts().CPlusPlus) 1792 return; 1793 1794 // Must have 'used' attribute, or else inline assembly can't rely on 1795 // the name existing. 1796 if (!D->template hasAttr<UsedAttr>()) 1797 return; 1798 1799 // Must have internal linkage and an ordinary name. 1800 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 1801 return; 1802 1803 // Must be in an extern "C" context. Entities declared directly within 1804 // a record are not extern "C" even if the record is in such a context. 1805 const SomeDecl *First = D->getFirstDecl(); 1806 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 1807 return; 1808 1809 // OK, this is an internal linkage entity inside an extern "C" linkage 1810 // specification. Make a note of that so we can give it the "expected" 1811 // mangled name if nothing else is using that name. 1812 std::pair<StaticExternCMap::iterator, bool> R = 1813 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 1814 1815 // If we have multiple internal linkage entities with the same name 1816 // in extern "C" regions, none of them gets that name. 1817 if (!R.second) 1818 R.first->second = nullptr; 1819 } 1820 1821 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1822 llvm::Constant *Init = nullptr; 1823 QualType ASTTy = D->getType(); 1824 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1825 bool NeedsGlobalCtor = false; 1826 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 1827 1828 const VarDecl *InitDecl; 1829 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 1830 1831 if (!InitExpr) { 1832 // This is a tentative definition; tentative definitions are 1833 // implicitly initialized with { 0 }. 1834 // 1835 // Note that tentative definitions are only emitted at the end of 1836 // a translation unit, so they should never have incomplete 1837 // type. In addition, EmitTentativeDefinition makes sure that we 1838 // never attempt to emit a tentative definition if a real one 1839 // exists. A use may still exists, however, so we still may need 1840 // to do a RAUW. 1841 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1842 Init = EmitNullConstant(D->getType()); 1843 } else { 1844 initializedGlobalDecl = GlobalDecl(D); 1845 Init = EmitConstantInit(*InitDecl); 1846 1847 if (!Init) { 1848 QualType T = InitExpr->getType(); 1849 if (D->getType()->isReferenceType()) 1850 T = D->getType(); 1851 1852 if (getLangOpts().CPlusPlus) { 1853 Init = EmitNullConstant(T); 1854 NeedsGlobalCtor = true; 1855 } else { 1856 ErrorUnsupported(D, "static initializer"); 1857 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1858 } 1859 } else { 1860 // We don't need an initializer, so remove the entry for the delayed 1861 // initializer position (just in case this entry was delayed) if we 1862 // also don't need to register a destructor. 1863 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 1864 DelayedCXXInitPosition.erase(D); 1865 } 1866 } 1867 1868 llvm::Type* InitType = Init->getType(); 1869 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1870 1871 // Strip off a bitcast if we got one back. 1872 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1873 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1874 CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 1875 // All zero index gep. 1876 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1877 Entry = CE->getOperand(0); 1878 } 1879 1880 // Entry is now either a Function or GlobalVariable. 1881 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1882 1883 // We have a definition after a declaration with the wrong type. 1884 // We must make a new GlobalVariable* and update everything that used OldGV 1885 // (a declaration or tentative definition) with the new GlobalVariable* 1886 // (which will be a definition). 1887 // 1888 // This happens if there is a prototype for a global (e.g. 1889 // "extern int x[];") and then a definition of a different type (e.g. 1890 // "int x[10];"). This also happens when an initializer has a different type 1891 // from the type of the global (this happens with unions). 1892 if (!GV || 1893 GV->getType()->getElementType() != InitType || 1894 GV->getType()->getAddressSpace() != 1895 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 1896 1897 // Move the old entry aside so that we'll create a new one. 1898 Entry->setName(StringRef()); 1899 1900 // Make a new global with the correct type, this is now guaranteed to work. 1901 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1902 1903 // Replace all uses of the old global with the new global 1904 llvm::Constant *NewPtrForOldDecl = 1905 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1906 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1907 1908 // Erase the old global, since it is no longer used. 1909 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1910 } 1911 1912 MaybeHandleStaticInExternC(D, GV); 1913 1914 if (D->hasAttr<AnnotateAttr>()) 1915 AddGlobalAnnotations(D, GV); 1916 1917 GV->setInitializer(Init); 1918 1919 // If it is safe to mark the global 'constant', do so now. 1920 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 1921 isTypeConstant(D->getType(), true)); 1922 1923 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1924 1925 // Set the llvm linkage type as appropriate. 1926 llvm::GlobalValue::LinkageTypes Linkage = 1927 getLLVMLinkageVarDefinition(D, GV->isConstant()); 1928 1929 // On Darwin, the backing variable for a C++11 thread_local variable always 1930 // has internal linkage; all accesses should just be calls to the 1931 // Itanium-specified entry point, which has the normal linkage of the 1932 // variable. 1933 if (const auto *VD = dyn_cast<VarDecl>(D)) 1934 if (!VD->isStaticLocal() && VD->getTLSKind() == VarDecl::TLS_Dynamic && 1935 Context.getTargetInfo().getTriple().isMacOSX()) 1936 Linkage = llvm::GlobalValue::InternalLinkage; 1937 1938 GV->setLinkage(Linkage); 1939 if (D->hasAttr<DLLImportAttr>()) 1940 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 1941 else if (D->hasAttr<DLLExportAttr>()) 1942 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1943 1944 if (Linkage == llvm::GlobalVariable::CommonLinkage) 1945 // common vars aren't constant even if declared const. 1946 GV->setConstant(false); 1947 1948 setNonAliasAttributes(D, GV); 1949 1950 // Emit the initializer function if necessary. 1951 if (NeedsGlobalCtor || NeedsGlobalDtor) 1952 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 1953 1954 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 1955 1956 // Emit global variable debug information. 1957 if (CGDebugInfo *DI = getModuleDebugInfo()) 1958 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 1959 DI->EmitGlobalVariable(GV, D); 1960 } 1961 1962 static bool isVarDeclStrongDefinition(const ASTContext &Context, 1963 const VarDecl *D, bool NoCommon) { 1964 // Don't give variables common linkage if -fno-common was specified unless it 1965 // was overridden by a NoCommon attribute. 1966 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 1967 return true; 1968 1969 // C11 6.9.2/2: 1970 // A declaration of an identifier for an object that has file scope without 1971 // an initializer, and without a storage-class specifier or with the 1972 // storage-class specifier static, constitutes a tentative definition. 1973 if (D->getInit() || D->hasExternalStorage()) 1974 return true; 1975 1976 // A variable cannot be both common and exist in a section. 1977 if (D->hasAttr<SectionAttr>()) 1978 return true; 1979 1980 // Thread local vars aren't considered common linkage. 1981 if (D->getTLSKind()) 1982 return true; 1983 1984 // Tentative definitions marked with WeakImportAttr are true definitions. 1985 if (D->hasAttr<WeakImportAttr>()) 1986 return true; 1987 1988 // Declarations with a required alignment do not have common linakge in MSVC 1989 // mode. 1990 if (Context.getLangOpts().MSVCCompat && 1991 (Context.isAlignmentRequired(D->getType()) || D->hasAttr<AlignedAttr>())) 1992 return true; 1993 1994 return false; 1995 } 1996 1997 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 1998 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 1999 if (Linkage == GVA_Internal) 2000 return llvm::Function::InternalLinkage; 2001 2002 if (D->hasAttr<WeakAttr>()) { 2003 if (IsConstantVariable) 2004 return llvm::GlobalVariable::WeakODRLinkage; 2005 else 2006 return llvm::GlobalVariable::WeakAnyLinkage; 2007 } 2008 2009 // We are guaranteed to have a strong definition somewhere else, 2010 // so we can use available_externally linkage. 2011 if (Linkage == GVA_AvailableExternally) 2012 return llvm::Function::AvailableExternallyLinkage; 2013 2014 // Note that Apple's kernel linker doesn't support symbol 2015 // coalescing, so we need to avoid linkonce and weak linkages there. 2016 // Normally, this means we just map to internal, but for explicit 2017 // instantiations we'll map to external. 2018 2019 // In C++, the compiler has to emit a definition in every translation unit 2020 // that references the function. We should use linkonce_odr because 2021 // a) if all references in this translation unit are optimized away, we 2022 // don't need to codegen it. b) if the function persists, it needs to be 2023 // merged with other definitions. c) C++ has the ODR, so we know the 2024 // definition is dependable. 2025 if (Linkage == GVA_DiscardableODR) 2026 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 2027 : llvm::Function::InternalLinkage; 2028 2029 // An explicit instantiation of a template has weak linkage, since 2030 // explicit instantiations can occur in multiple translation units 2031 // and must all be equivalent. However, we are not allowed to 2032 // throw away these explicit instantiations. 2033 if (Linkage == GVA_StrongODR) 2034 return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage 2035 : llvm::Function::ExternalLinkage; 2036 2037 // C++ doesn't have tentative definitions and thus cannot have common 2038 // linkage. 2039 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 2040 !isVarDeclStrongDefinition(Context, cast<VarDecl>(D), 2041 CodeGenOpts.NoCommon)) 2042 return llvm::GlobalVariable::CommonLinkage; 2043 2044 // selectany symbols are externally visible, so use weak instead of 2045 // linkonce. MSVC optimizes away references to const selectany globals, so 2046 // all definitions should be the same and ODR linkage should be used. 2047 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 2048 if (D->hasAttr<SelectAnyAttr>()) 2049 return llvm::GlobalVariable::WeakODRLinkage; 2050 2051 // Otherwise, we have strong external linkage. 2052 assert(Linkage == GVA_StrongExternal); 2053 return llvm::GlobalVariable::ExternalLinkage; 2054 } 2055 2056 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 2057 const VarDecl *VD, bool IsConstant) { 2058 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 2059 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 2060 } 2061 2062 /// Replace the uses of a function that was declared with a non-proto type. 2063 /// We want to silently drop extra arguments from call sites 2064 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2065 llvm::Function *newFn) { 2066 // Fast path. 2067 if (old->use_empty()) return; 2068 2069 llvm::Type *newRetTy = newFn->getReturnType(); 2070 SmallVector<llvm::Value*, 4> newArgs; 2071 2072 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2073 ui != ue; ) { 2074 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 2075 llvm::User *user = use->getUser(); 2076 2077 // Recognize and replace uses of bitcasts. Most calls to 2078 // unprototyped functions will use bitcasts. 2079 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2080 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2081 replaceUsesOfNonProtoConstant(bitcast, newFn); 2082 continue; 2083 } 2084 2085 // Recognize calls to the function. 2086 llvm::CallSite callSite(user); 2087 if (!callSite) continue; 2088 if (!callSite.isCallee(&*use)) continue; 2089 2090 // If the return types don't match exactly, then we can't 2091 // transform this call unless it's dead. 2092 if (callSite->getType() != newRetTy && !callSite->use_empty()) 2093 continue; 2094 2095 // Get the call site's attribute list. 2096 SmallVector<llvm::AttributeSet, 8> newAttrs; 2097 llvm::AttributeSet oldAttrs = callSite.getAttributes(); 2098 2099 // Collect any return attributes from the call. 2100 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 2101 newAttrs.push_back( 2102 llvm::AttributeSet::get(newFn->getContext(), 2103 oldAttrs.getRetAttributes())); 2104 2105 // If the function was passed too few arguments, don't transform. 2106 unsigned newNumArgs = newFn->arg_size(); 2107 if (callSite.arg_size() < newNumArgs) continue; 2108 2109 // If extra arguments were passed, we silently drop them. 2110 // If any of the types mismatch, we don't transform. 2111 unsigned argNo = 0; 2112 bool dontTransform = false; 2113 for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 2114 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 2115 if (callSite.getArgument(argNo)->getType() != ai->getType()) { 2116 dontTransform = true; 2117 break; 2118 } 2119 2120 // Add any parameter attributes. 2121 if (oldAttrs.hasAttributes(argNo + 1)) 2122 newAttrs. 2123 push_back(llvm:: 2124 AttributeSet::get(newFn->getContext(), 2125 oldAttrs.getParamAttributes(argNo + 1))); 2126 } 2127 if (dontTransform) 2128 continue; 2129 2130 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 2131 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 2132 oldAttrs.getFnAttributes())); 2133 2134 // Okay, we can transform this. Create the new call instruction and copy 2135 // over the required information. 2136 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2137 2138 llvm::CallSite newCall; 2139 if (callSite.isCall()) { 2140 newCall = llvm::CallInst::Create(newFn, newArgs, "", 2141 callSite.getInstruction()); 2142 } else { 2143 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 2144 newCall = llvm::InvokeInst::Create(newFn, 2145 oldInvoke->getNormalDest(), 2146 oldInvoke->getUnwindDest(), 2147 newArgs, "", 2148 callSite.getInstruction()); 2149 } 2150 newArgs.clear(); // for the next iteration 2151 2152 if (!newCall->getType()->isVoidTy()) 2153 newCall->takeName(callSite.getInstruction()); 2154 newCall.setAttributes( 2155 llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2156 newCall.setCallingConv(callSite.getCallingConv()); 2157 2158 // Finally, remove the old call, replacing any uses with the new one. 2159 if (!callSite->use_empty()) 2160 callSite->replaceAllUsesWith(newCall.getInstruction()); 2161 2162 // Copy debug location attached to CI. 2163 if (!callSite->getDebugLoc().isUnknown()) 2164 newCall->setDebugLoc(callSite->getDebugLoc()); 2165 callSite->eraseFromParent(); 2166 } 2167 } 2168 2169 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2170 /// implement a function with no prototype, e.g. "int foo() {}". If there are 2171 /// existing call uses of the old function in the module, this adjusts them to 2172 /// call the new function directly. 2173 /// 2174 /// This is not just a cleanup: the always_inline pass requires direct calls to 2175 /// functions to be able to inline them. If there is a bitcast in the way, it 2176 /// won't inline them. Instcombine normally deletes these calls, but it isn't 2177 /// run at -O0. 2178 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2179 llvm::Function *NewFn) { 2180 // If we're redefining a global as a function, don't transform it. 2181 if (!isa<llvm::Function>(Old)) return; 2182 2183 replaceUsesOfNonProtoConstant(Old, NewFn); 2184 } 2185 2186 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2187 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2188 // If we have a definition, this might be a deferred decl. If the 2189 // instantiation is explicit, make sure we emit it at the end. 2190 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2191 GetAddrOfGlobalVar(VD); 2192 2193 EmitTopLevelDecl(VD); 2194 } 2195 2196 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 2197 llvm::GlobalValue *GV) { 2198 const auto *D = cast<FunctionDecl>(GD.getDecl()); 2199 2200 // Compute the function info and LLVM type. 2201 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2202 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2203 2204 // Get or create the prototype for the function. 2205 if (!GV) { 2206 llvm::Constant *C = 2207 GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true); 2208 2209 // Strip off a bitcast if we got one back. 2210 if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) { 2211 assert(CE->getOpcode() == llvm::Instruction::BitCast); 2212 GV = cast<llvm::GlobalValue>(CE->getOperand(0)); 2213 } else { 2214 GV = cast<llvm::GlobalValue>(C); 2215 } 2216 } 2217 2218 if (!GV->isDeclaration()) { 2219 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name); 2220 GlobalDecl OldGD = Manglings.lookup(GV->getName()); 2221 if (auto *Prev = OldGD.getDecl()) 2222 getDiags().Report(Prev->getLocation(), diag::note_previous_definition); 2223 return; 2224 } 2225 2226 if (GV->getType()->getElementType() != Ty) { 2227 // If the types mismatch then we have to rewrite the definition. 2228 assert(GV->isDeclaration() && "Shouldn't replace non-declaration"); 2229 2230 // F is the Function* for the one with the wrong type, we must make a new 2231 // Function* and update everything that used F (a declaration) with the new 2232 // Function* (which will be a definition). 2233 // 2234 // This happens if there is a prototype for a function 2235 // (e.g. "int f()") and then a definition of a different type 2236 // (e.g. "int f(int x)"). Move the old function aside so that it 2237 // doesn't interfere with GetAddrOfFunction. 2238 GV->setName(StringRef()); 2239 auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 2240 2241 // This might be an implementation of a function without a 2242 // prototype, in which case, try to do special replacement of 2243 // calls which match the new prototype. The really key thing here 2244 // is that we also potentially drop arguments from the call site 2245 // so as to make a direct call, which makes the inliner happier 2246 // and suppresses a number of optimizer warnings (!) about 2247 // dropping arguments. 2248 if (!GV->use_empty()) { 2249 ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn); 2250 GV->removeDeadConstantUsers(); 2251 } 2252 2253 // Replace uses of F with the Function we will endow with a body. 2254 if (!GV->use_empty()) { 2255 llvm::Constant *NewPtrForOldDecl = 2256 llvm::ConstantExpr::getBitCast(NewFn, GV->getType()); 2257 GV->replaceAllUsesWith(NewPtrForOldDecl); 2258 } 2259 2260 // Ok, delete the old function now, which is dead. 2261 GV->eraseFromParent(); 2262 2263 GV = NewFn; 2264 } 2265 2266 // We need to set linkage and visibility on the function before 2267 // generating code for it because various parts of IR generation 2268 // want to propagate this information down (e.g. to local static 2269 // declarations). 2270 auto *Fn = cast<llvm::Function>(GV); 2271 setFunctionLinkage(GD, Fn); 2272 2273 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 2274 setGlobalVisibility(Fn, D); 2275 2276 MaybeHandleStaticInExternC(D, Fn); 2277 2278 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2279 2280 setFunctionDefinitionAttributes(D, Fn); 2281 SetLLVMFunctionAttributesForDefinition(D, Fn); 2282 2283 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2284 AddGlobalCtor(Fn, CA->getPriority()); 2285 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2286 AddGlobalDtor(Fn, DA->getPriority()); 2287 if (D->hasAttr<AnnotateAttr>()) 2288 AddGlobalAnnotations(D, Fn); 2289 } 2290 2291 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 2292 const auto *D = cast<ValueDecl>(GD.getDecl()); 2293 const AliasAttr *AA = D->getAttr<AliasAttr>(); 2294 assert(AA && "Not an alias?"); 2295 2296 StringRef MangledName = getMangledName(GD); 2297 2298 // If there is a definition in the module, then it wins over the alias. 2299 // This is dubious, but allow it to be safe. Just ignore the alias. 2300 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2301 if (Entry && !Entry->isDeclaration()) 2302 return; 2303 2304 Aliases.push_back(GD); 2305 2306 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2307 2308 // Create a reference to the named value. This ensures that it is emitted 2309 // if a deferred decl. 2310 llvm::Constant *Aliasee; 2311 if (isa<llvm::FunctionType>(DeclTy)) 2312 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 2313 /*ForVTable=*/false); 2314 else 2315 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2316 llvm::PointerType::getUnqual(DeclTy), 2317 nullptr); 2318 2319 // Create the new alias itself, but don't set a name yet. 2320 auto *GA = llvm::GlobalAlias::create( 2321 cast<llvm::PointerType>(Aliasee->getType())->getElementType(), 0, 2322 llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 2323 2324 if (Entry) { 2325 if (GA->getAliasee() == Entry) { 2326 Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 2327 return; 2328 } 2329 2330 assert(Entry->isDeclaration()); 2331 2332 // If there is a declaration in the module, then we had an extern followed 2333 // by the alias, as in: 2334 // extern int test6(); 2335 // ... 2336 // int test6() __attribute__((alias("test7"))); 2337 // 2338 // Remove it and replace uses of it with the alias. 2339 GA->takeName(Entry); 2340 2341 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2342 Entry->getType())); 2343 Entry->eraseFromParent(); 2344 } else { 2345 GA->setName(MangledName); 2346 } 2347 2348 // Set attributes which are particular to an alias; this is a 2349 // specialization of the attributes which may be set on a global 2350 // variable/function. 2351 if (D->hasAttr<DLLExportAttr>()) { 2352 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 2353 // The dllexport attribute is ignored for undefined symbols. 2354 if (FD->hasBody()) 2355 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 2356 } else { 2357 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 2358 } 2359 } else if (D->hasAttr<WeakAttr>() || 2360 D->hasAttr<WeakRefAttr>() || 2361 D->isWeakImported()) { 2362 GA->setLinkage(llvm::Function::WeakAnyLinkage); 2363 } 2364 2365 SetCommonAttributes(D, GA); 2366 } 2367 2368 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 2369 ArrayRef<llvm::Type*> Tys) { 2370 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 2371 Tys); 2372 } 2373 2374 static llvm::StringMapEntry<llvm::Constant*> & 2375 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2376 const StringLiteral *Literal, 2377 bool TargetIsLSB, 2378 bool &IsUTF16, 2379 unsigned &StringLength) { 2380 StringRef String = Literal->getString(); 2381 unsigned NumBytes = String.size(); 2382 2383 // Check for simple case. 2384 if (!Literal->containsNonAsciiOrNull()) { 2385 StringLength = NumBytes; 2386 return Map.GetOrCreateValue(String); 2387 } 2388 2389 // Otherwise, convert the UTF8 literals into a string of shorts. 2390 IsUTF16 = true; 2391 2392 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 2393 const UTF8 *FromPtr = (const UTF8 *)String.data(); 2394 UTF16 *ToPtr = &ToBuf[0]; 2395 2396 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2397 &ToPtr, ToPtr + NumBytes, 2398 strictConversion); 2399 2400 // ConvertUTF8toUTF16 returns the length in ToPtr. 2401 StringLength = ToPtr - &ToBuf[0]; 2402 2403 // Add an explicit null. 2404 *ToPtr = 0; 2405 return Map. 2406 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()), 2407 (StringLength + 1) * 2)); 2408 } 2409 2410 static llvm::StringMapEntry<llvm::Constant*> & 2411 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2412 const StringLiteral *Literal, 2413 unsigned &StringLength) { 2414 StringRef String = Literal->getString(); 2415 StringLength = String.size(); 2416 return Map.GetOrCreateValue(String); 2417 } 2418 2419 llvm::Constant * 2420 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2421 unsigned StringLength = 0; 2422 bool isUTF16 = false; 2423 llvm::StringMapEntry<llvm::Constant*> &Entry = 2424 GetConstantCFStringEntry(CFConstantStringMap, Literal, 2425 getDataLayout().isLittleEndian(), 2426 isUTF16, StringLength); 2427 2428 if (llvm::Constant *C = Entry.getValue()) 2429 return C; 2430 2431 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2432 llvm::Constant *Zeros[] = { Zero, Zero }; 2433 llvm::Value *V; 2434 2435 // If we don't already have it, get __CFConstantStringClassReference. 2436 if (!CFConstantStringClassRef) { 2437 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2438 Ty = llvm::ArrayType::get(Ty, 0); 2439 llvm::Constant *GV = CreateRuntimeVariable(Ty, 2440 "__CFConstantStringClassReference"); 2441 // Decay array -> ptr 2442 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2443 CFConstantStringClassRef = V; 2444 } 2445 else 2446 V = CFConstantStringClassRef; 2447 2448 QualType CFTy = getContext().getCFConstantStringType(); 2449 2450 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2451 2452 llvm::Constant *Fields[4]; 2453 2454 // Class pointer. 2455 Fields[0] = cast<llvm::ConstantExpr>(V); 2456 2457 // Flags. 2458 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2459 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2460 llvm::ConstantInt::get(Ty, 0x07C8); 2461 2462 // String pointer. 2463 llvm::Constant *C = nullptr; 2464 if (isUTF16) { 2465 ArrayRef<uint16_t> Arr = 2466 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>( 2467 const_cast<char *>(Entry.getKey().data())), 2468 Entry.getKey().size() / 2); 2469 C = llvm::ConstantDataArray::get(VMContext, Arr); 2470 } else { 2471 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2472 } 2473 2474 // Note: -fwritable-strings doesn't make the backing store strings of 2475 // CFStrings writable. (See <rdar://problem/10657500>) 2476 auto *GV = 2477 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 2478 llvm::GlobalValue::PrivateLinkage, C, ".str"); 2479 GV->setUnnamedAddr(true); 2480 // Don't enforce the target's minimum global alignment, since the only use 2481 // of the string is via this class initializer. 2482 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without 2483 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing 2484 // that changes the section it ends in, which surprises ld64. 2485 if (isUTF16) { 2486 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2487 GV->setAlignment(Align.getQuantity()); 2488 GV->setSection("__TEXT,__ustring"); 2489 } else { 2490 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2491 GV->setAlignment(Align.getQuantity()); 2492 GV->setSection("__TEXT,__cstring,cstring_literals"); 2493 } 2494 2495 // String. 2496 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2497 2498 if (isUTF16) 2499 // Cast the UTF16 string to the correct type. 2500 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2501 2502 // String length. 2503 Ty = getTypes().ConvertType(getContext().LongTy); 2504 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2505 2506 // The struct. 2507 C = llvm::ConstantStruct::get(STy, Fields); 2508 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2509 llvm::GlobalVariable::PrivateLinkage, C, 2510 "_unnamed_cfstring_"); 2511 GV->setSection("__DATA,__cfstring"); 2512 Entry.setValue(GV); 2513 2514 return GV; 2515 } 2516 2517 llvm::Constant * 2518 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2519 unsigned StringLength = 0; 2520 llvm::StringMapEntry<llvm::Constant*> &Entry = 2521 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2522 2523 if (llvm::Constant *C = Entry.getValue()) 2524 return C; 2525 2526 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2527 llvm::Constant *Zeros[] = { Zero, Zero }; 2528 llvm::Value *V; 2529 // If we don't already have it, get _NSConstantStringClassReference. 2530 if (!ConstantStringClassRef) { 2531 std::string StringClass(getLangOpts().ObjCConstantStringClass); 2532 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2533 llvm::Constant *GV; 2534 if (LangOpts.ObjCRuntime.isNonFragile()) { 2535 std::string str = 2536 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2537 : "OBJC_CLASS_$_" + StringClass; 2538 GV = getObjCRuntime().GetClassGlobal(str); 2539 // Make sure the result is of the correct type. 2540 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2541 V = llvm::ConstantExpr::getBitCast(GV, PTy); 2542 ConstantStringClassRef = V; 2543 } else { 2544 std::string str = 2545 StringClass.empty() ? "_NSConstantStringClassReference" 2546 : "_" + StringClass + "ClassReference"; 2547 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 2548 GV = CreateRuntimeVariable(PTy, str); 2549 // Decay array -> ptr 2550 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2551 ConstantStringClassRef = V; 2552 } 2553 } 2554 else 2555 V = ConstantStringClassRef; 2556 2557 if (!NSConstantStringType) { 2558 // Construct the type for a constant NSString. 2559 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString"); 2560 D->startDefinition(); 2561 2562 QualType FieldTypes[3]; 2563 2564 // const int *isa; 2565 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 2566 // const char *str; 2567 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 2568 // unsigned int length; 2569 FieldTypes[2] = Context.UnsignedIntTy; 2570 2571 // Create fields 2572 for (unsigned i = 0; i < 3; ++i) { 2573 FieldDecl *Field = FieldDecl::Create(Context, D, 2574 SourceLocation(), 2575 SourceLocation(), nullptr, 2576 FieldTypes[i], /*TInfo=*/nullptr, 2577 /*BitWidth=*/nullptr, 2578 /*Mutable=*/false, 2579 ICIS_NoInit); 2580 Field->setAccess(AS_public); 2581 D->addDecl(Field); 2582 } 2583 2584 D->completeDefinition(); 2585 QualType NSTy = Context.getTagDeclType(D); 2586 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 2587 } 2588 2589 llvm::Constant *Fields[3]; 2590 2591 // Class pointer. 2592 Fields[0] = cast<llvm::ConstantExpr>(V); 2593 2594 // String pointer. 2595 llvm::Constant *C = 2596 llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2597 2598 llvm::GlobalValue::LinkageTypes Linkage; 2599 bool isConstant; 2600 Linkage = llvm::GlobalValue::PrivateLinkage; 2601 isConstant = !LangOpts.WritableStrings; 2602 2603 auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant, 2604 Linkage, C, ".str"); 2605 GV->setUnnamedAddr(true); 2606 // Don't enforce the target's minimum global alignment, since the only use 2607 // of the string is via this class initializer. 2608 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2609 GV->setAlignment(Align.getQuantity()); 2610 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2611 2612 // String length. 2613 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2614 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 2615 2616 // The struct. 2617 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 2618 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2619 llvm::GlobalVariable::PrivateLinkage, C, 2620 "_unnamed_nsstring_"); 2621 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip"; 2622 const char *NSStringNonFragileABISection = 2623 "__DATA,__objc_stringobj,regular,no_dead_strip"; 2624 // FIXME. Fix section. 2625 GV->setSection(LangOpts.ObjCRuntime.isNonFragile() 2626 ? NSStringNonFragileABISection 2627 : NSStringSection); 2628 Entry.setValue(GV); 2629 2630 return GV; 2631 } 2632 2633 QualType CodeGenModule::getObjCFastEnumerationStateType() { 2634 if (ObjCFastEnumerationStateType.isNull()) { 2635 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 2636 D->startDefinition(); 2637 2638 QualType FieldTypes[] = { 2639 Context.UnsignedLongTy, 2640 Context.getPointerType(Context.getObjCIdType()), 2641 Context.getPointerType(Context.UnsignedLongTy), 2642 Context.getConstantArrayType(Context.UnsignedLongTy, 2643 llvm::APInt(32, 5), ArrayType::Normal, 0) 2644 }; 2645 2646 for (size_t i = 0; i < 4; ++i) { 2647 FieldDecl *Field = FieldDecl::Create(Context, 2648 D, 2649 SourceLocation(), 2650 SourceLocation(), nullptr, 2651 FieldTypes[i], /*TInfo=*/nullptr, 2652 /*BitWidth=*/nullptr, 2653 /*Mutable=*/false, 2654 ICIS_NoInit); 2655 Field->setAccess(AS_public); 2656 D->addDecl(Field); 2657 } 2658 2659 D->completeDefinition(); 2660 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 2661 } 2662 2663 return ObjCFastEnumerationStateType; 2664 } 2665 2666 llvm::Constant * 2667 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 2668 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 2669 2670 // Don't emit it as the address of the string, emit the string data itself 2671 // as an inline array. 2672 if (E->getCharByteWidth() == 1) { 2673 SmallString<64> Str(E->getString()); 2674 2675 // Resize the string to the right size, which is indicated by its type. 2676 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 2677 Str.resize(CAT->getSize().getZExtValue()); 2678 return llvm::ConstantDataArray::getString(VMContext, Str, false); 2679 } 2680 2681 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 2682 llvm::Type *ElemTy = AType->getElementType(); 2683 unsigned NumElements = AType->getNumElements(); 2684 2685 // Wide strings have either 2-byte or 4-byte elements. 2686 if (ElemTy->getPrimitiveSizeInBits() == 16) { 2687 SmallVector<uint16_t, 32> Elements; 2688 Elements.reserve(NumElements); 2689 2690 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2691 Elements.push_back(E->getCodeUnit(i)); 2692 Elements.resize(NumElements); 2693 return llvm::ConstantDataArray::get(VMContext, Elements); 2694 } 2695 2696 assert(ElemTy->getPrimitiveSizeInBits() == 32); 2697 SmallVector<uint32_t, 32> Elements; 2698 Elements.reserve(NumElements); 2699 2700 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2701 Elements.push_back(E->getCodeUnit(i)); 2702 Elements.resize(NumElements); 2703 return llvm::ConstantDataArray::get(VMContext, Elements); 2704 } 2705 2706 static llvm::GlobalVariable * 2707 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 2708 CodeGenModule &CGM, StringRef GlobalName, 2709 unsigned Alignment) { 2710 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 2711 unsigned AddrSpace = 0; 2712 if (CGM.getLangOpts().OpenCL) 2713 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 2714 2715 // Create a global variable for this string 2716 auto *GV = new llvm::GlobalVariable( 2717 CGM.getModule(), C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, 2718 GlobalName, nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 2719 GV->setAlignment(Alignment); 2720 GV->setUnnamedAddr(true); 2721 return GV; 2722 } 2723 2724 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 2725 /// constant array for the given string literal. 2726 llvm::GlobalVariable * 2727 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 2728 auto Alignment = 2729 getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity(); 2730 2731 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 2732 llvm::GlobalVariable **Entry = nullptr; 2733 if (!LangOpts.WritableStrings) { 2734 Entry = &ConstantStringMap[C]; 2735 if (auto GV = *Entry) { 2736 if (Alignment > GV->getAlignment()) 2737 GV->setAlignment(Alignment); 2738 return GV; 2739 } 2740 } 2741 2742 SmallString<256> MangledNameBuffer; 2743 StringRef GlobalVariableName; 2744 llvm::GlobalValue::LinkageTypes LT; 2745 2746 // Mangle the string literal if the ABI allows for it. However, we cannot 2747 // do this if we are compiling with ASan or -fwritable-strings because they 2748 // rely on strings having normal linkage. 2749 if (!LangOpts.WritableStrings && !LangOpts.Sanitize.Address && 2750 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 2751 llvm::raw_svector_ostream Out(MangledNameBuffer); 2752 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 2753 Out.flush(); 2754 2755 LT = llvm::GlobalValue::LinkOnceODRLinkage; 2756 GlobalVariableName = MangledNameBuffer; 2757 } else { 2758 LT = llvm::GlobalValue::PrivateLinkage; 2759 GlobalVariableName = ".str"; 2760 } 2761 2762 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 2763 if (Entry) 2764 *Entry = GV; 2765 2766 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>"); 2767 return GV; 2768 } 2769 2770 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 2771 /// array for the given ObjCEncodeExpr node. 2772 llvm::GlobalVariable * 2773 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 2774 std::string Str; 2775 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 2776 2777 return GetAddrOfConstantCString(Str); 2778 } 2779 2780 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 2781 /// the literal and a terminating '\0' character. 2782 /// The result has pointer to array type. 2783 llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString( 2784 const std::string &Str, const char *GlobalName, unsigned Alignment) { 2785 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 2786 if (Alignment == 0) { 2787 Alignment = getContext() 2788 .getAlignOfGlobalVarInChars(getContext().CharTy) 2789 .getQuantity(); 2790 } 2791 2792 llvm::Constant *C = 2793 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 2794 2795 // Don't share any string literals if strings aren't constant. 2796 llvm::GlobalVariable **Entry = nullptr; 2797 if (!LangOpts.WritableStrings) { 2798 Entry = &ConstantStringMap[C]; 2799 if (auto GV = *Entry) { 2800 if (Alignment > GV->getAlignment()) 2801 GV->setAlignment(Alignment); 2802 return GV; 2803 } 2804 } 2805 2806 // Get the default prefix if a name wasn't specified. 2807 if (!GlobalName) 2808 GlobalName = ".str"; 2809 // Create a global variable for this. 2810 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 2811 GlobalName, Alignment); 2812 if (Entry) 2813 *Entry = GV; 2814 return GV; 2815 } 2816 2817 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary( 2818 const MaterializeTemporaryExpr *E, const Expr *Init) { 2819 assert((E->getStorageDuration() == SD_Static || 2820 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 2821 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 2822 2823 // If we're not materializing a subobject of the temporary, keep the 2824 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 2825 QualType MaterializedType = Init->getType(); 2826 if (Init == E->GetTemporaryExpr()) 2827 MaterializedType = E->getType(); 2828 2829 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E]; 2830 if (Slot) 2831 return Slot; 2832 2833 // FIXME: If an externally-visible declaration extends multiple temporaries, 2834 // we need to give each temporary the same name in every translation unit (and 2835 // we also need to make the temporaries externally-visible). 2836 SmallString<256> Name; 2837 llvm::raw_svector_ostream Out(Name); 2838 getCXXABI().getMangleContext().mangleReferenceTemporary( 2839 VD, E->getManglingNumber(), Out); 2840 Out.flush(); 2841 2842 APValue *Value = nullptr; 2843 if (E->getStorageDuration() == SD_Static) { 2844 // We might have a cached constant initializer for this temporary. Note 2845 // that this might have a different value from the value computed by 2846 // evaluating the initializer if the surrounding constant expression 2847 // modifies the temporary. 2848 Value = getContext().getMaterializedTemporaryValue(E, false); 2849 if (Value && Value->isUninit()) 2850 Value = nullptr; 2851 } 2852 2853 // Try evaluating it now, it might have a constant initializer. 2854 Expr::EvalResult EvalResult; 2855 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 2856 !EvalResult.hasSideEffects()) 2857 Value = &EvalResult.Val; 2858 2859 llvm::Constant *InitialValue = nullptr; 2860 bool Constant = false; 2861 llvm::Type *Type; 2862 if (Value) { 2863 // The temporary has a constant initializer, use it. 2864 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr); 2865 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 2866 Type = InitialValue->getType(); 2867 } else { 2868 // No initializer, the initialization will be provided when we 2869 // initialize the declaration which performed lifetime extension. 2870 Type = getTypes().ConvertTypeForMem(MaterializedType); 2871 } 2872 2873 // Create a global variable for this lifetime-extended temporary. 2874 llvm::GlobalValue::LinkageTypes Linkage = 2875 getLLVMLinkageVarDefinition(VD, Constant); 2876 // There is no need for this temporary to have global linkage if the global 2877 // variable has external linkage. 2878 if (Linkage == llvm::GlobalVariable::ExternalLinkage) 2879 Linkage = llvm::GlobalVariable::PrivateLinkage; 2880 unsigned AddrSpace = GetGlobalVarAddressSpace( 2881 VD, getContext().getTargetAddressSpace(MaterializedType)); 2882 auto *GV = new llvm::GlobalVariable( 2883 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 2884 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 2885 AddrSpace); 2886 setGlobalVisibility(GV, VD); 2887 GV->setAlignment( 2888 getContext().getTypeAlignInChars(MaterializedType).getQuantity()); 2889 if (VD->getTLSKind()) 2890 setTLSMode(GV, *VD); 2891 Slot = GV; 2892 return GV; 2893 } 2894 2895 /// EmitObjCPropertyImplementations - Emit information for synthesized 2896 /// properties for an implementation. 2897 void CodeGenModule::EmitObjCPropertyImplementations(const 2898 ObjCImplementationDecl *D) { 2899 for (const auto *PID : D->property_impls()) { 2900 // Dynamic is just for type-checking. 2901 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 2902 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2903 2904 // Determine which methods need to be implemented, some may have 2905 // been overridden. Note that ::isPropertyAccessor is not the method 2906 // we want, that just indicates if the decl came from a 2907 // property. What we want to know is if the method is defined in 2908 // this implementation. 2909 if (!D->getInstanceMethod(PD->getGetterName())) 2910 CodeGenFunction(*this).GenerateObjCGetter( 2911 const_cast<ObjCImplementationDecl *>(D), PID); 2912 if (!PD->isReadOnly() && 2913 !D->getInstanceMethod(PD->getSetterName())) 2914 CodeGenFunction(*this).GenerateObjCSetter( 2915 const_cast<ObjCImplementationDecl *>(D), PID); 2916 } 2917 } 2918 } 2919 2920 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 2921 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 2922 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 2923 ivar; ivar = ivar->getNextIvar()) 2924 if (ivar->getType().isDestructedType()) 2925 return true; 2926 2927 return false; 2928 } 2929 2930 /// EmitObjCIvarInitializations - Emit information for ivar initialization 2931 /// for an implementation. 2932 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 2933 // We might need a .cxx_destruct even if we don't have any ivar initializers. 2934 if (needsDestructMethod(D)) { 2935 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 2936 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2937 ObjCMethodDecl *DTORMethod = 2938 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 2939 cxxSelector, getContext().VoidTy, nullptr, D, 2940 /*isInstance=*/true, /*isVariadic=*/false, 2941 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 2942 /*isDefined=*/false, ObjCMethodDecl::Required); 2943 D->addInstanceMethod(DTORMethod); 2944 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 2945 D->setHasDestructors(true); 2946 } 2947 2948 // If the implementation doesn't have any ivar initializers, we don't need 2949 // a .cxx_construct. 2950 if (D->getNumIvarInitializers() == 0) 2951 return; 2952 2953 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 2954 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2955 // The constructor returns 'self'. 2956 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 2957 D->getLocation(), 2958 D->getLocation(), 2959 cxxSelector, 2960 getContext().getObjCIdType(), 2961 nullptr, D, /*isInstance=*/true, 2962 /*isVariadic=*/false, 2963 /*isPropertyAccessor=*/true, 2964 /*isImplicitlyDeclared=*/true, 2965 /*isDefined=*/false, 2966 ObjCMethodDecl::Required); 2967 D->addInstanceMethod(CTORMethod); 2968 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 2969 D->setHasNonZeroConstructors(true); 2970 } 2971 2972 /// EmitNamespace - Emit all declarations in a namespace. 2973 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 2974 for (auto *I : ND->decls()) { 2975 if (const auto *VD = dyn_cast<VarDecl>(I)) 2976 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 2977 VD->getTemplateSpecializationKind() != TSK_Undeclared) 2978 continue; 2979 EmitTopLevelDecl(I); 2980 } 2981 } 2982 2983 // EmitLinkageSpec - Emit all declarations in a linkage spec. 2984 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 2985 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 2986 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 2987 ErrorUnsupported(LSD, "linkage spec"); 2988 return; 2989 } 2990 2991 for (auto *I : LSD->decls()) { 2992 // Meta-data for ObjC class includes references to implemented methods. 2993 // Generate class's method definitions first. 2994 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 2995 for (auto *M : OID->methods()) 2996 EmitTopLevelDecl(M); 2997 } 2998 EmitTopLevelDecl(I); 2999 } 3000 } 3001 3002 /// EmitTopLevelDecl - Emit code for a single top level declaration. 3003 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3004 // Ignore dependent declarations. 3005 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3006 return; 3007 3008 switch (D->getKind()) { 3009 case Decl::CXXConversion: 3010 case Decl::CXXMethod: 3011 case Decl::Function: 3012 // Skip function templates 3013 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 3014 cast<FunctionDecl>(D)->isLateTemplateParsed()) 3015 return; 3016 3017 EmitGlobal(cast<FunctionDecl>(D)); 3018 // Always provide some coverage mapping 3019 // even for the functions that aren't emitted. 3020 AddDeferredUnusedCoverageMapping(D); 3021 break; 3022 3023 case Decl::Var: 3024 // Skip variable templates 3025 if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3026 return; 3027 case Decl::VarTemplateSpecialization: 3028 EmitGlobal(cast<VarDecl>(D)); 3029 break; 3030 3031 // Indirect fields from global anonymous structs and unions can be 3032 // ignored; only the actual variable requires IR gen support. 3033 case Decl::IndirectField: 3034 break; 3035 3036 // C++ Decls 3037 case Decl::Namespace: 3038 EmitNamespace(cast<NamespaceDecl>(D)); 3039 break; 3040 // No code generation needed. 3041 case Decl::UsingShadow: 3042 case Decl::ClassTemplate: 3043 case Decl::VarTemplate: 3044 case Decl::VarTemplatePartialSpecialization: 3045 case Decl::FunctionTemplate: 3046 case Decl::TypeAliasTemplate: 3047 case Decl::Block: 3048 case Decl::Empty: 3049 break; 3050 case Decl::Using: // using X; [C++] 3051 if (CGDebugInfo *DI = getModuleDebugInfo()) 3052 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 3053 return; 3054 case Decl::NamespaceAlias: 3055 if (CGDebugInfo *DI = getModuleDebugInfo()) 3056 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3057 return; 3058 case Decl::UsingDirective: // using namespace X; [C++] 3059 if (CGDebugInfo *DI = getModuleDebugInfo()) 3060 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3061 return; 3062 case Decl::CXXConstructor: 3063 // Skip function templates 3064 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 3065 cast<FunctionDecl>(D)->isLateTemplateParsed()) 3066 return; 3067 3068 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3069 break; 3070 case Decl::CXXDestructor: 3071 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 3072 return; 3073 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3074 break; 3075 3076 case Decl::StaticAssert: 3077 // Nothing to do. 3078 break; 3079 3080 // Objective-C Decls 3081 3082 // Forward declarations, no (immediate) code generation. 3083 case Decl::ObjCInterface: 3084 case Decl::ObjCCategory: 3085 break; 3086 3087 case Decl::ObjCProtocol: { 3088 auto *Proto = cast<ObjCProtocolDecl>(D); 3089 if (Proto->isThisDeclarationADefinition()) 3090 ObjCRuntime->GenerateProtocol(Proto); 3091 break; 3092 } 3093 3094 case Decl::ObjCCategoryImpl: 3095 // Categories have properties but don't support synthesize so we 3096 // can ignore them here. 3097 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3098 break; 3099 3100 case Decl::ObjCImplementation: { 3101 auto *OMD = cast<ObjCImplementationDecl>(D); 3102 EmitObjCPropertyImplementations(OMD); 3103 EmitObjCIvarInitializations(OMD); 3104 ObjCRuntime->GenerateClass(OMD); 3105 // Emit global variable debug information. 3106 if (CGDebugInfo *DI = getModuleDebugInfo()) 3107 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 3108 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3109 OMD->getClassInterface()), OMD->getLocation()); 3110 break; 3111 } 3112 case Decl::ObjCMethod: { 3113 auto *OMD = cast<ObjCMethodDecl>(D); 3114 // If this is not a prototype, emit the body. 3115 if (OMD->getBody()) 3116 CodeGenFunction(*this).GenerateObjCMethod(OMD); 3117 break; 3118 } 3119 case Decl::ObjCCompatibleAlias: 3120 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3121 break; 3122 3123 case Decl::LinkageSpec: 3124 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3125 break; 3126 3127 case Decl::FileScopeAsm: { 3128 auto *AD = cast<FileScopeAsmDecl>(D); 3129 StringRef AsmString = AD->getAsmString()->getString(); 3130 3131 const std::string &S = getModule().getModuleInlineAsm(); 3132 if (S.empty()) 3133 getModule().setModuleInlineAsm(AsmString); 3134 else if (S.end()[-1] == '\n') 3135 getModule().setModuleInlineAsm(S + AsmString.str()); 3136 else 3137 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 3138 break; 3139 } 3140 3141 case Decl::Import: { 3142 auto *Import = cast<ImportDecl>(D); 3143 3144 // Ignore import declarations that come from imported modules. 3145 if (clang::Module *Owner = Import->getOwningModule()) { 3146 if (getLangOpts().CurrentModule.empty() || 3147 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule) 3148 break; 3149 } 3150 3151 ImportedModules.insert(Import->getImportedModule()); 3152 break; 3153 } 3154 3155 case Decl::ClassTemplateSpecialization: { 3156 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 3157 if (DebugInfo && 3158 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition) 3159 DebugInfo->completeTemplateDefinition(*Spec); 3160 } 3161 3162 default: 3163 // Make sure we handled everything we should, every other kind is a 3164 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3165 // function. Need to recode Decl::Kind to do that easily. 3166 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 3167 } 3168 } 3169 3170 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 3171 // Do we need to generate coverage mapping? 3172 if (!CodeGenOpts.CoverageMapping) 3173 return; 3174 switch (D->getKind()) { 3175 case Decl::CXXConversion: 3176 case Decl::CXXMethod: 3177 case Decl::Function: 3178 case Decl::ObjCMethod: 3179 case Decl::CXXConstructor: 3180 case Decl::CXXDestructor: { 3181 if (!cast<FunctionDecl>(D)->hasBody()) 3182 return; 3183 auto I = DeferredEmptyCoverageMappingDecls.find(D); 3184 if (I == DeferredEmptyCoverageMappingDecls.end()) 3185 DeferredEmptyCoverageMappingDecls[D] = true; 3186 break; 3187 } 3188 default: 3189 break; 3190 }; 3191 } 3192 3193 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 3194 // Do we need to generate coverage mapping? 3195 if (!CodeGenOpts.CoverageMapping) 3196 return; 3197 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 3198 if (Fn->isTemplateInstantiation()) 3199 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 3200 } 3201 auto I = DeferredEmptyCoverageMappingDecls.find(D); 3202 if (I == DeferredEmptyCoverageMappingDecls.end()) 3203 DeferredEmptyCoverageMappingDecls[D] = false; 3204 else 3205 I->second = false; 3206 } 3207 3208 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 3209 std::vector<const Decl *> DeferredDecls; 3210 for (const auto I : DeferredEmptyCoverageMappingDecls) { 3211 if (!I.second) 3212 continue; 3213 DeferredDecls.push_back(I.first); 3214 } 3215 // Sort the declarations by their location to make sure that the tests get a 3216 // predictable order for the coverage mapping for the unused declarations. 3217 if (CodeGenOpts.DumpCoverageMapping) 3218 std::sort(DeferredDecls.begin(), DeferredDecls.end(), 3219 [] (const Decl *LHS, const Decl *RHS) { 3220 return LHS->getLocStart() < RHS->getLocStart(); 3221 }); 3222 for (const auto *D : DeferredDecls) { 3223 switch (D->getKind()) { 3224 case Decl::CXXConversion: 3225 case Decl::CXXMethod: 3226 case Decl::Function: 3227 case Decl::ObjCMethod: { 3228 CodeGenPGO PGO(*this); 3229 GlobalDecl GD(cast<FunctionDecl>(D)); 3230 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 3231 getFunctionLinkage(GD)); 3232 break; 3233 } 3234 case Decl::CXXConstructor: { 3235 CodeGenPGO PGO(*this); 3236 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 3237 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 3238 getFunctionLinkage(GD)); 3239 break; 3240 } 3241 case Decl::CXXDestructor: { 3242 CodeGenPGO PGO(*this); 3243 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 3244 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 3245 getFunctionLinkage(GD)); 3246 break; 3247 } 3248 default: 3249 break; 3250 }; 3251 } 3252 } 3253 3254 /// Turns the given pointer into a constant. 3255 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 3256 const void *Ptr) { 3257 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 3258 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 3259 return llvm::ConstantInt::get(i64, PtrInt); 3260 } 3261 3262 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 3263 llvm::NamedMDNode *&GlobalMetadata, 3264 GlobalDecl D, 3265 llvm::GlobalValue *Addr) { 3266 if (!GlobalMetadata) 3267 GlobalMetadata = 3268 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 3269 3270 // TODO: should we report variant information for ctors/dtors? 3271 llvm::Value *Ops[] = { 3272 Addr, 3273 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 3274 }; 3275 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 3276 } 3277 3278 /// For each function which is declared within an extern "C" region and marked 3279 /// as 'used', but has internal linkage, create an alias from the unmangled 3280 /// name to the mangled name if possible. People expect to be able to refer 3281 /// to such functions with an unmangled name from inline assembly within the 3282 /// same translation unit. 3283 void CodeGenModule::EmitStaticExternCAliases() { 3284 for (StaticExternCMap::iterator I = StaticExternCValues.begin(), 3285 E = StaticExternCValues.end(); 3286 I != E; ++I) { 3287 IdentifierInfo *Name = I->first; 3288 llvm::GlobalValue *Val = I->second; 3289 if (Val && !getModule().getNamedValue(Name->getName())) 3290 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 3291 } 3292 } 3293 3294 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 3295 GlobalDecl &Result) const { 3296 auto Res = Manglings.find(MangledName); 3297 if (Res == Manglings.end()) 3298 return false; 3299 Result = Res->getValue(); 3300 return true; 3301 } 3302 3303 /// Emits metadata nodes associating all the global values in the 3304 /// current module with the Decls they came from. This is useful for 3305 /// projects using IR gen as a subroutine. 3306 /// 3307 /// Since there's currently no way to associate an MDNode directly 3308 /// with an llvm::GlobalValue, we create a global named metadata 3309 /// with the name 'clang.global.decl.ptrs'. 3310 void CodeGenModule::EmitDeclMetadata() { 3311 llvm::NamedMDNode *GlobalMetadata = nullptr; 3312 3313 // StaticLocalDeclMap 3314 for (auto &I : MangledDeclNames) { 3315 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 3316 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 3317 } 3318 } 3319 3320 /// Emits metadata nodes for all the local variables in the current 3321 /// function. 3322 void CodeGenFunction::EmitDeclMetadata() { 3323 if (LocalDeclMap.empty()) return; 3324 3325 llvm::LLVMContext &Context = getLLVMContext(); 3326 3327 // Find the unique metadata ID for this name. 3328 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 3329 3330 llvm::NamedMDNode *GlobalMetadata = nullptr; 3331 3332 for (auto &I : LocalDeclMap) { 3333 const Decl *D = I.first; 3334 llvm::Value *Addr = I.second; 3335 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 3336 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 3337 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 3338 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3339 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3340 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3341 } 3342 } 3343 } 3344 3345 void CodeGenModule::EmitVersionIdentMetadata() { 3346 llvm::NamedMDNode *IdentMetadata = 3347 TheModule.getOrInsertNamedMetadata("llvm.ident"); 3348 std::string Version = getClangFullVersion(); 3349 llvm::LLVMContext &Ctx = TheModule.getContext(); 3350 3351 llvm::Value *IdentNode[] = { 3352 llvm::MDString::get(Ctx, Version) 3353 }; 3354 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 3355 } 3356 3357 void CodeGenModule::EmitTargetMetadata() { 3358 // Warning, new MangledDeclNames may be appended within this loop. 3359 // We rely on MapVector insertions adding new elements to the end 3360 // of the container. 3361 // FIXME: Move this loop into the one target that needs it, and only 3362 // loop over those declarations for which we couldn't emit the target 3363 // metadata when we emitted the declaration. 3364 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 3365 auto Val = *(MangledDeclNames.begin() + I); 3366 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 3367 llvm::GlobalValue *GV = GetGlobalValue(Val.second); 3368 getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 3369 } 3370 } 3371 3372 void CodeGenModule::EmitCoverageFile() { 3373 if (!getCodeGenOpts().CoverageFile.empty()) { 3374 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3375 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3376 llvm::LLVMContext &Ctx = TheModule.getContext(); 3377 llvm::MDString *CoverageFile = 3378 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3379 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3380 llvm::MDNode *CU = CUNode->getOperand(i); 3381 llvm::Value *node[] = { CoverageFile, CU }; 3382 llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 3383 GCov->addOperand(N); 3384 } 3385 } 3386 } 3387 } 3388 3389 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 3390 // Sema has checked that all uuid strings are of the form 3391 // "12345678-1234-1234-1234-1234567890ab". 3392 assert(Uuid.size() == 36); 3393 for (unsigned i = 0; i < 36; ++i) { 3394 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 3395 else assert(isHexDigit(Uuid[i])); 3396 } 3397 3398 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 3399 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 3400 3401 llvm::Constant *Field3[8]; 3402 for (unsigned Idx = 0; Idx < 8; ++Idx) 3403 Field3[Idx] = llvm::ConstantInt::get( 3404 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 3405 3406 llvm::Constant *Fields[4] = { 3407 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 3408 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 3409 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 3410 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 3411 }; 3412 3413 return llvm::ConstantStruct::getAnon(Fields); 3414 } 3415 3416 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 3417 bool ForEH) { 3418 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 3419 // FIXME: should we even be calling this method if RTTI is disabled 3420 // and it's not for EH? 3421 if (!ForEH && !getLangOpts().RTTI) 3422 return llvm::Constant::getNullValue(Int8PtrTy); 3423 3424 if (ForEH && Ty->isObjCObjectPointerType() && 3425 LangOpts.ObjCRuntime.isGNUFamily()) 3426 return ObjCRuntime->GetEHType(Ty); 3427 3428 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 3429 } 3430 3431