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