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