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