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