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