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