blob: b0e08a2c6591f265b5afeaf4b45179406cfc6f7e [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCall.h"
18#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000019#include "CGObjCRuntime.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000020#include "CGOpenCLRuntime.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "CodeGenFunction.h"
Justin Bogneref512b92014-01-06 22:27:43 +000023#include "CodeGenPGO.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000024#include "CodeGenTBAA.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000025#include "TargetInfo.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000026#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000027#include "clang/AST/CharUnits.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000028#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/AST/DeclObjC.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000030#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000031#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000032#include "clang/AST/RecordLayout.h"
Rafael Espindolac5941352011-10-26 20:41:06 +000033#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindola4fdc1752011-12-19 14:41:01 +000034#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000035#include "clang/Basic/CharInfo.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000036#include "clang/Basic/Diagnostic.h"
Douglas Gregor6ddfca92013-01-14 17:21:00 +000037#include "clang/Basic/Module.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000038#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000039#include "clang/Basic/TargetInfo.h"
Rafael Espindola3bfa4682013-10-16 19:28:50 +000040#include "clang/Basic/Version.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "clang/Frontend/CodeGenOptions.h"
Rafael Espindola208b5c02013-10-22 19:26:13 +000042#include "clang/Sema/SemaDiagnostic.h"
Sebastian Redl4a7eab22012-02-25 20:51:20 +000043#include "llvm/ADT/APSInt.h"
John McCallbeec5a02010-03-06 00:35:14 +000044#include "llvm/ADT/Triple.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000045#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000046#include "llvm/IR/CallingConv.h"
47#include "llvm/IR/DataLayout.h"
48#include "llvm/IR/Intrinsics.h"
49#include "llvm/IR/LLVMContext.h"
50#include "llvm/IR/Module.h"
Justin Bogner837a6f62014-04-18 21:52:00 +000051#include "llvm/ProfileData/InstrProfReader.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000052#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000053#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000054
Chris Lattnerbed31442007-05-28 01:07:47 +000055using namespace clang;
56using namespace CodeGen;
57
Julien Lerouge5a6b6982011-09-09 22:41:49 +000058static const char AnnotationSection[] = "llvm.metadata";
59
Alp Toker82862252013-12-28 21:58:40 +000060static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000061 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000062 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000063 case TargetCXXABI::GenericARM:
64 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000065 case TargetCXXABI::iOS64:
John McCall57625922013-01-25 23:36:14 +000066 case TargetCXXABI::GenericItanium:
Alp Toker82862252013-12-28 21:58:40 +000067 return CreateItaniumCXXABI(CGM);
John McCall57625922013-01-25 23:36:14 +000068 case TargetCXXABI::Microsoft:
Alp Toker82862252013-12-28 21:58:40 +000069 return CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000070 }
71
72 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000073}
74
Chandler Carruthbc55fe22009-11-12 17:24:48 +000075CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall568d4102013-04-16 22:48:20 +000076 llvm::Module &M, const llvm::DataLayout &TD,
David Blaikie9c902b52011-09-25 23:23:43 +000077 DiagnosticsEngine &diags)
Alexey Samsonovd6e043b2013-08-12 11:48:05 +000078 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
79 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
Craig Topper8a13c412014-05-21 05:09:00 +000080 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(nullptr),
81 TheTargetCodeGenInfo(nullptr), Types(*this), VTables(*this),
82 ObjCRuntime(nullptr), OpenCLRuntime(nullptr), OpenMPRuntime(nullptr),
83 CUDARuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr),
84 NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
85 CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
86 NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
87 NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
88 BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
89 GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
90 LifetimeEndFn(nullptr),
Alexey Samsonovd6e043b2013-08-12 11:48:05 +000091 SanitizerBlacklist(
92 llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)),
93 SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled
94 : LangOpts.Sanitize) {
Will Dietzf54319c2013-01-18 11:30:38 +000095
Chris Lattnerece04092012-02-07 00:39:47 +000096 // Initialize the type cache.
97 llvm::LLVMContext &LLVMContext = M.getContext();
98 VoidTy = llvm::Type::getVoidTy(LLVMContext);
99 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
100 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
101 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
102 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
103 FloatTy = llvm::Type::getFloatTy(LLVMContext);
104 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
105 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
106 PointerAlignInBytes =
107 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
108 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
109 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
110 Int8PtrTy = Int8Ty->getPointerTo(0);
111 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
112
John McCall882987f2013-02-28 19:01:20 +0000113 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
114
David Blaikiebbafb8a2012-03-11 07:00:24 +0000115 if (LangOpts.ObjC1)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000116 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000117 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000118 createOpenCLRuntime();
Alexey Bataev9959db52014-05-06 10:08:46 +0000119 if (LangOpts.OpenMP)
120 createOpenMPRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000121 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000122 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000123
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000124 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Will Dietzf54319c2013-01-18 11:30:38 +0000125 if (SanOpts.Thread ||
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000126 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
127 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
Alp Toker82862252013-12-28 21:58:40 +0000128 getCXXABI().getMangleContext());
Dan Gohman947c9af2010-10-14 23:06:10 +0000129
Nick Lewycky207bce32011-04-21 23:44:07 +0000130 // If debug info or coverage generation is enabled, create the CGDebugInfo
131 // object.
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000132 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000133 CodeGenOpts.EmitGcovArcs ||
Nick Lewycky207bce32011-04-21 23:44:07 +0000134 CodeGenOpts.EmitGcovNotes)
135 DebugInfo = new CGDebugInfo(*this);
John McCallad7c5c12011-02-08 08:22:06 +0000136
137 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000138
David Blaikiebbafb8a2012-03-11 07:00:24 +0000139 if (C.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +0000140 ARCData = new ARCEntrypoints();
141 RRData = new RREntrypoints();
Justin Bogneref512b92014-01-06 22:27:43 +0000142
Justin Bogner837a6f62014-04-18 21:52:00 +0000143 if (!CodeGenOpts.InstrProfileInput.empty()) {
144 if (llvm::error_code EC = llvm::IndexedInstrProfReader::create(
145 CodeGenOpts.InstrProfileInput, PGOReader)) {
146 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
147 "Could not read profile: %0");
148 getDiags().Report(DiagID) << EC.message();
149 }
150 }
Chris Lattnera087ff92008-03-01 08:45:05 +0000151}
152
153CodeGenModule::~CodeGenModule() {
Peter Collingbournee1d20992011-07-27 20:29:46 +0000154 delete ObjCRuntime;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000155 delete OpenCLRuntime;
Alexey Bataev9959db52014-05-06 10:08:46 +0000156 delete OpenMPRuntime;
Peter Collingbournefe883422011-10-06 18:29:37 +0000157 delete CUDARuntime;
Ted Kremenekc168e502011-10-08 05:28:26 +0000158 delete TheTargetCodeGenInfo;
Dan Gohmand19ee8a2010-10-15 18:04:46 +0000159 delete TBAA;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000160 delete DebugInfo;
John McCall31168b02011-06-15 23:02:42 +0000161 delete ARCData;
162 delete RRData;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000163}
164
David Chisnall481e3a82010-01-23 02:40:42 +0000165void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000166 // This is just isGNUFamily(), but we want to force implementors of
167 // new ABIs to decide how best to do this.
168 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000169 case ObjCRuntime::GNUstep:
170 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000171 case ObjCRuntime::ObjFW:
Peter Collingbournee1d20992011-07-27 20:29:46 +0000172 ObjCRuntime = CreateGNUObjCRuntime(*this);
John McCall5fb5df92012-06-20 06:18:46 +0000173 return;
174
175 case ObjCRuntime::FragileMacOSX:
176 case ObjCRuntime::MacOSX:
177 case ObjCRuntime::iOS:
Peter Collingbournee1d20992011-07-27 20:29:46 +0000178 ObjCRuntime = CreateMacObjCRuntime(*this);
John McCall5fb5df92012-06-20 06:18:46 +0000179 return;
180 }
181 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000182}
183
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000184void CodeGenModule::createOpenCLRuntime() {
185 OpenCLRuntime = new CGOpenCLRuntime(*this);
186}
187
Alexey Bataev9959db52014-05-06 10:08:46 +0000188void CodeGenModule::createOpenMPRuntime() {
189 OpenMPRuntime = new CGOpenMPRuntime(*this);
190}
191
Peter Collingbournefe883422011-10-06 18:29:37 +0000192void CodeGenModule::createCUDARuntime() {
193 CUDARuntime = CreateNVCUDARuntime(*this);
194}
195
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000196void CodeGenModule::applyReplacements() {
197 for (ReplacementsTy::iterator I = Replacements.begin(),
198 E = Replacements.end();
199 I != E; ++I) {
200 StringRef MangledName = I->first();
201 llvm::Constant *Replacement = I->second;
202 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
203 if (!Entry)
204 continue;
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000205 auto *OldF = cast<llvm::Function>(Entry);
206 auto *NewF = dyn_cast<llvm::Function>(Replacement);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000207 if (!NewF) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000208 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
Rafael Espindola0fcad882014-05-16 22:20:18 +0000209 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
Reid Klecknerb78257d2014-02-03 18:54:51 +0000210 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000211 auto *CE = cast<llvm::ConstantExpr>(Replacement);
Reid Klecknerb78257d2014-02-03 18:54:51 +0000212 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
213 CE->getOpcode() == llvm::Instruction::GetElementPtr);
214 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
215 }
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000216 }
217
218 // Replace old with new, but keep the old order.
219 OldF->replaceAllUsesWith(Replacement);
220 if (NewF) {
221 NewF->removeFromParent();
222 OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
223 }
224 OldF->eraseFromParent();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000225 }
226}
227
Rafael Espindola208b5c02013-10-22 19:26:13 +0000228void CodeGenModule::checkAliases() {
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000229 // Check if the constructed aliases are well formed. It is really unfortunate
230 // that we have to do this in CodeGen, but we only construct mangled names
231 // and aliases during codegen.
Rafael Espindola208b5c02013-10-22 19:26:13 +0000232 bool Error = false;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000233 DiagnosticsEngine &Diags = getDiags();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000234 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
235 E = Aliases.end(); I != E; ++I) {
236 const GlobalDecl &GD = *I;
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000237 const auto *D = cast<ValueDecl>(GD.getDecl());
Rafael Espindola208b5c02013-10-22 19:26:13 +0000238 const AliasAttr *AA = D->getAttr<AliasAttr>();
239 StringRef MangledName = getMangledName(GD);
240 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000241 auto *Alias = cast<llvm::GlobalAlias>(Entry);
Rafael Espindola0fcad882014-05-16 22:20:18 +0000242 llvm::GlobalValue *GV = Alias->getAliasee();
Rafael Espindolab2633b92014-05-16 19:35:48 +0000243 if (GV->isDeclaration()) {
Rafael Espindola93c7a652014-03-13 15:47:50 +0000244 Error = true;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000245 Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000246 }
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000247
Rafael Espindolab2633b92014-05-16 19:35:48 +0000248 llvm::GlobalObject *Aliasee = Alias->getAliasee();
Rafael Espindola502f65a2014-05-05 20:21:03 +0000249 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
250 StringRef AliasSection = SA->getName();
Rafael Espindolab2633b92014-05-16 19:35:48 +0000251 if (AliasSection != Aliasee->getSection())
Rafael Espindola502f65a2014-05-05 20:21:03 +0000252 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
253 << AliasSection;
254 }
Rafael Espindola208b5c02013-10-22 19:26:13 +0000255 }
256 if (!Error)
257 return;
258
259 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
260 E = Aliases.end(); I != E; ++I) {
261 const GlobalDecl &GD = *I;
262 StringRef MangledName = getMangledName(GD);
263 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000264 auto *Alias = cast<llvm::GlobalAlias>(Entry);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000265 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
266 Alias->eraseFromParent();
267 }
268}
269
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000270void CodeGenModule::clear() {
271 DeferredDeclsToEmit.clear();
272}
273
Ted Kremenek2c674f62008-08-05 18:50:11 +0000274void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000275 EmitDeferred();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000276 applyReplacements();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000277 checkAliases();
Eli Friedman5866fe32010-01-08 00:50:11 +0000278 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000279 EmitCXXGlobalDtorFunc();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000280 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000281 if (ObjCRuntime)
282 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000283 AddGlobalCtor(ObjCInitFunction);
Justin Bognerf2ea7752014-04-10 18:13:13 +0000284 if (getCodeGenOpts().ProfileInstrGenerate)
285 if (llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this))
286 AddGlobalCtor(PGOInit, 0);
Justin Bogner837a6f62014-04-18 21:52:00 +0000287 if (PGOReader && PGOStats.isOutOfDate())
Justin Bognere2ef2a02014-04-15 21:22:35 +0000288 getDiags().Report(diag::warn_profile_data_out_of_date)
289 << PGOStats.Visited << PGOStats.Missing << PGOStats.Mismatched;
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000290 EmitCtorList(GlobalCtors, "llvm.global_ctors");
291 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000292 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000293 EmitStaticExternCAliases();
Rafael Espindola060062a2014-03-06 22:15:10 +0000294 emitLLVMUsed();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000295
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000296 if (CodeGenOpts.Autolink &&
297 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000298 EmitModuleLinkOptions();
299 }
Manman Ren9691f7f2013-06-19 01:46:49 +0000300 if (CodeGenOpts.DwarfVersion)
301 // We actually want the latest version when there are conflicts.
302 // We can change from Warning to Latest if such mode is supported.
303 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
304 CodeGenOpts.DwarfVersion);
Manman Ren4b7f23d2013-11-22 19:42:45 +0000305 if (DebugInfo)
Adrian Prantl2dbdd202014-05-19 23:40:06 +0000306 // We support a single version in the linked module. The LLVM
307 // parser will drop debug info with a different version number
308 // (and warn about it, too).
309 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000310 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000311
John McCall0bdb1fd2010-09-16 06:16:50 +0000312 SimplifyPersonality();
313
John McCall09ae0322010-07-06 23:57:41 +0000314 if (getCodeGenOpts().EmitDeclMetadata)
315 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000316
317 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000318 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000319
320 if (DebugInfo)
321 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000322
323 EmitVersionIdentMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000324}
325
Devang Patel945b8ae2011-03-23 16:29:39 +0000326void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
327 // Make sure that this type is translated.
328 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000329}
330
Dan Gohman947c9af2010-10-14 23:06:10 +0000331llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
332 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000333 return nullptr;
Dan Gohman947c9af2010-10-14 23:06:10 +0000334 return TBAA->getTBAAInfo(QTy);
335}
336
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000337llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
338 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000339 return nullptr;
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000340 return TBAA->getTBAAInfoForVTablePtr();
341}
342
Dan Gohman22695fc2012-09-28 21:58:29 +0000343llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
344 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000345 return nullptr;
Dan Gohman22695fc2012-09-28 21:58:29 +0000346 return TBAA->getTBAAStructInfo(QTy);
347}
348
Manman Renc451e572013-04-04 21:53:22 +0000349llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
350 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000351 return nullptr;
Manman Renc451e572013-04-04 21:53:22 +0000352 return TBAA->getTBAAStructTypeInfo(QTy);
353}
354
355llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
356 llvm::MDNode *AccessN,
357 uint64_t O) {
358 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000359 return nullptr;
Manman Renc451e572013-04-04 21:53:22 +0000360 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
361}
362
Manman Ren4f755de2013-10-08 00:08:49 +0000363/// Decorate the instruction with a TBAA tag. For both scalar TBAA
364/// and struct-path aware TBAA, the tag has the same format:
365/// base type, access type and offset.
Manman Rene1ad74e2013-04-11 23:02:56 +0000366/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
Dan Gohman947c9af2010-10-14 23:06:10 +0000367void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
Manman Rene1ad74e2013-04-11 23:02:56 +0000368 llvm::MDNode *TBAAInfo,
369 bool ConvertTypeToTag) {
Manman Ren4f755de2013-10-08 00:08:49 +0000370 if (ConvertTypeToTag && TBAA)
Manman Rene1ad74e2013-04-11 23:02:56 +0000371 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
372 TBAA->getTBAAScalarTagInfo(TBAAInfo));
373 else
374 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
Dan Gohman947c9af2010-10-14 23:06:10 +0000375}
376
Alp Toker29cb66b2014-01-26 06:17:37 +0000377void CodeGenModule::Error(SourceLocation loc, StringRef message) {
378 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
379 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000380}
381
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000382/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000383/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000384void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000385 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000386 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000387 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000388 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
389 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000390}
Chris Lattner41af8182007-12-02 06:27:33 +0000391
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000392/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000393/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000394void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000395 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000396 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000397 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000398 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000399}
400
John McCall23c29fe2011-06-24 21:55:10 +0000401llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
402 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
403}
404
Mike Stump11289f42009-09-09 15:08:12 +0000405void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlssonc6a47892011-01-29 19:39:23 +0000406 const NamedDecl *D) const {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000407 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000408 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000409 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000410 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000411 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000412
John McCallc273f242010-10-30 11:50:40 +0000413 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000414 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000415 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
416 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000417}
418
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000419static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
420 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
421 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
422 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
423 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
424 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
425}
426
427static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
428 CodeGenOptions::TLSModel M) {
429 switch (M) {
430 case CodeGenOptions::GeneralDynamicTLSModel:
431 return llvm::GlobalVariable::GeneralDynamicTLSModel;
432 case CodeGenOptions::LocalDynamicTLSModel:
433 return llvm::GlobalVariable::LocalDynamicTLSModel;
434 case CodeGenOptions::InitialExecTLSModel:
435 return llvm::GlobalVariable::InitialExecTLSModel;
436 case CodeGenOptions::LocalExecTLSModel:
437 return llvm::GlobalVariable::LocalExecTLSModel;
438 }
439 llvm_unreachable("Invalid TLS model!");
440}
441
442void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
443 const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000444 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000445
446 llvm::GlobalVariable::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000447 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000448
449 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000450 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000451 TLM = GetLLVMTLSModel(Attr->getModel());
452 }
453
454 GV->setThreadLocalMode(TLM);
455}
456
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000457StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000458 const auto *ND = cast<NamedDecl>(GD.getDecl());
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000459
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000460 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000461 if (!Str.empty())
462 return Str;
463
John McCall5d865c322010-08-31 07:33:07 +0000464 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000465 IdentifierInfo *II = ND->getIdentifier();
466 assert(II && "Attempt to mangle unnamed decl.");
467
468 Str = II->getName();
469 return Str;
470 }
471
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000472 SmallString<256> Buffer;
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000473 llvm::raw_svector_ostream Out(Buffer);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000474 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000475 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000476 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000477 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000478 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000479 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000480
481 // Allocate space for the mangled name.
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000482 Out.flush();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000483 size_t Length = Buffer.size();
484 char *Name = MangledNamesAllocator.Allocate<char>(Length);
485 std::copy(Buffer.begin(), Buffer.end(), Name);
486
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000487 Str = StringRef(Name, Length);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000488
489 return Str;
490}
491
Alp Toker0e64e0d2014-06-03 02:13:57 +0000492std::string CodeGenModule::getBlockMangledName(GlobalDecl GD,
493 const BlockDecl *BD) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000494 MangleContext &MangleCtx = getCXXABI().getMangleContext();
495 const Decl *D = GD.getDecl();
Alp Toker0e64e0d2014-06-03 02:13:57 +0000496
497 std::string Buffer;
498 llvm::raw_string_ostream Out(Buffer);
Craig Topper8a13c412014-05-21 05:09:00 +0000499 if (!D)
Fariborz Jahanian63628032012-06-26 16:06:38 +0000500 MangleCtx.mangleGlobalBlock(BD,
501 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000502 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000503 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000504 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000505 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000506 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000507 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Alp Toker0e64e0d2014-06-03 02:13:57 +0000508
509 return Out.str();
Anders Carlsson635186a2010-06-09 02:36:32 +0000510}
511
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000512llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +0000513 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000514}
515
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000516/// AddGlobalCtor - Add a function to the list that will be called before
517/// main() runs.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000518void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
519 llvm::Constant *AssociatedData) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000520 // FIXME: Type coercion of void()* types.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000521 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000522}
523
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000524/// AddGlobalDtor - Add a function to the list that will be called
525/// when the module is unloaded.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000526void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000527 // FIXME: Type coercion of void()* types.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000528 GlobalDtors.push_back(Structor(Priority, Dtor, 0));
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000529}
530
531void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
532 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +0000533 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000534 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000535
Reid Kleckner563f0e82014-05-23 21:13:45 +0000536 // Get the type of a ctor entry, { i32, void ()*, i8* }.
537 llvm::StructType *CtorStructTy = llvm::StructType::get(
538 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, NULL);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000539
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000540 // Construct the constructor and destructor arrays.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000541 SmallVector<llvm::Constant*, 8> Ctors;
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000542 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
Chris Lattner3def9ae2012-02-06 22:16:34 +0000543 llvm::Constant *S[] = {
Reid Kleckner563f0e82014-05-23 21:13:45 +0000544 llvm::ConstantInt::get(Int32Ty, I->Priority, false),
545 llvm::ConstantExpr::getBitCast(I->Initializer, CtorPFTy),
546 (I->AssociatedData
547 ? llvm::ConstantExpr::getBitCast(I->AssociatedData, VoidPtrTy)
548 : llvm::Constant::getNullValue(VoidPtrTy))
Chris Lattner3def9ae2012-02-06 22:16:34 +0000549 };
Owen Anderson0e0189d2009-07-27 22:29:56 +0000550 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000551 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000552
553 if (!Ctors.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000554 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Andersonc10c8d32009-07-08 19:05:04 +0000555 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000556 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000557 llvm::ConstantArray::get(AT, Ctors),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000558 GlobalName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000559 }
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000560}
561
John McCalld4324142010-02-19 01:32:20 +0000562llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000563CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000564 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +0000565
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000566 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +0000567
Hans Wennborg275efb92014-05-28 01:52:23 +0000568 if (isa<CXXDestructorDecl>(D) &&
Reid Klecknera12cd282013-12-11 19:21:27 +0000569 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
Hans Wennborg275efb92014-05-28 01:52:23 +0000570 GD.getDtorType())) {
571 // Destructor variants in the Microsoft C++ ABI are always internal or
572 // linkonce_odr thunks emitted on an as-needed basis.
573 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
574 : llvm::GlobalValue::LinkOnceODRLinkage;
575 }
Reid Klecknera12cd282013-12-11 19:21:27 +0000576
Hans Wennborg275efb92014-05-28 01:52:23 +0000577 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld4324142010-02-19 01:32:20 +0000578}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000579
Rafael Espindolae033c8c2014-05-08 15:26:12 +0000580void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
581 llvm::Function *F) {
582 setNonAliasAttributes(D, F);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000583}
584
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000585void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000586 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000587 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000588 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +0000589 AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +0000590 ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
Bill Wendling3087d022012-12-07 23:17:26 +0000591 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000592 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000593}
594
John McCall9b0a7ce2011-10-02 01:16:38 +0000595/// Determines whether the language options require us to model
596/// unwind exceptions. We treat -fexceptions as mandating this
597/// except under the fragile ObjC ABI with only ObjC exceptions
598/// enabled. This means, for example, that C with -fexceptions
599/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000600static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +0000601 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000602 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +0000603
604 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000605 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +0000606
607 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000608 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +0000609 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +0000610 }
611
612 return true;
613}
614
Daniel Dunbar38932572009-04-14 08:05:55 +0000615void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
616 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000617 llvm::AttrBuilder B;
618
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000619 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000620 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000621
David Blaikiebbafb8a2012-03-11 07:00:24 +0000622 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000623 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000624
Eli Friedmanc55efe42011-08-22 23:55:33 +0000625 if (D->hasAttr<NakedAttr>()) {
626 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000627 B.addAttribute(llvm::Attribute::Naked);
628 B.addAttribute(llvm::Attribute::NoInline);
Paul Robinsonf0674352014-03-31 22:29:15 +0000629 } else if (D->hasAttr<OptimizeNoneAttr>()) {
630 // OptimizeNone implies noinline; we should not be inlining such functions.
631 B.addAttribute(llvm::Attribute::OptimizeNone);
632 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +0000633 } else if (D->hasAttr<NoDuplicateAttr>()) {
634 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000635 } else if (D->hasAttr<NoInlineAttr>()) {
636 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +0000637 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000638 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
639 llvm::Attribute::NoInline)) {
640 // (noinline wins over always_inline, and we can't specify both in IR)
641 B.addAttribute(llvm::Attribute::AlwaysInline);
Eli Friedmanc55efe42011-08-22 23:55:33 +0000642 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +0000643
Diego Novillo5f2b1ce2013-05-24 20:18:15 +0000644 if (D->hasAttr<ColdAttr>()) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000645 B.addAttribute(llvm::Attribute::OptimizeForSize);
Diego Novillo5f2b1ce2013-05-24 20:18:15 +0000646 B.addAttribute(llvm::Attribute::Cold);
647 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +0000648
Quentin Colombet4e172062012-11-01 23:55:47 +0000649 if (D->hasAttr<MinSizeAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000650 B.addAttribute(llvm::Attribute::MinSize);
Richard Smithb555a762012-09-28 22:46:07 +0000651
Paul Robinsonf0674352014-03-31 22:29:15 +0000652 if (D->hasAttr<OptimizeNoneAttr>()) {
653 // OptimizeNone wins over OptimizeForSize and MinSize.
654 B.removeAttribute(llvm::Attribute::OptimizeForSize);
655 B.removeAttribute(llvm::Attribute::MinSize);
656 }
657
David Blaikiebbafb8a2012-03-11 07:00:24 +0000658 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000659 B.addAttribute(llvm::Attribute::StackProtect);
Josh Mageee0fc1a82014-02-11 01:35:14 +0000660 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
661 B.addAttribute(llvm::Attribute::StackProtectStrong);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000662 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000663 B.addAttribute(llvm::Attribute::StackProtectReq);
Will Dietzf54319c2013-01-18 11:30:38 +0000664
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000665 // Add sanitizer attributes if function is not blacklisted.
Alexey Samsonovd6e043b2013-08-12 11:48:05 +0000666 if (!SanitizerBlacklist->isIn(*F)) {
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000667 // When AddressSanitizer is enabled, set SanitizeAddress attribute
668 // unless __attribute__((no_sanitize_address)) is used.
669 if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000670 B.addAttribute(llvm::Attribute::SanitizeAddress);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000671 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
672 if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000673 B.addAttribute(llvm::Attribute::SanitizeThread);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000674 }
675 // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
676 if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000677 B.addAttribute(llvm::Attribute::SanitizeMemory);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000678 }
Alexander Potapenkoef41fd32012-02-02 11:49:28 +0000679
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000680 F->addAttributes(llvm::AttributeSet::FunctionIndex,
681 llvm::AttributeSet::get(
682 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
683
684 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
685 F->setUnnamedAddr(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000686 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000687 if (MD->isVirtual())
688 F->setUnnamedAddr(true);
689
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000690 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
691 if (alignment)
692 F->setAlignment(alignment);
693
Mike Stump3472ae52009-10-05 22:49:20 +0000694 // C++ ABI requires 2-byte alignment for member functions.
Mike Stump916c0062009-10-05 23:08:21 +0000695 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
696 F->setAlignment(2);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000697}
698
Mike Stump11289f42009-09-09 15:08:12 +0000699void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +0000700 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000701 if (const auto *ND = dyn_cast<NamedDecl>(D))
Anders Carlsson072ef742011-01-29 19:41:00 +0000702 setGlobalVisibility(GV, ND);
John McCall457a04e2010-10-22 21:05:15 +0000703 else
704 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +0000705
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000706 if (D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000707 addUsedGlobal(GV);
Rafael Espindola502f65a2014-05-05 20:21:03 +0000708}
709
710void CodeGenModule::setNonAliasAttributes(const Decl *D,
Rafael Espindolaee076a22014-05-13 18:45:53 +0000711 llvm::GlobalObject *GO) {
712 SetCommonAttributes(D, GO);
Daniel Dunbar38932572009-04-14 08:05:55 +0000713
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000714 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Rafael Espindolaee076a22014-05-13 18:45:53 +0000715 GO->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000716
Rafael Espindolaee076a22014-05-13 18:45:53 +0000717 getTargetCodeGenInfo().SetTargetAttributes(D, GO, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +0000718}
719
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000720void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
721 llvm::Function *F,
722 const CGFunctionInfo &FI) {
723 SetLLVMFunctionAttributes(D, FI, F);
724 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +0000725
726 F->setLinkage(llvm::Function::InternalLinkage);
727
Rafael Espindola502f65a2014-05-05 20:21:03 +0000728 setNonAliasAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000729}
730
David Majnemerf6acb762014-04-25 17:07:16 +0000731static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
732 const NamedDecl *ND) {
733 // Set linkage and visibility in case we never see a definition.
734 LinkageInfo LV = ND->getLinkageAndVisibility();
735 if (LV.getLinkage() != ExternalLinkage) {
736 // Don't set internal linkage on declarations.
737 } else {
738 if (ND->hasAttr<DLLImportAttr>()) {
739 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
740 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
741 } else if (ND->hasAttr<DLLExportAttr>()) {
742 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
743 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
744 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
745 // "extern_weak" is overloaded in LLVM; we probably should have
746 // separate linkage types for this.
747 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
748 }
749
750 // Set visibility on a declaration only if it's explicit.
751 if (LV.isVisibilityExplicit())
752 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
753 }
754}
755
Anders Carlsson6710c532010-02-06 02:44:09 +0000756void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedman895771a2009-05-26 01:22:57 +0000757 llvm::Function *F,
758 bool IsIncompleteFunction) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +0000759 if (unsigned IID = F->getIntrinsicID()) {
760 // If this is an intrinsic function, set the function's attributes
761 // to the intrinsic's attributes.
Bill Wendling311c8322012-10-15 04:47:45 +0000762 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
763 (llvm::Intrinsic::ID)IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +0000764 return;
765 }
766
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000767 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlsson6710c532010-02-06 02:44:09 +0000768
Eli Friedman895771a2009-05-26 01:22:57 +0000769 if (!IsIncompleteFunction)
John McCalla729c622012-02-17 03:33:10 +0000770 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +0000771
Bob Wilsonfc6297f2014-04-01 01:38:16 +0000772 // Add the Returned attribute for "this", except for iOS 5 and earlier
773 // where substantial code, including the libstdc++ dylib, was compiled with
774 // GCC and does not actually return "this".
775 if (getCXXABI().HasThisReturn(GD) &&
776 !(getTarget().getTriple().isiOS() &&
777 getTarget().getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000778 assert(!F->arg_empty() &&
779 F->arg_begin()->getType()
780 ->canLosslesslyBitCastTo(F->getReturnType()) &&
781 "unexpected this return");
782 F->addAttribute(1, llvm::Attribute::Returned);
783 }
784
Daniel Dunbar38932572009-04-14 08:05:55 +0000785 // Only a few attributes are set on declarations; these may later be
786 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +0000787
David Majnemerf6acb762014-04-25 17:07:16 +0000788 setLinkageAndVisibilityForGV(F, FD);
Daniel Dunbar38932572009-04-14 08:05:55 +0000789
Hans Wennborg275efb92014-05-28 01:52:23 +0000790 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
791 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
792 // Don't dllexport/import destructor thunks.
793 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
794 }
795 }
796
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000797 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000798 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +0000799
800 // A replaceable global allocation function does not act like a builtin by
801 // default, only if it is invoked by a new-expression or delete-expression.
802 if (FD->isReplaceableGlobalAllocationFunction())
803 F->addAttribute(llvm::AttributeSet::FunctionIndex,
804 llvm::Attribute::NoBuiltin);
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000805}
806
Rafael Espindola060062a2014-03-06 22:15:10 +0000807void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +0000808 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000809 "Only globals with definition can force usage.");
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000810 LLVMUsed.push_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000811}
812
Rafael Espindola060062a2014-03-06 22:15:10 +0000813void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
814 assert(!GV->isDeclaration() &&
815 "Only globals with definition can force usage.");
816 LLVMCompilerUsed.push_back(GV);
817}
818
819static void emitUsed(CodeGenModule &CGM, StringRef Name,
820 std::vector<llvm::WeakVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000821 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +0000822 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000823 return;
824
Rafael Espindola060062a2014-03-06 22:15:10 +0000825 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000826 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +0000827 UsedArray.resize(List.size());
828 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000829 UsedArray[i] =
Rafael Espindola060062a2014-03-06 22:15:10 +0000830 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]),
831 CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000832 }
Mike Stump11289f42009-09-09 15:08:12 +0000833
Fariborz Jahanian248c7192009-06-23 21:47:46 +0000834 if (UsedArray.empty())
835 return;
Rafael Espindola060062a2014-03-06 22:15:10 +0000836 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +0000837
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000838 auto *GV = new llvm::GlobalVariable(
839 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
840 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000841
842 GV->setSection("llvm.metadata");
843}
844
Rafael Espindola060062a2014-03-06 22:15:10 +0000845void CodeGenModule::emitLLVMUsed() {
846 emitUsed(*this, "llvm.used", LLVMUsed);
847 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
848}
849
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000850void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
851 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
852 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
853}
854
Aaron Ballman5d041be2013-06-04 02:07:14 +0000855void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
856 llvm::SmallString<32> Opt;
857 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
858 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
859 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
860}
861
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000862void CodeGenModule::AddDependentLib(StringRef Lib) {
863 llvm::SmallString<24> Opt;
864 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
865 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
866 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
867}
868
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000869/// \brief Add link options implied by the given module, including modules
870/// it depends on, using a postorder walk.
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000871static void addLinkOptionsPostorder(CodeGenModule &CGM,
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000872 Module *Mod,
Daniel Dunbar69e47462013-01-17 01:35:06 +0000873 SmallVectorImpl<llvm::Value *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000874 llvm::SmallPtrSet<Module *, 16> &Visited) {
875 // Import this module's parent.
876 if (Mod->Parent && Visited.insert(Mod->Parent)) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000877 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000878 }
879
880 // Import this module's dependencies.
881 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
882 if (Visited.insert(Mod->Imports[I-1]))
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000883 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000884 }
885
886 // Add linker options to link against the libraries/frameworks
887 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000888 llvm::LLVMContext &Context = CGM.getLLVMContext();
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000889 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000890 // Link against a framework. Frameworks are currently Darwin only, so we
891 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000892 if (Mod->LinkLibraries[I-1].IsFramework) {
893 llvm::Value *Args[2] = {
894 llvm::MDString::get(Context, "-framework"),
895 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
896 };
897
898 Metadata.push_back(llvm::MDNode::get(Context, Args));
899 continue;
900 }
901
902 // Link against a library.
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000903 llvm::SmallString<24> Opt;
904 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
905 Mod->LinkLibraries[I-1].Library, Opt);
906 llvm::Value *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000907 Metadata.push_back(llvm::MDNode::get(Context, OptString));
908 }
909}
910
911void CodeGenModule::EmitModuleLinkOptions() {
912 // Collect the set of all of the modules we want to visit to emit link
913 // options, which is essentially the imported modules and all of their
914 // non-explicit child modules.
915 llvm::SetVector<clang::Module *> LinkModules;
916 llvm::SmallPtrSet<clang::Module *, 16> Visited;
917 SmallVector<clang::Module *, 16> Stack;
918
919 // Seed the stack with imported modules.
920 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
921 MEnd = ImportedModules.end();
922 M != MEnd; ++M) {
923 if (Visited.insert(*M))
924 Stack.push_back(*M);
925 }
926
927 // Find all of the modules to import, making a little effort to prune
928 // non-leaf modules.
929 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000930 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000931
932 bool AnyChildren = false;
933
934 // Visit the submodules of this module.
935 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
936 SubEnd = Mod->submodule_end();
937 Sub != SubEnd; ++Sub) {
938 // Skip explicit children; they need to be explicitly imported to be
939 // linked against.
940 if ((*Sub)->IsExplicit)
941 continue;
942
943 if (Visited.insert(*Sub)) {
944 Stack.push_back(*Sub);
945 AnyChildren = true;
946 }
947 }
948
949 // We didn't find any children, so add this module to the list of
950 // modules to link against.
951 if (!AnyChildren) {
952 LinkModules.insert(Mod);
953 }
954 }
955
956 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000957 // order. We don't do anything to try to order import link flags with respect
958 // to linker options inserted by things like #pragma comment().
Daniel Dunbar69e47462013-01-17 01:35:06 +0000959 SmallVector<llvm::Value *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000960 Visited.clear();
961 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
962 MEnd = LinkModules.end();
963 M != MEnd; ++M) {
964 if (Visited.insert(*M))
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000965 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000966 }
Daniel Dunbar69e47462013-01-17 01:35:06 +0000967 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000968 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000969
Daniel Dunbar69e47462013-01-17 01:35:06 +0000970 // Add the linker options metadata flag.
971 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000972 llvm::MDNode::get(getLLVMContext(),
973 LinkerOptionsMetadata));
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000974}
975
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000976void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +0000977 // Emit code for any potentially referenced deferred decls. Since a
978 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +0000979 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000980
John McCall6bd2a892013-01-25 22:31:03 +0000981 while (true) {
Anders Carlsson11e51402010-04-17 20:15:18 +0000982 if (!DeferredVTables.empty()) {
John McCall6bd2a892013-01-25 22:31:03 +0000983 EmitDeferredVTables();
984
985 // Emitting a v-table doesn't directly cause more v-tables to
986 // become deferred, although it can cause functions to be
987 // emitted that then need those v-tables.
988 assert(DeferredVTables.empty());
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000989 }
990
John McCall6bd2a892013-01-25 22:31:03 +0000991 // Stop if we're out of both deferred v-tables and deferred declarations.
992 if (DeferredDeclsToEmit.empty()) break;
993
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000994 DeferredGlobal &G = DeferredDeclsToEmit.back();
995 GlobalDecl D = G.GD;
996 llvm::GlobalValue *GV = G.GV;
Chris Lattner45470942009-03-21 09:44:56 +0000997 DeferredDeclsToEmit.pop_back();
998
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000999 assert(GV == GetGlobalValue(getMangledName(D)));
John McCallc2af9392010-05-27 01:45:30 +00001000 // Check to see if we've already emitted this. This is necessary
1001 // for a couple of reasons: first, decls can end up in the
1002 // deferred-decls queue multiple times, and second, decls can end
1003 // up with definitions in unusual ways (e.g. by an extern inline
1004 // function acquiring a strong function redefinition). Just
1005 // ignore these cases.
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001006 if(!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00001007 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001008
Chris Lattner45470942009-03-21 09:44:56 +00001009 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001010 EmitGlobalDefinition(D, GV);
Chris Lattner45470942009-03-21 09:44:56 +00001011 }
Chris Lattnerbed31442007-05-28 01:07:47 +00001012}
Chris Lattner09153c02007-06-22 18:48:09 +00001013
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001014void CodeGenModule::EmitGlobalAnnotations() {
1015 if (Annotations.empty())
1016 return;
1017
1018 // Create a new global variable for the ConstantStruct in the Module.
1019 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1020 Annotations[0]->getType(), Annotations.size()), Annotations);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001021 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1022 llvm::GlobalValue::AppendingLinkage,
1023 Array, "llvm.global.annotations");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001024 gv->setSection(AnnotationSection);
1025}
1026
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001027llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001028 llvm::Constant *&AStr = AnnotationStrings[Str];
1029 if (AStr)
1030 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001031
1032 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001033 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001034 auto *gv =
1035 new llvm::GlobalVariable(getModule(), s->getType(), true,
1036 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001037 gv->setSection(AnnotationSection);
1038 gv->setUnnamedAddr(true);
Benjamin Kramereed80612013-11-10 16:55:11 +00001039 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001040 return gv;
1041}
1042
1043llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1044 SourceManager &SM = getContext().getSourceManager();
1045 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1046 if (PLoc.isValid())
1047 return EmitAnnotationString(PLoc.getFilename());
1048 return EmitAnnotationString(SM.getBufferName(Loc));
1049}
1050
1051llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1052 SourceManager &SM = getContext().getSourceManager();
1053 PresumedLoc PLoc = SM.getPresumedLoc(L);
1054 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1055 SM.getExpansionLineNumber(L);
1056 return llvm::ConstantInt::get(Int32Ty, LineNo);
1057}
1058
Mike Stump11289f42009-09-09 15:08:12 +00001059llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001060 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001061 SourceLocation L) {
1062 // Get the globals for file name, annotation, and the line number.
1063 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1064 *UnitGV = EmitAnnotationUnit(L),
1065 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001066
Daniel Dunbar346892a2009-04-14 22:41:13 +00001067 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001068 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001069 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1070 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1071 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1072 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001073 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001074 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001075}
1076
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001077void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1078 llvm::GlobalValue *GV) {
1079 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1080 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001081 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1082 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001083}
1084
Argyrios Kyrtzidisc0279a92010-07-27 22:37:14 +00001085bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001086 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001087 if (LangOpts.EmitAllDecls)
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001088 return false;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001089
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00001090 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001091}
1092
Nico Webercf4ff5862012-10-11 10:13:44 +00001093llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1094 const CXXUuidofExpr* E) {
1095 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1096 // well-formed.
David Majnemer8eaab6f2013-08-13 06:32:20 +00001097 StringRef Uuid = E->getUuidAsStringRef(Context);
David Majnemercf963ce2013-08-09 08:35:59 +00001098 std::string Name = "_GUID_" + Uuid.lower();
1099 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00001100
1101 // Look for an existing global.
1102 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1103 return GV;
1104
1105 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1106 assert(Init && "failed to initialize as constant");
1107
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001108 auto *GV = new llvm::GlobalVariable(
David Majnemerbbecd092013-08-15 19:59:14 +00001109 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00001110 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
Nico Webercf4ff5862012-10-11 10:13:44 +00001111 return GV;
1112}
1113
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001114llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1115 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1116 assert(AA && "No alias?");
1117
Chris Lattner2192fe52011-07-18 04:24:23 +00001118 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001119
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001120 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00001121 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001122 if (Entry) {
1123 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1124 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1125 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001126
1127 llvm::Constant *Aliasee;
1128 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00001129 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1130 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00001131 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001132 else
John McCall7ec50432010-03-19 23:29:14 +00001133 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00001134 llvm::PointerType::getUnqual(DeclTy),
1135 nullptr);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001136
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001137 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001138 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1139 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001140
1141 return Aliasee;
1142}
1143
Chris Lattnere0be0df2009-05-12 21:21:08 +00001144void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001145 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001146
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001147 // Weak references don't produce any output by themselves.
1148 if (Global->hasAttr<WeakRefAttr>())
1149 return;
1150
Chris Lattner54041692009-03-22 21:47:11 +00001151 // If this is an alias definition (which otherwise looks like a declaration)
1152 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001153 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00001154 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001155
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001156 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001157 if (LangOpts.CUDA) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001158 if (CodeGenOpts.CUDAIsDevice) {
1159 if (!Global->hasAttr<CUDADeviceAttr>() &&
1160 !Global->hasAttr<CUDAGlobalAttr>() &&
1161 !Global->hasAttr<CUDAConstantAttr>() &&
1162 !Global->hasAttr<CUDASharedAttr>())
1163 return;
1164 } else {
1165 if (!Global->hasAttr<CUDAHostAttr>() && (
1166 Global->hasAttr<CUDADeviceAttr>() ||
1167 Global->hasAttr<CUDAConstantAttr>() ||
1168 Global->hasAttr<CUDASharedAttr>()))
1169 return;
1170 }
1171 }
1172
Chris Lattner45470942009-03-21 09:44:56 +00001173 // Ignore declarations, they will be emitted on their first use.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001174 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001175 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001176 if (!FD->doesThisDeclarationHaveABody()) {
1177 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1178 return;
1179
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001180 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00001181
1182 // Compute the function info and LLVM type.
1183 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1184 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1185
1186 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1187 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001188 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001189 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001190 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001191 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001192 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1193
Douglas Gregor61f6db52010-02-06 05:15:45 +00001194 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorbeecd582009-04-21 17:11:58 +00001195 return;
Nate Begeman8e8d4982008-04-20 06:29:50 +00001196 }
1197
Chris Lattner45470942009-03-21 09:44:56 +00001198 // Defer code generation when possible if this is a static definition, inline
1199 // function etc. These we only want to emit if they are used.
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001200 if (!MayDeferGeneration(Global)) {
1201 // Emit the definition if it can't be deferred.
1202 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001203 return;
1204 }
John McCall70013b62010-07-15 23:40:35 +00001205
1206 // If we're deferring emission of a C++ variable with an
1207 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001208 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00001209 cast<VarDecl>(Global)->hasInit()) {
1210 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Craig Topper8a13c412014-05-21 05:09:00 +00001211 CXXGlobalInits.push_back(nullptr);
John McCall70013b62010-07-15 23:40:35 +00001212 }
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001213
1214 // If the value has already been used, add it directly to the
1215 // DeferredDeclsToEmit list.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001216 StringRef MangledName = getMangledName(GD);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001217 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName))
1218 addDeferredDeclToEmit(GV, GD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001219 else {
1220 // Otherwise, remember that we saw a deferred decl with this name. The
1221 // first use of the mangled name will cause it to move into
1222 // DeferredDeclsToEmit.
1223 DeferredDecls[MangledName] = GD;
1224 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00001225}
1226
Rafael Espindolac5941352011-10-26 20:41:06 +00001227namespace {
1228 struct FunctionIsDirectlyRecursive :
1229 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1230 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001231 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00001232 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001233 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1234 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001235 }
1236 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1237
1238 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001239 const FunctionDecl *FD = E->getDirectCallee();
1240 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00001241 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001242 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1243 if (Attr && Name == Attr->getLabel()) {
1244 Result = true;
1245 return false;
1246 }
1247 unsigned BuiltinID = FD->getBuiltinID();
1248 if (!BuiltinID)
Rafael Espindolac5941352011-10-26 20:41:06 +00001249 return true;
Nick Lewycky9ed5b152012-01-18 03:41:19 +00001250 StringRef BuiltinName = BI.GetName(BuiltinID);
1251 if (BuiltinName.startswith("__builtin_") &&
1252 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001253 Result = true;
1254 return false;
1255 }
1256 return true;
1257 }
1258 };
1259}
1260
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001261// isTriviallyRecursive - Check if this function calls another
1262// decl that, because of the asm attribute or the other decl being a builtin,
1263// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00001264bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001265CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1266 StringRef Name;
1267 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00001268 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001269 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1270 if (!Attr)
1271 return false;
1272 Name = Attr->getLabel();
1273 } else {
1274 Name = FD->getName();
1275 }
Rafael Espindolac5941352011-10-26 20:41:06 +00001276
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001277 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1278 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00001279 return Walker.Result;
1280}
1281
1282bool
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001283CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1284 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00001285 return true;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001286 const auto *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00001287 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00001288 return false;
1289 // PR9614. Avoid cases where the source code is lying to us. An available
1290 // externally function should have an equivalent function somewhere else,
1291 // but a function that calls itself is clearly not equivalent to the real
1292 // implementation.
1293 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001294 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00001295}
1296
Adrian Prantlffcf4ba2013-05-09 23:16:27 +00001297/// If the type for the method's class was generated by
1298/// CGDebugInfo::createContextChain(), the cache contains only a
1299/// limited DIType without any declarations. Since EmitFunctionStart()
1300/// needs to find the canonical declaration for each method, we need
1301/// to construct the complete type prior to emitting the method.
1302void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1303 if (!D->isInstance())
1304 return;
1305
1306 if (CGDebugInfo *DI = getModuleDebugInfo())
1307 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001308 const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
Adrian Prantlffcf4ba2013-05-09 23:16:27 +00001309 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1310 }
1311}
1312
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001313void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001314 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001315
Dan Gohman145f3f12010-04-19 16:39:44 +00001316 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00001317 Context.getSourceManager(),
1318 "Generating code for declaration");
1319
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001320 if (isa<FunctionDecl>(D)) {
Douglas Gregora700f682010-07-13 06:02:28 +00001321 // At -O0, don't generate IR for functions with available_externally
1322 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001323 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00001324 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00001325
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001326 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Adrian Prantlffcf4ba2013-05-09 23:16:27 +00001327 CompleteDIClassType(Method);
Eli Friedman49a94b12011-05-06 17:27:27 +00001328 // Make sure to emit the definition(s) before we emit the thunks.
1329 // This is necessary for the generation of certain thunks.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001330 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
Eli Friedman49a94b12011-05-06 17:27:27 +00001331 EmitCXXConstructor(CD, GD.getCtorType());
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001332 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
Eli Friedman49a94b12011-05-06 17:27:27 +00001333 EmitCXXDestructor(DD, GD.getDtorType());
1334 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001335 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00001336
Douglas Gregora700f682010-07-13 06:02:28 +00001337 if (Method->isVirtual())
1338 getVTables().EmitThunks(GD);
1339
Eli Friedman49a94b12011-05-06 17:27:27 +00001340 return;
Douglas Gregora700f682010-07-13 06:02:28 +00001341 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001342
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001343 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00001344 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001345
1346 if (const auto *VD = dyn_cast<VarDecl>(D))
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001347 return EmitGlobalVarDefinition(VD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001348
David Blaikie83d382b2011-09-23 05:06:16 +00001349 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00001350}
1351
Chris Lattnerd4808922009-03-22 21:03:39 +00001352/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1353/// module, create and return an llvm Function with the specified type. If there
1354/// is something in the module with the specified name, return it potentially
1355/// bitcasted to the right type.
1356///
1357/// If D is non-null, it specifies a decl that correspond to this. This is used
1358/// to set the attributes on the function when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001359llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001360CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00001361 llvm::Type *Ty,
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001362 GlobalDecl GD, bool ForVTable,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001363 bool DontDefer,
Bill Wendling8594fcb2013-01-31 00:30:05 +00001364 llvm::AttributeSet ExtraAttrs) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001365 const Decl *D = GD.getDecl();
1366
Chris Lattnera85d68e2009-03-21 09:25:43 +00001367 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001368 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001369 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00001370 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001371 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001372 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001373 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001374 }
1375
Chris Lattnera85d68e2009-03-21 09:25:43 +00001376 if (Entry->getType()->getElementType() == Ty)
1377 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001378
Chris Lattnera85d68e2009-03-21 09:25:43 +00001379 // Make sure the result is of the correct type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001380 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00001381 }
Mike Stump11289f42009-09-09 15:08:12 +00001382
Eli Friedmancc522d92009-11-09 05:07:37 +00001383 // This function doesn't have a complete type (for example, the return
1384 // type is an incomplete struct). Use a fake type instead, and make
1385 // sure not to try to set attributes.
1386 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00001387
Chris Lattner2192fe52011-07-18 04:24:23 +00001388 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00001389 if (isa<llvm::FunctionType>(Ty)) {
1390 FTy = cast<llvm::FunctionType>(Ty);
1391 } else {
John McCall9dc0db22011-05-15 01:53:33 +00001392 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00001393 IsIncompleteFunction = true;
1394 }
Chris Lattner5c740f12010-06-30 19:14:05 +00001395
John McCalld06fb862010-04-28 00:00:30 +00001396 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedmancc522d92009-11-09 05:07:37 +00001397 llvm::Function::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +00001398 MangledName, &getModule());
1399 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001400 if (D)
1401 SetFunctionAttributes(GD, F, IsIncompleteFunction);
Bill Wendling8594fcb2013-01-31 00:30:05 +00001402 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1403 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
Bill Wendling9a677922013-01-23 00:21:06 +00001404 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1405 llvm::AttributeSet::get(VMContext,
1406 llvm::AttributeSet::FunctionIndex,
1407 B));
1408 }
Eli Friedmancc522d92009-11-09 05:07:37 +00001409
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001410 if (!DontDefer) {
1411 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1412 // each other bottoming out with the base dtor. Therefore we emit non-base
1413 // dtors on usage, even if there is no dtor definition in the TU.
1414 if (D && isa<CXXDestructorDecl>(D) &&
1415 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1416 GD.getDtorType()))
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001417 addDeferredDeclToEmit(F, GD);
John McCall357d0f32010-12-15 04:00:32 +00001418
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001419 // This is the first use or definition of a mangled name. If there is a
1420 // deferred decl with this name, remember that we need to emit it at the end
1421 // of the file.
1422 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1423 if (DDI != DeferredDecls.end()) {
1424 // Move the potentially referenced deferred decl to the
1425 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1426 // don't need it anymore).
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001427 addDeferredDeclToEmit(F, DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001428 DeferredDecls.erase(DDI);
Richard Smithb47c36f2013-11-05 09:12:18 +00001429
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001430 // Otherwise, if this is a sized deallocation function, emit a weak
1431 // definition
1432 // for it at the end of the translation unit.
1433 } else if (D && cast<FunctionDecl>(D)
1434 ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001435 addDeferredDeclToEmit(F, GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001436
1437 // Otherwise, there are cases we have to worry about where we're
1438 // using a declaration for which we must emit a definition but where
1439 // we might not find a top-level definition:
1440 // - member functions defined inline in their classes
1441 // - friend functions defined inline in some class
1442 // - special member functions with implicit definitions
1443 // If we ever change our AST traversal to walk into class methods,
1444 // this will be unnecessary.
1445 //
1446 // We also don't emit a definition for a function if it's going to be an
1447 // entry
1448 // in a vtable, unless it's already marked as used.
1449 } else if (getLangOpts().CPlusPlus && D) {
1450 // Look for a declaration that's lexically in a record.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001451 const auto *FD = cast<FunctionDecl>(D);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001452 FD = FD->getMostRecentDecl();
1453 do {
1454 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1455 if (FD->isImplicit() && !ForVTable) {
1456 assert(FD->isUsed() &&
1457 "Sema didn't mark implicit function as used!");
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001458 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001459 break;
1460 } else if (FD->doesThisDeclarationHaveABody()) {
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001461 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001462 break;
1463 }
John McCall357d0f32010-12-15 04:00:32 +00001464 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001465 FD = FD->getPreviousDecl();
1466 } while (FD);
1467 }
Chris Lattner45470942009-03-21 09:44:56 +00001468 }
Mike Stump11289f42009-09-09 15:08:12 +00001469
Robert Lytton844aeeb2014-05-02 09:33:20 +00001470 getTargetCodeGenInfo().emitTargetMD(D, F, *this);
1471
John McCalld06fb862010-04-28 00:00:30 +00001472 // Make sure the result is of the requested type.
1473 if (!IsIncompleteFunction) {
1474 assert(F->getType()->getElementType() == Ty);
1475 return F;
1476 }
1477
Chris Lattnera5f58b02011-07-09 17:41:47 +00001478 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00001479 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001480}
1481
Chris Lattnerd4808922009-03-22 21:03:39 +00001482/// GetAddrOfFunction - Return the address of the given function. If Ty is
1483/// non-null, then this function will use the specified type if it has to
1484/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00001485llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00001486 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001487 bool ForVTable,
1488 bool DontDefer) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001489 // If there was no specific requested type, just convert it now.
1490 if (!Ty)
Anders Carlsson38988d72009-09-10 23:38:47 +00001491 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattner5c740f12010-06-30 19:14:05 +00001492
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001493 StringRef MangledName = getMangledName(GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001494 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
Chris Lattnerd4808922009-03-22 21:03:39 +00001495}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001496
Chris Lattnerd4808922009-03-22 21:03:39 +00001497/// CreateRuntimeFunction - Create a new runtime function with the specified
1498/// type and name.
1499llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001500CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001501 StringRef Name,
Bill Wendling8594fcb2013-01-31 00:30:05 +00001502 llvm::AttributeSet ExtraAttrs) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001503 llvm::Constant *C =
1504 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1505 /*DontDefer=*/false, ExtraAttrs);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001506 if (auto *F = dyn_cast<llvm::Function>(C))
John McCall882987f2013-02-28 19:01:20 +00001507 if (F->empty())
1508 F->setCallingConv(getRuntimeCC());
1509 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00001510}
Daniel Dunbar9c426522008-07-29 23:18:29 +00001511
Richard Smithe070fd22012-02-17 06:48:11 +00001512/// isTypeConstant - Determine whether an object of this type can be emitted
1513/// as a constant.
1514///
1515/// If ExcludeCtor is true, the duration when the object's constructor runs
1516/// will not be considered. The caller will need to verify that the object is
1517/// not written to during its construction.
1518bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1519 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00001520 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00001521
David Blaikiebbafb8a2012-03-11 07:00:24 +00001522 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00001523 if (const CXXRecordDecl *Record
1524 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1525 return ExcludeCtor && !Record->hasMutableFields() &&
1526 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00001527 }
Richard Smithe070fd22012-02-17 06:48:11 +00001528
Eli Friedmanb095e152009-12-11 21:23:03 +00001529 return true;
1530}
1531
David Majnemer01bbd1b2014-04-25 17:08:41 +00001532static bool isVarDeclInlineInitializedStaticDataMember(const VarDecl *VD) {
1533 if (!VD->isStaticDataMember())
1534 return false;
1535 const VarDecl *InitDecl;
1536 const Expr *InitExpr = VD->getAnyInitializer(InitDecl);
1537 if (!InitExpr)
1538 return false;
1539 if (InitDecl->isThisDeclarationADefinition())
1540 return false;
1541 return true;
1542}
1543
Chris Lattnerd4808922009-03-22 21:03:39 +00001544/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1545/// create and return an llvm GlobalVariable with the specified type. If there
1546/// is something in the module with the specified name, return it potentially
1547/// bitcasted to the right type.
1548///
1549/// If D is non-null, it specifies a decl that correspond to this. This is used
1550/// to set the attributes on the global when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001551llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001552CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00001553 llvm::PointerType *Ty,
Rafael Espindolab73c9732014-05-22 23:33:27 +00001554 const VarDecl *D) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00001555 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001556 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00001557 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00001558 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001559 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001560 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001561 }
1562
Chris Lattnerd4808922009-03-22 21:03:39 +00001563 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00001564 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001565
Chris Lattner3bfce182009-03-21 08:03:33 +00001566 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00001567 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1568 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1569
Owen Andersonade90fd2009-07-29 18:54:39 +00001570 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00001571 }
Mike Stump11289f42009-09-09 15:08:12 +00001572
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001573 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001574 auto *GV = new llvm::GlobalVariable(
1575 getModule(), Ty->getElementType(), false,
Craig Topper8a13c412014-05-21 05:09:00 +00001576 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001577 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001578
Chris Lattner45470942009-03-21 09:44:56 +00001579 // This is the first use or definition of a mangled name. If there is a
1580 // deferred decl with this name, remember that we need to emit it at the end
1581 // of the file.
John McCall7ec50432010-03-19 23:29:14 +00001582 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00001583 if (DDI != DeferredDecls.end()) {
1584 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1585 // list, and remove it from DeferredDecls (since we don't need it anymore).
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001586 addDeferredDeclToEmit(GV, DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00001587 DeferredDecls.erase(DDI);
1588 }
Mike Stump11289f42009-09-09 15:08:12 +00001589
Chris Lattner3bfce182009-03-21 08:03:33 +00001590 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00001591 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +00001592 // FIXME: This code is overly simple and should be merged with other global
1593 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00001594 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00001595
David Majnemerf6acb762014-04-25 17:07:16 +00001596 setLinkageAndVisibilityForGV(GV, D);
Eli Friedman4f856742009-04-19 21:05:03 +00001597
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001598 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00001599 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1600 CXXThreadLocals.push_back(std::make_pair(D, GV));
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001601 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001602 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00001603
1604 // If required by the ABI, treat declarations of static data members with
1605 // inline initializers as definitions.
1606 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
David Majnemer01bbd1b2014-04-25 17:08:41 +00001607 isVarDeclInlineInitializedStaticDataMember(D))
Hans Wennborgfeedf852013-11-21 00:15:56 +00001608 EmitGlobalVarDefinition(D);
Robert Lyttonf80d6882014-05-02 09:33:30 +00001609
1610 // Handle XCore specific ABI requirements.
1611 if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1612 D->getLanguageLinkage() == CLanguageLinkage &&
1613 D->getType().isConstant(Context) &&
1614 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1615 GV->setSection(".cp.rodata");
Chris Lattnerd4808922009-03-22 21:03:39 +00001616 }
Mike Stump11289f42009-09-09 15:08:12 +00001617
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001618 if (AddrSpace != Ty->getAddressSpace())
Matt Arsenault00e65b22013-11-15 02:19:52 +00001619 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1620
Robert Lytton844aeeb2014-05-02 09:33:20 +00001621 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
1622
Matt Arsenault00e65b22013-11-15 02:19:52 +00001623 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001624}
1625
Chris Lattnerd4808922009-03-22 21:03:39 +00001626
Anders Carlssonda80af32011-01-29 18:20:20 +00001627llvm::GlobalVariable *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001628CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2192fe52011-07-18 04:24:23 +00001629 llvm::Type *Ty,
Anders Carlssonda80af32011-01-29 18:20:20 +00001630 llvm::GlobalValue::LinkageTypes Linkage) {
1631 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Craig Topper8a13c412014-05-21 05:09:00 +00001632 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlssonda80af32011-01-29 18:20:20 +00001633
Anders Carlssonda80af32011-01-29 18:20:20 +00001634 if (GV) {
1635 // Check if the variable has the right type.
1636 if (GV->getType()->getElementType() == Ty)
1637 return GV;
1638
1639 // Because C++ name mangling, the only way we can end up with an already
1640 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00001641 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00001642 OldGV = GV;
1643 }
1644
1645 // Create a new variable.
1646 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Craig Topper8a13c412014-05-21 05:09:00 +00001647 Linkage, nullptr, Name);
1648
Anders Carlssonda80af32011-01-29 18:20:20 +00001649 if (OldGV) {
1650 // Replace occurrences of the old variable if needed.
1651 GV->takeName(OldGV);
1652
1653 if (!OldGV->use_empty()) {
1654 llvm::Constant *NewPtrForOldDecl =
1655 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1656 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1657 }
1658
1659 OldGV->eraseFromParent();
1660 }
1661
1662 return GV;
1663}
1664
Chris Lattnerd4808922009-03-22 21:03:39 +00001665/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1666/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00001667/// then it will be created with the specified type instead of whatever the
Chris Lattnerd4808922009-03-22 21:03:39 +00001668/// normal requested type would be.
1669llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2192fe52011-07-18 04:24:23 +00001670 llvm::Type *Ty) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001671 assert(D->hasGlobalStorage() && "Not a global variable");
1672 QualType ASTTy = D->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00001673 if (!Ty)
Chris Lattnerd4808922009-03-22 21:03:39 +00001674 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00001675
Chris Lattner2192fe52011-07-18 04:24:23 +00001676 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001677 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00001678
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001679 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001680 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001681}
1682
1683/// CreateRuntimeVariable - Create a new runtime global variable with the
1684/// specified type and name.
1685llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001686CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001687 StringRef Name) {
Rafael Espindolab73c9732014-05-22 23:33:27 +00001688 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
Chris Lattnerd4808922009-03-22 21:03:39 +00001689}
1690
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001691void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1692 assert(!D->getInit() && "Cannot emit definite definitions here!");
1693
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001694 if (MayDeferGeneration(D)) {
1695 // If we have not seen a reference to this variable yet, place it
1696 // into the deferred declarations table to be emitted if needed
1697 // later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001698 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001699 if (!GetGlobalValue(MangledName)) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001700 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001701 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001702 }
1703 }
1704
1705 // The tentative definition is the only definition.
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001706 EmitGlobalVarDefinition(D);
1707}
1708
Chris Lattner2192fe52011-07-18 04:24:23 +00001709CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck9a648692011-01-18 02:01:14 +00001710 return Context.toCharUnitsFromBits(
Micah Villmowdd31ca12012-10-08 16:25:52 +00001711 TheDataLayout.getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00001712}
1713
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001714unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1715 unsigned AddrSpace) {
1716 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1717 if (D->hasAttr<CUDAConstantAttr>())
1718 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1719 else if (D->hasAttr<CUDASharedAttr>())
1720 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1721 else
1722 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1723 }
1724
1725 return AddrSpace;
1726}
1727
Richard Smithdf931ce2013-04-06 05:00:46 +00001728template<typename SomeDecl>
1729void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1730 llvm::GlobalValue *GV) {
1731 if (!getLangOpts().CPlusPlus)
1732 return;
1733
1734 // Must have 'used' attribute, or else inline assembly can't rely on
1735 // the name existing.
1736 if (!D->template hasAttr<UsedAttr>())
1737 return;
1738
1739 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001740 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00001741 return;
1742
1743 // Must be in an extern "C" context. Entities declared directly within
1744 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001745 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00001746 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00001747 return;
1748
1749 // OK, this is an internal linkage entity inside an extern "C" linkage
1750 // specification. Make a note of that so we can give it the "expected"
1751 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00001752 std::pair<StaticExternCMap::iterator, bool> R =
1753 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00001754
1755 // If we have multiple internal linkage entities with the same name
1756 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00001757 if (!R.second)
Craig Topper8a13c412014-05-21 05:09:00 +00001758 R.first->second = nullptr;
Richard Smithdf931ce2013-04-06 05:00:46 +00001759}
1760
Daniel Dunbar9c426522008-07-29 23:18:29 +00001761void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Craig Topper8a13c412014-05-21 05:09:00 +00001762 llvm::Constant *Init = nullptr;
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001763 QualType ASTTy = D->getType();
Richard Smith6331c402012-02-13 22:16:19 +00001764 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1765 bool NeedsGlobalCtor = false;
1766 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00001767
Richard Smithdafff942012-01-14 04:30:29 +00001768 const VarDecl *InitDecl;
1769 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001770
Anders Carlssonca4a5452010-01-26 17:43:42 +00001771 if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00001772 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001773 // implicitly initialized with { 0 }.
1774 //
1775 // Note that tentative definitions are only emitted at the end of
1776 // a translation unit, so they should never have incomplete
1777 // type. In addition, EmitTentativeDefinition makes sure that we
1778 // never attempt to emit a tentative definition if a real one
1779 // exists. A use may still exists, however, so we still may need
1780 // to do a RAUW.
1781 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00001782 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001783 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00001784 initializedGlobalDecl = GlobalDecl(D);
1785 Init = EmitConstantInit(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001786
Fariborz Jahanian63628032012-06-26 16:06:38 +00001787 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00001788 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00001789 if (D->getType()->isReferenceType())
1790 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00001791
David Blaikiebbafb8a2012-03-11 07:00:24 +00001792 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001793 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00001794 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001795 } else {
1796 ErrorUnsupported(D, "static initializer");
1797 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1798 }
John McCall70013b62010-07-15 23:40:35 +00001799 } else {
1800 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00001801 // initializer position (just in case this entry was delayed) if we
1802 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001803 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00001804 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00001805 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001806 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001807
Chris Lattner2192fe52011-07-18 04:24:23 +00001808 llvm::Type* InitType = Init->getType();
Chris Lattner149927c2009-03-21 09:16:30 +00001809 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump11289f42009-09-09 15:08:12 +00001810
Chris Lattner149927c2009-03-21 09:16:30 +00001811 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001812 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00001813 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00001814 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
1815 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00001816 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00001817 Entry = CE->getOperand(0);
1818 }
Mike Stump11289f42009-09-09 15:08:12 +00001819
Chris Lattner149927c2009-03-21 09:16:30 +00001820 // Entry is now either a Function or GlobalVariable.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001821 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001822
Chris Lattner149927c2009-03-21 09:16:30 +00001823 // We have a definition after a declaration with the wrong type.
1824 // We must make a new GlobalVariable* and update everything that used OldGV
1825 // (a declaration or tentative definition) with the new GlobalVariable*
1826 // (which will be a definition).
1827 //
1828 // This happens if there is a prototype for a global (e.g.
1829 // "extern int x[];") and then a definition of a different type (e.g.
1830 // "int x[10];"). This also happens when an initializer has a different type
1831 // from the type of the global (this happens with unions).
Craig Topper8a13c412014-05-21 05:09:00 +00001832 if (!GV ||
Chris Lattner149927c2009-03-21 09:16:30 +00001833 GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001834 GV->getType()->getAddressSpace() !=
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001835 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump11289f42009-09-09 15:08:12 +00001836
John McCall7ec50432010-03-19 23:29:14 +00001837 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001838 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00001839
Chris Lattner149927c2009-03-21 09:16:30 +00001840 // Make a new global with the correct type, this is now guaranteed to work.
1841 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattnera85d68e2009-03-21 09:25:43 +00001842
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001843 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00001844 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001845 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00001846 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001847
1848 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00001849 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001850 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00001851
Richard Smithdf931ce2013-04-06 05:00:46 +00001852 MaybeHandleStaticInExternC(D, GV);
1853
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001854 if (D->hasAttr<AnnotateAttr>())
1855 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00001856
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001857 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001858
1859 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00001860 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1861 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00001862
Ken Dyck160146e2010-01-27 17:10:57 +00001863 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00001864
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001865 // Set the llvm linkage type as appropriate.
David Majnemer27d69db2014-04-28 22:17:59 +00001866 llvm::GlobalValue::LinkageTypes Linkage =
1867 getLLVMLinkageVarDefinition(D, GV->isConstant());
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001868 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00001869 if (D->hasAttr<DLLImportAttr>())
1870 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1871 else if (D->hasAttr<DLLExportAttr>())
1872 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00001873
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001874 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnerf49573d2009-08-05 05:20:29 +00001875 // common vars aren't constant even if declared const.
1876 GV->setConstant(false);
Daniel Dunbard272cca2009-04-10 20:26:50 +00001877
Rafael Espindola502f65a2014-05-05 20:21:03 +00001878 setNonAliasAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001879
John McCallcdf7ef52010-11-06 09:44:32 +00001880 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00001881 if (NeedsGlobalCtor || NeedsGlobalDtor)
1882 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00001883
Kostya Serebryany28a26c82012-08-21 06:53:28 +00001884 // If we are compiling with ASan, add metadata indicating dynamically
Alexey Samsonovc054d982014-05-29 01:43:53 +00001885 // initialized (and not blacklisted) globals.
1886 if (SanOpts.Address && NeedsGlobalCtor &&
1887 !SanitizerBlacklist->isIn(*GV, "init")) {
1888 llvm::NamedMDNode *DynamicInitializers = TheModule.getOrInsertNamedMetadata(
1889 "llvm.asan.dynamically_initialized_globals");
Kostya Serebryany28a26c82012-08-21 06:53:28 +00001890 llvm::Value *GlobalToAdd[] = { GV };
1891 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1892 DynamicInitializers->addOperand(ThisGlobal);
1893 }
1894
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001895 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00001896 if (CGDebugInfo *DI = getModuleDebugInfo())
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001897 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00001898 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001899}
Chris Lattner09153c02007-06-22 18:48:09 +00001900
David Majnemer9832a3d2014-04-10 16:53:16 +00001901static bool isVarDeclStrongDefinition(const VarDecl *D, bool NoCommon) {
1902 // Don't give variables common linkage if -fno-common was specified unless it
1903 // was overridden by a NoCommon attribute.
1904 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
1905 return true;
1906
1907 // C11 6.9.2/2:
1908 // A declaration of an identifier for an object that has file scope without
1909 // an initializer, and without a storage-class specifier or with the
1910 // storage-class specifier static, constitutes a tentative definition.
1911 if (D->getInit() || D->hasExternalStorage())
1912 return true;
1913
1914 // A variable cannot be both common and exist in a section.
1915 if (D->hasAttr<SectionAttr>())
1916 return true;
1917
1918 // Thread local vars aren't considered common linkage.
1919 if (D->getTLSKind())
1920 return true;
1921
1922 // Tentative definitions marked with WeakImportAttr are true definitions.
1923 if (D->hasAttr<WeakImportAttr>())
1924 return true;
1925
1926 return false;
1927}
1928
Hans Wennborg1a3a0742014-05-14 19:54:53 +00001929llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
Hans Wennborg275efb92014-05-28 01:52:23 +00001930 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001931 if (Linkage == GVA_Internal)
1932 return llvm::Function::InternalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00001933
1934 if (D->hasAttr<WeakAttr>()) {
1935 if (IsConstantVariable)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001936 return llvm::GlobalVariable::WeakODRLinkage;
1937 else
1938 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00001939 }
1940
1941 // We are guaranteed to have a strong definition somewhere else,
1942 // so we can use available_externally linkage.
1943 if (Linkage == GVA_AvailableExternally)
1944 return llvm::Function::AvailableExternallyLinkage;
1945
David Majnemer27d69db2014-04-28 22:17:59 +00001946 // Note that Apple's kernel linker doesn't support symbol
1947 // coalescing, so we need to avoid linkonce and weak linkages there.
1948 // Normally, this means we just map to internal, but for explicit
1949 // instantiations we'll map to external.
1950
1951 // In C++, the compiler has to emit a definition in every translation unit
1952 // that references the function. We should use linkonce_odr because
1953 // a) if all references in this translation unit are optimized away, we
1954 // don't need to codegen it. b) if the function persists, it needs to be
1955 // merged with other definitions. c) C++ has the ODR, so we know the
1956 // definition is dependable.
1957 if (Linkage == GVA_DiscardableODR)
Hans Wennborgb0f2f142014-05-15 22:07:49 +00001958 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
David Majnemer27d69db2014-04-28 22:17:59 +00001959 : llvm::Function::InternalLinkage;
1960
1961 // An explicit instantiation of a template has weak linkage, since
1962 // explicit instantiations can occur in multiple translation units
1963 // and must all be equivalent. However, we are not allowed to
1964 // throw away these explicit instantiations.
1965 if (Linkage == GVA_StrongODR)
1966 return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
1967 : llvm::Function::ExternalLinkage;
1968
David Majnemer27d69db2014-04-28 22:17:59 +00001969 // If required by the ABI, give definitions of static data members with inline
1970 // initializers at least linkonce_odr linkage.
Nico Rieckb4662c32014-05-29 16:50:46 +00001971 auto const VD = dyn_cast<VarDecl>(D);
David Majnemer27d69db2014-04-28 22:17:59 +00001972 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
Nico Rieckb4662c32014-05-29 16:50:46 +00001973 VD && isVarDeclInlineInitializedStaticDataMember(VD)) {
1974 if (VD->hasAttr<DLLImportAttr>())
1975 return llvm::GlobalValue::AvailableExternallyLinkage;
1976 if (VD->hasAttr<DLLExportAttr>())
1977 return llvm::GlobalValue::WeakODRLinkage;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00001978 return llvm::GlobalValue::LinkOnceODRLinkage;
Nico Rieckb4662c32014-05-29 16:50:46 +00001979 }
David Majnemer27d69db2014-04-28 22:17:59 +00001980
1981 // C++ doesn't have tentative definitions and thus cannot have common
1982 // linkage.
1983 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
1984 !isVarDeclStrongDefinition(cast<VarDecl>(D), CodeGenOpts.NoCommon))
David Majnemer9832a3d2014-04-10 16:53:16 +00001985 return llvm::GlobalVariable::CommonLinkage;
1986
David Majnemer27d69db2014-04-28 22:17:59 +00001987 // selectany symbols are externally visible, so use weak instead of
1988 // linkonce. MSVC optimizes away references to const selectany globals, so
1989 // all definitions should be the same and ODR linkage should be used.
1990 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
1991 if (D->hasAttr<SelectAnyAttr>())
1992 return llvm::GlobalVariable::WeakODRLinkage;
1993
1994 // Otherwise, we have strong external linkage.
1995 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001996 return llvm::GlobalVariable::ExternalLinkage;
1997}
1998
David Majnemer27d69db2014-04-28 22:17:59 +00001999llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2000 const VarDecl *VD, bool IsConstant) {
2001 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
Hans Wennborg275efb92014-05-28 01:52:23 +00002002 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
David Majnemer27d69db2014-04-28 22:17:59 +00002003}
2004
John McCall49954ca2012-12-12 22:21:47 +00002005/// Replace the uses of a function that was declared with a non-proto type.
2006/// We want to silently drop extra arguments from call sites
2007static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2008 llvm::Function *newFn) {
2009 // Fast path.
2010 if (old->use_empty()) return;
2011
2012 llvm::Type *newRetTy = newFn->getReturnType();
2013 SmallVector<llvm::Value*, 4> newArgs;
2014
2015 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2016 ui != ue; ) {
2017 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002018 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00002019
2020 // Recognize and replace uses of bitcasts. Most calls to
2021 // unprototyped functions will use bitcasts.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002022 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCall49954ca2012-12-12 22:21:47 +00002023 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2024 replaceUsesOfNonProtoConstant(bitcast, newFn);
2025 continue;
2026 }
2027
2028 // Recognize calls to the function.
2029 llvm::CallSite callSite(user);
2030 if (!callSite) continue;
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002031 if (!callSite.isCallee(&*use)) continue;
John McCall49954ca2012-12-12 22:21:47 +00002032
2033 // If the return types don't match exactly, then we can't
2034 // transform this call unless it's dead.
2035 if (callSite->getType() != newRetTy && !callSite->use_empty())
2036 continue;
2037
2038 // Get the call site's attribute list.
Bill Wendling290d9522013-01-27 02:46:53 +00002039 SmallVector<llvm::AttributeSet, 8> newAttrs;
John McCall49954ca2012-12-12 22:21:47 +00002040 llvm::AttributeSet oldAttrs = callSite.getAttributes();
2041
2042 // Collect any return attributes from the call.
Bill Wendling304f6f02013-01-21 21:57:40 +00002043 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
Bill Wendlingb7abb302013-01-21 22:45:00 +00002044 newAttrs.push_back(
Bill Wendling290d9522013-01-27 02:46:53 +00002045 llvm::AttributeSet::get(newFn->getContext(),
2046 oldAttrs.getRetAttributes()));
John McCall49954ca2012-12-12 22:21:47 +00002047
2048 // If the function was passed too few arguments, don't transform.
2049 unsigned newNumArgs = newFn->arg_size();
2050 if (callSite.arg_size() < newNumArgs) continue;
2051
2052 // If extra arguments were passed, we silently drop them.
2053 // If any of the types mismatch, we don't transform.
2054 unsigned argNo = 0;
2055 bool dontTransform = false;
2056 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2057 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2058 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2059 dontTransform = true;
2060 break;
2061 }
2062
2063 // Add any parameter attributes.
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002064 if (oldAttrs.hasAttributes(argNo + 1))
2065 newAttrs.
Bill Wendling290d9522013-01-27 02:46:53 +00002066 push_back(llvm::
2067 AttributeSet::get(newFn->getContext(),
2068 oldAttrs.getParamAttributes(argNo + 1)));
John McCall49954ca2012-12-12 22:21:47 +00002069 }
2070 if (dontTransform)
2071 continue;
2072
Bill Wendling63ffde52013-01-18 21:26:07 +00002073 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
Bill Wendling290d9522013-01-27 02:46:53 +00002074 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2075 oldAttrs.getFnAttributes()));
John McCall49954ca2012-12-12 22:21:47 +00002076
2077 // Okay, we can transform this. Create the new call instruction and copy
2078 // over the required information.
2079 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2080
2081 llvm::CallSite newCall;
2082 if (callSite.isCall()) {
2083 newCall = llvm::CallInst::Create(newFn, newArgs, "",
2084 callSite.getInstruction());
2085 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002086 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
John McCall49954ca2012-12-12 22:21:47 +00002087 newCall = llvm::InvokeInst::Create(newFn,
2088 oldInvoke->getNormalDest(),
2089 oldInvoke->getUnwindDest(),
2090 newArgs, "",
2091 callSite.getInstruction());
2092 }
2093 newArgs.clear(); // for the next iteration
2094
2095 if (!newCall->getType()->isVoidTy())
2096 newCall->takeName(callSite.getInstruction());
2097 newCall.setAttributes(
2098 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2099 newCall.setCallingConv(callSite.getCallingConv());
2100
2101 // Finally, remove the old call, replacing any uses with the new one.
2102 if (!callSite->use_empty())
2103 callSite->replaceAllUsesWith(newCall.getInstruction());
2104
2105 // Copy debug location attached to CI.
2106 if (!callSite->getDebugLoc().isUnknown())
2107 newCall->setDebugLoc(callSite->getDebugLoc());
2108 callSite->eraseFromParent();
2109 }
2110}
2111
Chris Lattner36797ab2009-05-05 06:16:31 +00002112/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2113/// implement a function with no prototype, e.g. "int foo() {}". If there are
2114/// existing call uses of the old function in the module, this adjusts them to
2115/// call the new function directly.
2116///
2117/// This is not just a cleanup: the always_inline pass requires direct calls to
2118/// functions to be able to inline them. If there is a bitcast in the way, it
2119/// won't inline them. Instcombine normally deletes these calls, but it isn't
2120/// run at -O0.
2121static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2122 llvm::Function *NewFn) {
2123 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00002124 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00002125
John McCall49954ca2012-12-12 22:21:47 +00002126 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00002127}
2128
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00002129void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2130 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2131 // If we have a definition, this might be a deferred decl. If the
2132 // instantiation is explicit, make sure we emit it at the end.
2133 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2134 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00002135
2136 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00002137}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002138
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002139void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2140 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002141 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00002142
John McCall46288ef2011-03-09 08:12:35 +00002143 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00002144 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2145 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00002146
Chris Lattnereb7466d2009-05-12 20:58:15 +00002147 // Get or create the prototype for the function.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002148 if (!GV) {
2149 llvm::Constant *C =
2150 GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
Mike Stump11289f42009-09-09 15:08:12 +00002151
Rafael Espindola489c66b2014-05-08 14:33:38 +00002152 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002153 if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
Rafael Espindola489c66b2014-05-08 14:33:38 +00002154 assert(CE->getOpcode() == llvm::Instruction::BitCast);
2155 GV = cast<llvm::GlobalValue>(CE->getOperand(0));
2156 } else {
2157 GV = cast<llvm::GlobalValue>(C);
2158 }
Chris Lattnera85d68e2009-03-21 09:25:43 +00002159 }
Mike Stump11289f42009-09-09 15:08:12 +00002160
Rafael Espindola489c66b2014-05-08 14:33:38 +00002161 if (!GV->isDeclaration()) {
Argyrios Kyrtzidisf405dd62013-11-23 18:41:35 +00002162 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2163 return;
2164 }
Mike Stump11289f42009-09-09 15:08:12 +00002165
Rafael Espindola489c66b2014-05-08 14:33:38 +00002166 if (GV->getType()->getElementType() != Ty) {
Daniel Dunbar99d28352009-03-09 23:53:08 +00002167 // If the types mismatch then we have to rewrite the definition.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002168 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
Chris Lattner832323e2009-03-21 08:53:37 +00002169
Chris Lattner5eaee562009-03-21 08:38:50 +00002170 // F is the Function* for the one with the wrong type, we must make a new
2171 // Function* and update everything that used F (a declaration) with the new
2172 // Function* (which will be a definition).
2173 //
2174 // This happens if there is a prototype for a function
2175 // (e.g. "int f()") and then a definition of a different type
John McCall7ec50432010-03-19 23:29:14 +00002176 // (e.g. "int f(int x)"). Move the old function aside so that it
2177 // doesn't interfere with GetAddrOfFunction.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002178 GV->setName(StringRef());
2179 auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump11289f42009-09-09 15:08:12 +00002180
John McCall49954ca2012-12-12 22:21:47 +00002181 // This might be an implementation of a function without a
2182 // prototype, in which case, try to do special replacement of
2183 // calls which match the new prototype. The really key thing here
2184 // is that we also potentially drop arguments from the call site
2185 // so as to make a direct call, which makes the inliner happier
2186 // and suppresses a number of optimizer warnings (!) about
2187 // dropping arguments.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002188 if (!GV->use_empty()) {
2189 ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
2190 GV->removeDeadConstantUsers();
Chris Lattnereb7466d2009-05-12 20:58:15 +00002191 }
Mike Stump11289f42009-09-09 15:08:12 +00002192
Chris Lattner5eaee562009-03-21 08:38:50 +00002193 // Replace uses of F with the Function we will endow with a body.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002194 if (!GV->use_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00002195 llvm::Constant *NewPtrForOldDecl =
Rafael Espindola489c66b2014-05-08 14:33:38 +00002196 llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
2197 GV->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattner36797ab2009-05-05 06:16:31 +00002198 }
Mike Stump11289f42009-09-09 15:08:12 +00002199
Chris Lattner5eaee562009-03-21 08:38:50 +00002200 // Ok, delete the old function now, which is dead.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002201 GV->eraseFromParent();
Mike Stump11289f42009-09-09 15:08:12 +00002202
Rafael Espindola489c66b2014-05-08 14:33:38 +00002203 GV = NewFn;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002204 }
Mike Stump11289f42009-09-09 15:08:12 +00002205
John McCall8e7cb6d2010-11-02 21:04:24 +00002206 // We need to set linkage and visibility on the function before
2207 // generating code for it because various parts of IR generation
2208 // want to propagate this information down (e.g. to local static
2209 // declarations).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002210 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002211 setFunctionLinkage(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002212
Rafael Espindolae033c8c2014-05-08 15:26:12 +00002213 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Anders Carlssonc6a47892011-01-29 19:39:23 +00002214 setGlobalVisibility(Fn, D);
John McCall8e7cb6d2010-11-02 21:04:24 +00002215
Richard Smithdf931ce2013-04-06 05:00:46 +00002216 MaybeHandleStaticInExternC(D, Fn);
2217
John McCalla738c252011-03-09 04:27:21 +00002218 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00002219
Rafael Espindolae033c8c2014-05-08 15:26:12 +00002220 setFunctionDefinitionAttributes(D, Fn);
Daniel Dunbar38932572009-04-14 08:05:55 +00002221 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00002222
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002223 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002224 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002225 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002226 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002227 if (D->hasAttr<AnnotateAttr>())
2228 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002229}
2230
Rafael Espindolab2633b92014-05-16 19:35:48 +00002231static llvm::GlobalObject &getGlobalObjectInExpr(DiagnosticsEngine &Diags,
2232 const AliasAttr *AA,
2233 llvm::Constant *C) {
2234 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
2235 return *GO;
2236
2237 auto *GA = dyn_cast<llvm::GlobalAlias>(C);
2238 if (GA) {
2239 if (GA->mayBeOverridden()) {
2240 Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
2241 << GA->getAliasee()->getName() << GA->getName();
2242 }
2243
2244 return *GA->getAliasee();
2245 }
2246
2247 auto *CE = cast<llvm::ConstantExpr>(C);
2248 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2249 CE->getOpcode() == llvm::Instruction::GetElementPtr ||
2250 CE->getOpcode() == llvm::Instruction::AddrSpaceCast);
2251 return *cast<llvm::GlobalObject>(CE->getOperand(0));
2252}
2253
John McCall7ec50432010-03-19 23:29:14 +00002254void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002255 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002256 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00002257 assert(AA && "Not an alias?");
2258
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002259 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00002260
John McCall7ec50432010-03-19 23:29:14 +00002261 // If there is a definition in the module, then it wins over the alias.
2262 // This is dubious, but allow it to be safe. Just ignore the alias.
2263 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2264 if (Entry && !Entry->isDeclaration())
2265 return;
2266
Rafael Espindola208b5c02013-10-22 19:26:13 +00002267 Aliases.push_back(GD);
2268
Chris Lattner2192fe52011-07-18 04:24:23 +00002269 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00002270
2271 // Create a reference to the named value. This ensures that it is emitted
2272 // if a deferred decl.
2273 llvm::Constant *Aliasee;
2274 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00002275 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00002276 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00002277 else
John McCall7ec50432010-03-19 23:29:14 +00002278 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00002279 llvm::PointerType::getUnqual(DeclTy),
2280 nullptr);
Chris Lattner54041692009-03-22 21:47:11 +00002281
2282 // Create the new alias itself, but don't set a name yet.
Rafael Espindola234405b2014-05-17 21:30:14 +00002283 auto *GA = llvm::GlobalAlias::create(
Rafael Espindola61722772014-05-17 19:58:16 +00002284 cast<llvm::PointerType>(Aliasee->getType())->getElementType(), 0,
Rafael Espindolab2633b92014-05-16 19:35:48 +00002285 llvm::Function::ExternalLinkage, "",
Rafael Espindola61722772014-05-17 19:58:16 +00002286 &getGlobalObjectInExpr(Diags, AA, Aliasee));
Mike Stump11289f42009-09-09 15:08:12 +00002287
Chris Lattner54041692009-03-22 21:47:11 +00002288 if (Entry) {
Rafael Espindolab2633b92014-05-16 19:35:48 +00002289 if (GA->getAliasee() == Entry) {
2290 Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2291 return;
2292 }
2293
John McCall7ec50432010-03-19 23:29:14 +00002294 assert(Entry->isDeclaration());
2295
Chris Lattner54041692009-03-22 21:47:11 +00002296 // If there is a declaration in the module, then we had an extern followed
2297 // by the alias, as in:
2298 // extern int test6();
2299 // ...
2300 // int test6() __attribute__((alias("test7")));
2301 //
2302 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00002303 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00002304
Owen Andersonade90fd2009-07-29 18:54:39 +00002305 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00002306 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00002307 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00002308 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00002309 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00002310 }
Mike Stump11289f42009-09-09 15:08:12 +00002311
Daniel Dunbar38932572009-04-14 08:05:55 +00002312 // Set attributes which are particular to an alias; this is a
2313 // specialization of the attributes which may be set on a global
2314 // variable/function.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002315 if (D->hasAttr<DLLExportAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002316 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Daniel Dunbar38932572009-04-14 08:05:55 +00002317 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002318 if (FD->hasBody())
Nico Rieckbb0554f2014-01-14 15:23:53 +00002319 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Daniel Dunbar38932572009-04-14 08:05:55 +00002320 } else {
Nico Rieckbb0554f2014-01-14 15:23:53 +00002321 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Daniel Dunbar38932572009-04-14 08:05:55 +00002322 }
Mike Stump11289f42009-09-09 15:08:12 +00002323 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindolac18086a2010-02-23 22:00:30 +00002324 D->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002325 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00002326 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2327 }
2328
2329 SetCommonAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00002330}
2331
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002332llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00002333 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00002334 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002335 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00002336}
Chris Lattner1eec6602007-08-31 04:31:45 +00002337
Daniel Dunbar64509b22009-07-23 22:52:48 +00002338static llvm::StringMapEntry<llvm::Constant*> &
2339GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2340 const StringLiteral *Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00002341 bool TargetIsLSB,
Daniel Dunbar64509b22009-07-23 22:52:48 +00002342 bool &IsUTF16,
2343 unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002344 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002345 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00002346
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00002347 // Check for simple case.
2348 if (!Literal->containsNonAsciiOrNull()) {
2349 StringLength = NumBytes;
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002350 return Map.GetOrCreateValue(String);
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00002351 }
2352
Bill Wendling82b87f12012-03-30 00:26:17 +00002353 // Otherwise, convert the UTF8 literals into a string of shorts.
2354 IsUTF16 = true;
2355
2356 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
Roman Divackye6377112012-09-06 15:59:27 +00002357 const UTF8 *FromPtr = (const UTF8 *)String.data();
Daniel Dunbar64509b22009-07-23 22:52:48 +00002358 UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00002359
Fariborz Jahanian535618b2010-09-07 19:57:04 +00002360 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2361 &ToPtr, ToPtr + NumBytes,
2362 strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00002363
Daniel Dunbar91ade142009-07-23 23:41:22 +00002364 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00002365 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00002366
Bill Wendling82b87f12012-03-30 00:26:17 +00002367 // Add an explicit null.
2368 *ToPtr = 0;
2369 return Map.
2370 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2371 (StringLength + 1) * 2));
Daniel Dunbar64509b22009-07-23 22:52:48 +00002372}
2373
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002374static llvm::StringMapEntry<llvm::Constant*> &
2375GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
Bill Wendling07635cc2012-03-29 22:12:09 +00002376 const StringLiteral *Literal,
2377 unsigned &StringLength) {
2378 StringRef String = Literal->getString();
2379 StringLength = String.size();
2380 return Map.GetOrCreateValue(String);
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002381}
2382
Daniel Dunbar64509b22009-07-23 22:52:48 +00002383llvm::Constant *
2384CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2385 unsigned StringLength = 0;
2386 bool isUTF16 = false;
2387 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump11289f42009-09-09 15:08:12 +00002388 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002389 getDataLayout().isLittleEndian(),
Daniel Dunbar91ade142009-07-23 23:41:22 +00002390 isUTF16, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00002391
Daniel Dunbar64509b22009-07-23 22:52:48 +00002392 if (llvm::Constant *C = Entry.getValue())
2393 return C;
Mike Stump11289f42009-09-09 15:08:12 +00002394
Chris Lattnerece04092012-02-07 00:39:47 +00002395 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00002396 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002397 llvm::Value *V;
2398
Chris Lattneraa64ca22009-07-16 16:48:25 +00002399 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00002400 if (!CFConstantStringClassRef) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002401 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002402 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002403 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattneraa64ca22009-07-16 16:48:25 +00002404 "__CFConstantStringClassReference");
Daniel Dunbard644ad62008-08-23 18:37:06 +00002405 // Decay array -> ptr
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002406 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2407 CFConstantStringClassRef = V;
Anders Carlssonb04ea612007-08-21 00:21:21 +00002408 }
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002409 else
2410 V = CFConstantStringClassRef;
Mike Stump11289f42009-09-09 15:08:12 +00002411
Anders Carlssonc2480a52008-11-15 18:54:24 +00002412 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00002413
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002414 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssonc2480a52008-11-15 18:54:24 +00002415
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002416 llvm::Constant *Fields[4];
Douglas Gregor91f84212008-12-11 16:49:14 +00002417
Anders Carlssonb04ea612007-08-21 00:21:21 +00002418 // Class pointer.
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002419 Fields[0] = cast<llvm::ConstantExpr>(V);
Mike Stump11289f42009-09-09 15:08:12 +00002420
Anders Carlssonb04ea612007-08-21 00:21:21 +00002421 // Flags.
Chris Lattner2192fe52011-07-18 04:24:23 +00002422 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump11289f42009-09-09 15:08:12 +00002423 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson157c3212009-08-16 05:55:31 +00002424 llvm::ConstantInt::get(Ty, 0x07C8);
2425
Anders Carlssonb04ea612007-08-21 00:21:21 +00002426 // String pointer.
Craig Topper8a13c412014-05-21 05:09:00 +00002427 llvm::Constant *C = nullptr;
Bill Wendling82b87f12012-03-30 00:26:17 +00002428 if (isUTF16) {
2429 ArrayRef<uint16_t> Arr =
David Greene0a528db2013-01-15 22:09:41 +00002430 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2431 const_cast<char *>(Entry.getKey().data())),
Bill Wendling82b87f12012-03-30 00:26:17 +00002432 Entry.getKey().size() / 2);
2433 C = llvm::ConstantDataArray::get(VMContext, Arr);
2434 } else {
2435 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2436 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002437
Bill Wendling86131f22012-01-10 08:46:39 +00002438 // Note: -fwritable-strings doesn't make the backing store strings of
2439 // CFStrings writable. (See <rdar://problem/10657500>)
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002440 auto *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00002441 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2442 llvm::GlobalValue::PrivateLinkage, C, ".str");
Rafael Espindolae79d43da2011-01-17 16:31:00 +00002443 GV->setUnnamedAddr(true);
Ulrich Weigandfa806422013-05-06 16:23:57 +00002444 // Don't enforce the target's minimum global alignment, since the only use
2445 // of the string is via this class initializer.
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002446 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2447 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2448 // that changes the section it ends in, which surprises ld64.
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002449 if (isUTF16) {
Ken Dycka0f99ff2010-01-26 18:46:23 +00002450 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2451 GV->setAlignment(Align.getQuantity());
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002452 GV->setSection("__TEXT,__ustring");
Daniel Dunbar9c8cd4c2011-04-12 23:30:52 +00002453 } else {
2454 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2455 GV->setAlignment(Align.getQuantity());
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002456 GV->setSection("__TEXT,__cstring,cstring_literals");
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002457 }
Bill Wendling82b87f12012-03-30 00:26:17 +00002458
2459 // String.
Jay Foaded8db7d2011-07-21 14:31:17 +00002460 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00002461
Bill Wendling82b87f12012-03-30 00:26:17 +00002462 if (isUTF16)
2463 // Cast the UTF16 string to the correct type.
2464 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2465
Anders Carlssonb04ea612007-08-21 00:21:21 +00002466 // String length.
2467 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson157c3212009-08-16 05:55:31 +00002468 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00002469
Anders Carlssonb04ea612007-08-21 00:21:21 +00002470 // The struct.
Owen Anderson0e0189d2009-07-27 22:29:56 +00002471 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump11289f42009-09-09 15:08:12 +00002472 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2473 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner3afa3e12009-07-16 05:03:48 +00002474 "_unnamed_cfstring_");
Rafael Espindola8ff16102014-01-20 20:13:11 +00002475 GV->setSection("__DATA,__cfstring");
Daniel Dunbar64509b22009-07-23 22:52:48 +00002476 Entry.setValue(GV);
Mike Stump11289f42009-09-09 15:08:12 +00002477
Anders Carlsson41b7c6b2007-11-01 00:41:52 +00002478 return GV;
Anders Carlssonb04ea612007-08-21 00:21:21 +00002479}
Chris Lattnerfb300092007-11-28 05:34:05 +00002480
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002481llvm::Constant *
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002482CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002483 unsigned StringLength = 0;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002484 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002485 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002486
2487 if (llvm::Constant *C = Entry.getValue())
2488 return C;
2489
Chris Lattner00a10ca2012-02-06 22:47:00 +00002490 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002491 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002492 llvm::Value *V;
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00002493 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002494 if (!ConstantStringClassRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002495 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Chris Lattner2192fe52011-07-18 04:24:23 +00002496 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002497 llvm::Constant *GV;
John McCall5fb5df92012-06-20 06:18:46 +00002498 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002499 std::string str =
2500 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2501 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002502 GV = getObjCRuntime().GetClassGlobal(str);
2503 // Make sure the result is of the correct type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002504 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002505 V = llvm::ConstantExpr::getBitCast(GV, PTy);
2506 ConstantStringClassRef = V;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002507 } else {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002508 std::string str =
2509 StringClass.empty() ? "_NSConstantStringClassReference"
2510 : "_" + StringClass + "ClassReference";
Chris Lattner2192fe52011-07-18 04:24:23 +00002511 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002512 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002513 // Decay array -> ptr
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002514 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2515 ConstantStringClassRef = V;
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002516 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002517 }
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002518 else
2519 V = ConstantStringClassRef;
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002520
2521 if (!NSConstantStringType) {
2522 // Construct the type for a constant NSString.
Alp Toker2dea15b2013-12-17 01:22:38 +00002523 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002524 D->startDefinition();
2525
2526 QualType FieldTypes[3];
2527
2528 // const int *isa;
2529 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2530 // const char *str;
2531 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2532 // unsigned int length;
2533 FieldTypes[2] = Context.UnsignedIntTy;
2534
2535 // Create fields
2536 for (unsigned i = 0; i < 3; ++i) {
2537 FieldDecl *Field = FieldDecl::Create(Context, D,
2538 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002539 SourceLocation(), nullptr,
2540 FieldTypes[i], /*TInfo=*/nullptr,
2541 /*BitWidth=*/nullptr,
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002542 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002543 ICIS_NoInit);
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002544 Field->setAccess(AS_public);
2545 D->addDecl(Field);
2546 }
2547
2548 D->completeDefinition();
2549 QualType NSTy = Context.getTagDeclType(D);
2550 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2551 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002552
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002553 llvm::Constant *Fields[3];
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002554
2555 // Class pointer.
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002556 Fields[0] = cast<llvm::ConstantExpr>(V);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002557
2558 // String pointer.
Chris Lattner9c818332012-02-05 02:30:40 +00002559 llvm::Constant *C =
2560 llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002561
2562 llvm::GlobalValue::LinkageTypes Linkage;
2563 bool isConstant;
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002564 Linkage = llvm::GlobalValue::PrivateLinkage;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002565 isConstant = !LangOpts.WritableStrings;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002566
2567 auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
2568 Linkage, C, ".str");
Rafael Espindolade089d42011-01-17 22:11:21 +00002569 GV->setUnnamedAddr(true);
Ulrich Weigandfa806422013-05-06 16:23:57 +00002570 // Don't enforce the target's minimum global alignment, since the only use
2571 // of the string is via this class initializer.
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002572 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2573 GV->setAlignment(Align.getQuantity());
Jay Foaded8db7d2011-07-21 14:31:17 +00002574 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002575
2576 // String length.
Chris Lattner2192fe52011-07-18 04:24:23 +00002577 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002578 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2579
2580 // The struct.
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002581 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002582 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2583 llvm::GlobalVariable::PrivateLinkage, C,
2584 "_unnamed_nsstring_");
Rafael Espindola63582d62014-01-20 15:19:43 +00002585 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2586 const char *NSStringNonFragileABISection =
Rafael Espindola8ff16102014-01-20 20:13:11 +00002587 "__DATA,__objc_stringobj,regular,no_dead_strip";
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002588 // FIXME. Fix section.
Rafael Espindola8ff16102014-01-20 20:13:11 +00002589 GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2590 ? NSStringNonFragileABISection
2591 : NSStringSection);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002592 Entry.setValue(GV);
2593
2594 return GV;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002595}
2596
Douglas Gregor636e2002011-08-09 17:23:49 +00002597QualType CodeGenModule::getObjCFastEnumerationStateType() {
2598 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00002599 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00002600 D->startDefinition();
2601
2602 QualType FieldTypes[] = {
2603 Context.UnsignedLongTy,
2604 Context.getPointerType(Context.getObjCIdType()),
2605 Context.getPointerType(Context.UnsignedLongTy),
2606 Context.getConstantArrayType(Context.UnsignedLongTy,
2607 llvm::APInt(32, 5), ArrayType::Normal, 0)
2608 };
2609
2610 for (size_t i = 0; i < 4; ++i) {
2611 FieldDecl *Field = FieldDecl::Create(Context,
2612 D,
2613 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002614 SourceLocation(), nullptr,
2615 FieldTypes[i], /*TInfo=*/nullptr,
2616 /*BitWidth=*/nullptr,
Douglas Gregor636e2002011-08-09 17:23:49 +00002617 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002618 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00002619 Field->setAccess(AS_public);
2620 D->addDecl(Field);
2621 }
2622
2623 D->completeDefinition();
2624 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2625 }
2626
2627 return ObjCFastEnumerationStateType;
2628}
2629
Eli Friedmanfcec6302011-11-01 02:23:42 +00002630llvm::Constant *
2631CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2632 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2633
2634 // Don't emit it as the address of the string, emit the string data itself
2635 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00002636 if (E->getCharByteWidth() == 1) {
2637 SmallString<64> Str(E->getString());
2638
2639 // Resize the string to the right size, which is indicated by its type.
2640 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2641 Str.resize(CAT->getSize().getZExtValue());
2642 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2643 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002644
2645 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner9c818332012-02-05 02:30:40 +00002646 llvm::Type *ElemTy = AType->getElementType();
2647 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00002648
2649 // Wide strings have either 2-byte or 4-byte elements.
2650 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2651 SmallVector<uint16_t, 32> Elements;
2652 Elements.reserve(NumElements);
2653
2654 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2655 Elements.push_back(E->getCodeUnit(i));
2656 Elements.resize(NumElements);
2657 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00002658 }
2659
Chris Lattner02cb1712012-02-06 22:52:04 +00002660 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2661 SmallVector<uint32_t, 32> Elements;
2662 Elements.reserve(NumElements);
2663
2664 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2665 Elements.push_back(E->getCodeUnit(i));
2666 Elements.resize(NumElements);
2667 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00002668}
2669
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002670/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2671/// constant array for the given string literal.
2672llvm::Constant *
2673CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
Ulrich Weigandfa806422013-05-06 16:23:57 +00002674 CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
James Molloye735b2b2014-05-09 16:28:56 +00002675
David Majnemer58e5bee2014-03-24 21:43:36 +00002676 llvm::StringMapEntry<llvm::GlobalVariable *> *Entry = nullptr;
2677 llvm::GlobalVariable *GV = nullptr;
2678 if (!LangOpts.WritableStrings) {
2679 llvm::StringMap<llvm::GlobalVariable *> *ConstantStringMap = nullptr;
2680 switch (S->getCharByteWidth()) {
2681 case 1:
2682 ConstantStringMap = &Constant1ByteStringMap;
2683 break;
2684 case 2:
2685 ConstantStringMap = &Constant2ByteStringMap;
2686 break;
2687 case 4:
2688 ConstantStringMap = &Constant4ByteStringMap;
2689 break;
2690 default:
2691 llvm_unreachable("unhandled byte width!");
2692 }
2693 Entry = &ConstantStringMap->GetOrCreateValue(S->getBytes());
2694 GV = Entry->getValue();
Eli Friedman49ddc5f2009-11-16 05:55:46 +00002695 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00002696
David Majnemer58e5bee2014-03-24 21:43:36 +00002697 if (!GV) {
2698 SmallString<256> MangledNameBuffer;
2699 StringRef GlobalVariableName;
2700 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00002701
David Majnemer58e5bee2014-03-24 21:43:36 +00002702 // Mangle the string literal if the ABI allows for it. However, we cannot
2703 // do this if we are compiling with ASan or -fwritable-strings because they
2704 // rely on strings having normal linkage.
2705 if (!LangOpts.WritableStrings && !SanOpts.Address &&
2706 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
2707 llvm::raw_svector_ostream Out(MangledNameBuffer);
2708 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
2709 Out.flush();
2710
2711 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2712 GlobalVariableName = MangledNameBuffer;
2713 } else {
Alp Toker5f072d82014-04-19 23:55:49 +00002714 LT = llvm::GlobalValue::PrivateLinkage;
David Majnemer58e5bee2014-03-24 21:43:36 +00002715 GlobalVariableName = ".str";
2716 }
2717
2718 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2719 unsigned AddrSpace = 0;
2720 if (getLangOpts().OpenCL)
2721 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
2722
2723 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2724 GV = new llvm::GlobalVariable(
2725 getModule(), C->getType(), !LangOpts.WritableStrings, LT, C,
2726 GlobalVariableName, /*InsertBefore=*/nullptr,
2727 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2728 GV->setUnnamedAddr(true);
2729 if (Entry)
2730 Entry->setValue(GV);
2731 }
2732
2733 if (Align.getQuantity() > GV->getAlignment())
2734 GV->setAlignment(Align.getQuantity());
2735
Eli Friedmanfcec6302011-11-01 02:23:42 +00002736 return GV;
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002737}
2738
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002739/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2740/// array for the given ObjCEncodeExpr node.
2741llvm::Constant *
2742CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2743 std::string Str;
2744 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00002745
2746 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002747}
2748
2749
Chris Lattner36fc8792008-02-11 00:02:17 +00002750/// GenerateWritableString -- Creates storage for a string literal.
John McCall9b24df42011-08-04 01:03:22 +00002751static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
Chris Lattnerfb300092007-11-28 05:34:05 +00002752 bool constant,
Daniel Dunbardfcf5992008-10-17 21:56:50 +00002753 CodeGenModule &CGM,
John McCall9b24df42011-08-04 01:03:22 +00002754 const char *GlobalName,
2755 unsigned Alignment) {
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002756 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson41a75022009-08-13 21:57:51 +00002757 llvm::Constant *C =
Chris Lattner9c818332012-02-05 02:30:40 +00002758 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
Mike Stump11289f42009-09-09 15:08:12 +00002759
David Majnemer58e5bee2014-03-24 21:43:36 +00002760 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
Joey Gouly561bba22013-11-14 18:26:10 +00002761 unsigned AddrSpace = 0;
2762 if (CGM.getLangOpts().OpenCL)
2763 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2764
Chris Lattnerfb300092007-11-28 05:34:05 +00002765 // Create a global variable for this string
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002766 auto *GV = new llvm::GlobalVariable(
Joey Gouly561bba22013-11-14 18:26:10 +00002767 CGM.getModule(), C->getType(), constant,
Craig Topper8a13c412014-05-21 05:09:00 +00002768 llvm::GlobalValue::PrivateLinkage, C, GlobalName, nullptr,
Joey Gouly561bba22013-11-14 18:26:10 +00002769 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall9b24df42011-08-04 01:03:22 +00002770 GV->setAlignment(Alignment);
Rafael Espindolab7f60e32011-01-10 22:34:03 +00002771 GV->setUnnamedAddr(true);
2772 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00002773}
2774
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002775/// GetAddrOfConstantString - Returns a pointer to a character array
2776/// containing the literal. This contents are exactly that of the
2777/// given string, i.e. it will not be null terminated automatically;
2778/// see GetAddrOfConstantCString. Note that whether the result is
2779/// actually a pointer to an LLVM constant depends on
2780/// Feature.WriteableStrings.
2781///
2782/// The result has pointer to array type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002783llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
John McCall9b24df42011-08-04 01:03:22 +00002784 const char *GlobalName,
2785 unsigned Alignment) {
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002786 // Get the default prefix if a name wasn't specified.
2787 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00002788 GlobalName = ".str";
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002789
Ulrich Weigandfa806422013-05-06 16:23:57 +00002790 if (Alignment == 0)
2791 Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
2792 .getQuantity();
2793
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002794 // Don't share any string literals if strings aren't constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002795 if (LangOpts.WritableStrings)
John McCall9b24df42011-08-04 01:03:22 +00002796 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
Mike Stump11289f42009-09-09 15:08:12 +00002797
John McCall9b24df42011-08-04 01:03:22 +00002798 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
David Majnemer58e5bee2014-03-24 21:43:36 +00002799 Constant1ByteStringMap.GetOrCreateValue(Str);
Chris Lattnerfb300092007-11-28 05:34:05 +00002800
John McCall9b24df42011-08-04 01:03:22 +00002801 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2802 if (Alignment > GV->getAlignment()) {
2803 GV->setAlignment(Alignment);
2804 }
2805 return GV;
2806 }
Chris Lattnerfb300092007-11-28 05:34:05 +00002807
2808 // Create a global variable for this.
Chris Lattner00a10ca2012-02-06 22:47:00 +00002809 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2810 Alignment);
John McCall9b24df42011-08-04 01:03:22 +00002811 Entry.setValue(GV);
2812 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00002813}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002814
2815/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002816/// array containing the literal and a terminating '\0'
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002817/// character. The result has pointer to array type.
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002818llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
John McCall9b24df42011-08-04 01:03:22 +00002819 const char *GlobalName,
2820 unsigned Alignment) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002821 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall9b24df42011-08-04 01:03:22 +00002822 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002823}
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002824
Richard Smithe6c01442013-06-05 00:46:14 +00002825llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00002826 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00002827 assert((E->getStorageDuration() == SD_Static ||
2828 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002829 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smithe6c01442013-06-05 00:46:14 +00002830
2831 // If we're not materializing a subobject of the temporary, keep the
2832 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00002833 QualType MaterializedType = Init->getType();
2834 if (Init == E->GetTemporaryExpr())
2835 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00002836
2837 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2838 if (Slot)
2839 return Slot;
2840
2841 // FIXME: If an externally-visible declaration extends multiple temporaries,
2842 // we need to give each temporary the same name in every translation unit (and
2843 // we also need to make the temporaries externally-visible).
2844 SmallString<256> Name;
2845 llvm::raw_svector_ostream Out(Name);
David Majnemerdaff3702014-05-01 17:50:17 +00002846 getCXXABI().getMangleContext().mangleReferenceTemporary(
2847 VD, E->getManglingNumber(), Out);
Richard Smithe6c01442013-06-05 00:46:14 +00002848 Out.flush();
2849
Craig Topper8a13c412014-05-21 05:09:00 +00002850 APValue *Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00002851 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00002852 // We might have a cached constant initializer for this temporary. Note
2853 // that this might have a different value from the value computed by
2854 // evaluating the initializer if the surrounding constant expression
2855 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00002856 Value = getContext().getMaterializedTemporaryValue(E, false);
2857 if (Value && Value->isUninit())
Craig Topper8a13c412014-05-21 05:09:00 +00002858 Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00002859 }
2860
Richard Smitha509f2f2013-06-14 03:07:01 +00002861 // Try evaluating it now, it might have a constant initializer.
2862 Expr::EvalResult EvalResult;
2863 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
2864 !EvalResult.hasSideEffects())
2865 Value = &EvalResult.Val;
2866
Craig Topper8a13c412014-05-21 05:09:00 +00002867 llvm::Constant *InitialValue = nullptr;
Richard Smitha509f2f2013-06-14 03:07:01 +00002868 bool Constant = false;
2869 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00002870 if (Value) {
2871 // The temporary has a constant initializer, use it.
Craig Topper8a13c412014-05-21 05:09:00 +00002872 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
Richard Smitha509f2f2013-06-14 03:07:01 +00002873 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
2874 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00002875 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00002876 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00002877 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00002878 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00002879 }
2880
2881 // Create a global variable for this lifetime-extended temporary.
David Majnemer27d69db2014-04-28 22:17:59 +00002882 llvm::GlobalValue::LinkageTypes Linkage =
2883 getLLVMLinkageVarDefinition(VD, Constant);
David Majnemer846c2832014-04-29 06:18:53 +00002884 // There is no need for this temporary to have global linkage if the global
2885 // variable has external linkage.
David Majnemer27d69db2014-04-28 22:17:59 +00002886 if (Linkage == llvm::GlobalVariable::ExternalLinkage)
2887 Linkage = llvm::GlobalVariable::PrivateLinkage;
2888 unsigned AddrSpace = GetGlobalVarAddressSpace(
2889 VD, getContext().getTargetAddressSpace(MaterializedType));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002890 auto *GV = new llvm::GlobalVariable(
David Majnemer27d69db2014-04-28 22:17:59 +00002891 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
2892 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
2893 AddrSpace);
David Majnemer846c2832014-04-29 06:18:53 +00002894 setGlobalVisibility(GV, VD);
Richard Smithe6c01442013-06-05 00:46:14 +00002895 GV->setAlignment(
Richard Smitha509f2f2013-06-14 03:07:01 +00002896 getContext().getTypeAlignInChars(MaterializedType).getQuantity());
Richard Smithe6c01442013-06-05 00:46:14 +00002897 if (VD->getTLSKind())
2898 setTLSMode(GV, *VD);
2899 Slot = GV;
2900 return GV;
2901}
2902
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002903/// EmitObjCPropertyImplementations - Emit information for synthesized
2904/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00002905void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002906 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00002907 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002908 // Dynamic is just for type-checking.
2909 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2910 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2911
2912 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00002913 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002914 // we want, that just indicates if the decl came from a
2915 // property. What we want to know is if the method is defined in
2916 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002917 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00002918 CodeGenFunction(*this).GenerateObjCGetter(
2919 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002920 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002921 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00002922 CodeGenFunction(*this).GenerateObjCSetter(
2923 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002924 }
2925 }
2926}
2927
John McCall6a4fa522011-03-22 07:05:39 +00002928static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002929 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2930 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00002931 ivar; ivar = ivar->getNextIvar())
2932 if (ivar->getType().isDestructedType())
2933 return true;
2934
2935 return false;
2936}
2937
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002938/// EmitObjCIvarInitializations - Emit information for ivar initialization
2939/// for an implementation.
2940void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00002941 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2942 if (needsDestructMethod(D)) {
2943 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2944 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2945 ObjCMethodDecl *DTORMethod =
2946 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002947 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002948 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00002949 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002950 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00002951 D->addInstanceMethod(DTORMethod);
2952 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00002953 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00002954 }
2955
2956 // If the implementation doesn't have any ivar initializers, we don't need
2957 // a .cxx_construct.
David Chisnalla9e54602011-03-17 14:19:08 +00002958 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002959 return;
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002960
John McCall6a4fa522011-03-22 07:05:39 +00002961 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2962 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002963 // The constructor returns 'self'.
2964 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2965 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00002966 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00002967 cxxSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00002968 getContext().getObjCIdType(),
2969 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002970 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00002971 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002972 /*isImplicitlyDeclared=*/true,
2973 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002974 ObjCMethodDecl::Required);
2975 D->addInstanceMethod(CTORMethod);
2976 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00002977 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002978}
2979
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002980/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson237f3492009-04-01 00:58:25 +00002981void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Aaron Ballman629afae2014-03-07 19:56:05 +00002982 for (auto *I : ND->decls()) {
2983 if (const auto *VD = dyn_cast<VarDecl>(I))
David Blaikieb00f3602013-09-04 21:07:37 +00002984 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2985 VD->getTemplateSpecializationKind() != TSK_Undeclared)
2986 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00002987 EmitTopLevelDecl(I);
David Blaikieb00f3602013-09-04 21:07:37 +00002988 }
Anders Carlsson237f3492009-04-01 00:58:25 +00002989}
2990
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002991// EmitLinkageSpec - Emit all declarations in a linkage spec.
2992void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00002993 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2994 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002995 ErrorUnsupported(LSD, "linkage spec");
2996 return;
2997 }
2998
Aaron Ballman629afae2014-03-07 19:56:05 +00002999 for (auto *I : LSD->decls()) {
Fariborz Jahanian9dd2e082012-10-26 22:20:25 +00003000 // Meta-data for ObjC class includes references to implemented methods.
3001 // Generate class's method definitions first.
Aaron Ballman629afae2014-03-07 19:56:05 +00003002 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003003 for (auto *M : OID->methods())
3004 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00003005 }
Aaron Ballman629afae2014-03-07 19:56:05 +00003006 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00003007 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003008}
3009
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003010/// EmitTopLevelDecl - Emit code for a single top level declaration.
3011void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003012 // Ignore dependent declarations.
3013 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3014 return;
Mike Stump11289f42009-09-09 15:08:12 +00003015
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003016 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00003017 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00003018 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003019 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00003020 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00003021 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3022 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor70d83e22009-06-29 17:30:29 +00003023 return;
Mike Stump11289f42009-09-09 15:08:12 +00003024
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003025 EmitGlobal(cast<FunctionDecl>(D));
3026 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003027
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003028 case Decl::Var:
Larisse Voufo39a1e502013-08-06 01:03:05 +00003029 // Skip variable templates
3030 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3031 return;
3032 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003033 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003034 break;
3035
John McCall32f44bd2011-04-12 01:01:22 +00003036 // Indirect fields from global anonymous structs and unions can be
3037 // ignored; only the actual variable requires IR gen support.
3038 case Decl::IndirectField:
3039 break;
3040
Anders Carlssonf7475242009-04-15 15:55:24 +00003041 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003042 case Decl::Namespace:
Anders Carlsson237f3492009-04-01 00:58:25 +00003043 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003044 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00003045 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00003046 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003047 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00003048 case Decl::VarTemplate:
3049 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003050 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00003051 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00003052 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00003053 case Decl::Empty:
Douglas Gregorfec52632009-06-20 00:51:54 +00003054 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00003055 case Decl::Using: // using X; [C++]
3056 if (CGDebugInfo *DI = getModuleDebugInfo())
3057 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3058 return;
David Blaikief121b932013-05-20 22:50:41 +00003059 case Decl::NamespaceAlias:
3060 if (CGDebugInfo *DI = getModuleDebugInfo())
3061 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3062 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00003063 case Decl::UsingDirective: // using namespace X; [C++]
3064 if (CGDebugInfo *DI = getModuleDebugInfo())
3065 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3066 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00003067 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00003068 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00003069 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3070 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson0ade9712009-11-24 05:16:24 +00003071 return;
3072
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00003073 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00003074 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00003075 case Decl::CXXDestructor:
Francois Pichet1c229c02011-04-22 22:18:13 +00003076 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3077 return;
Reid Klecknere7de47e2013-07-22 13:51:44 +00003078 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00003079 break;
Anders Carlsson87835432009-06-11 21:22:55 +00003080
3081 case Decl::StaticAssert:
3082 // Nothing to do.
3083 break;
3084
Anders Carlssonf7475242009-04-15 15:55:24 +00003085 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00003086
Fariborz Jahanian3654e652009-03-18 22:33:24 +00003087 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00003088 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00003089 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00003090 break;
3091
Douglas Gregorf6102672012-01-01 21:23:57 +00003092 case Decl::ObjCProtocol: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003093 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorf6102672012-01-01 21:23:57 +00003094 if (Proto->isThisDeclarationADefinition())
3095 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003096 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00003097 }
3098
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003099 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003100 // Categories have properties but don't support synthesize so we
3101 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00003102 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003103 break;
3104
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003105 case Decl::ObjCImplementation: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003106 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003107 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003108 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00003109 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00003110 // Emit global variable debug information.
3111 if (CGDebugInfo *DI = getModuleDebugInfo())
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00003112 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3113 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3114 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003115 break;
Mike Stump11289f42009-09-09 15:08:12 +00003116 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003117 case Decl::ObjCMethod: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003118 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003119 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003120 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003121 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3122 break;
3123 }
Mike Stump11289f42009-09-09 15:08:12 +00003124 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00003125 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003126 break;
3127
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003128 case Decl::LinkageSpec:
3129 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003130 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003131
3132 case Decl::FileScopeAsm: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003133 auto *AD = cast<FileScopeAsmDecl>(D);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003134 StringRef AsmString = AD->getAsmString()->getString();
Mike Stump11289f42009-09-09 15:08:12 +00003135
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003136 const std::string &S = getModule().getModuleInlineAsm();
3137 if (S.empty())
3138 getModule().setModuleInlineAsm(AsmString);
Joerg Sonnenberger8c02a242012-08-10 10:57:52 +00003139 else if (S.end()[-1] == '\n')
Chris Lattner84037d32011-07-23 20:04:25 +00003140 getModule().setModuleInlineAsm(S + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003141 else
Benjamin Kramerb11118b2009-12-11 13:33:18 +00003142 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003143 break;
3144 }
Mike Stump11289f42009-09-09 15:08:12 +00003145
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003146 case Decl::Import: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003147 auto *Import = cast<ImportDecl>(D);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003148
3149 // Ignore import declarations that come from imported modules.
3150 if (clang::Module *Owner = Import->getOwningModule()) {
3151 if (getLangOpts().CurrentModule.empty() ||
3152 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3153 break;
3154 }
3155
Douglas Gregorbc25ff42013-01-14 20:53:57 +00003156 ImportedModules.insert(Import->getImportedModule());
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003157 break;
David Blaikie0e716b42014-03-03 23:48:23 +00003158 }
3159
3160 case Decl::ClassTemplateSpecialization: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003161 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
David Blaikie0e716b42014-03-03 23:48:23 +00003162 if (DebugInfo &&
3163 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition)
3164 DebugInfo->completeTemplateDefinition(*Spec);
3165 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003166
Mike Stump11289f42009-09-09 15:08:12 +00003167 default:
Mike Stump18bb9282009-05-16 07:57:57 +00003168 // Make sure we handled everything we should, every other kind is a
3169 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
3170 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003171 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3172 }
3173}
John McCall09ae0322010-07-06 23:57:41 +00003174
3175/// Turns the given pointer into a constant.
3176static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3177 const void *Ptr) {
3178 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00003179 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00003180 return llvm::ConstantInt::get(i64, PtrInt);
3181}
3182
3183static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3184 llvm::NamedMDNode *&GlobalMetadata,
3185 GlobalDecl D,
3186 llvm::GlobalValue *Addr) {
3187 if (!GlobalMetadata)
3188 GlobalMetadata =
3189 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3190
3191 // TODO: should we report variant information for ctors/dtors?
3192 llvm::Value *Ops[] = {
3193 Addr,
3194 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
3195 };
Jay Foadea324f12011-04-21 19:59:12 +00003196 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00003197}
3198
Richard Smithdf931ce2013-04-06 05:00:46 +00003199/// For each function which is declared within an extern "C" region and marked
3200/// as 'used', but has internal linkage, create an alias from the unmangled
3201/// name to the mangled name if possible. People expect to be able to refer
3202/// to such functions with an unmangled name from inline assembly within the
3203/// same translation unit.
3204void CodeGenModule::EmitStaticExternCAliases() {
Richard Smithf21c9612013-04-13 01:28:18 +00003205 for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3206 E = StaticExternCValues.end();
3207 I != E; ++I) {
3208 IdentifierInfo *Name = I->first;
3209 llvm::GlobalValue *Val = I->second;
Richard Smith85465e62013-04-06 07:07:44 +00003210 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola234405b2014-05-17 21:30:14 +00003211 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(),
3212 cast<llvm::GlobalObject>(Val)));
Richard Smith85465e62013-04-06 07:07:44 +00003213 }
Richard Smithdf931ce2013-04-06 05:00:46 +00003214}
3215
John McCall09ae0322010-07-06 23:57:41 +00003216/// Emits metadata nodes associating all the global values in the
3217/// current module with the Decls they came from. This is useful for
3218/// projects using IR gen as a subroutine.
3219///
3220/// Since there's currently no way to associate an MDNode directly
3221/// with an llvm::GlobalValue, we create a global named metadata
3222/// with the name 'clang.global.decl.ptrs'.
3223void CodeGenModule::EmitDeclMetadata() {
Craig Topper8a13c412014-05-21 05:09:00 +00003224 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00003225
3226 // StaticLocalDeclMap
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003227 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
John McCall09ae0322010-07-06 23:57:41 +00003228 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
3229 I != E; ++I) {
3230 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
3231 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
3232 }
3233}
3234
3235/// Emits metadata nodes for all the local variables in the current
3236/// function.
3237void CodeGenFunction::EmitDeclMetadata() {
3238 if (LocalDeclMap.empty()) return;
3239
3240 llvm::LLVMContext &Context = getLLVMContext();
3241
3242 // Find the unique metadata ID for this name.
3243 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3244
Craig Topper8a13c412014-05-21 05:09:00 +00003245 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00003246
3247 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3248 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3249 const Decl *D = I->first;
3250 llvm::Value *Addr = I->second;
3251
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003252 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00003253 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foadea324f12011-04-21 19:59:12 +00003254 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003255 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00003256 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3257 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3258 }
3259 }
3260}
Daniel Dunbar900546d2010-07-16 00:00:15 +00003261
Rafael Espindola3bfa4682013-10-16 19:28:50 +00003262void CodeGenModule::EmitVersionIdentMetadata() {
3263 llvm::NamedMDNode *IdentMetadata =
3264 TheModule.getOrInsertNamedMetadata("llvm.ident");
3265 std::string Version = getClangFullVersion();
3266 llvm::LLVMContext &Ctx = TheModule.getContext();
3267
3268 llvm::Value *IdentNode[] = {
3269 llvm::MDString::get(Ctx, Version)
3270 };
3271 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3272}
3273
Nick Lewycky85c011d2011-05-05 00:08:20 +00003274void CodeGenModule::EmitCoverageFile() {
3275 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky480cb992011-05-04 20:46:58 +00003276 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3277 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3278 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky85c011d2011-05-05 00:08:20 +00003279 llvm::MDString *CoverageFile =
3280 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky480cb992011-05-04 20:46:58 +00003281 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3282 llvm::MDNode *CU = CUNode->getOperand(i);
Nick Lewycky85c011d2011-05-05 00:08:20 +00003283 llvm::Value *node[] = { CoverageFile, CU };
Nick Lewycky480cb992011-05-04 20:46:58 +00003284 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3285 GCov->addOperand(N);
3286 }
3287 }
3288 }
3289}
Nico Webercf4ff5862012-10-11 10:13:44 +00003290
3291llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3292 QualType GuidType) {
3293 // Sema has checked that all uuid strings are of the form
3294 // "12345678-1234-1234-1234-1234567890ab".
3295 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00003296 for (unsigned i = 0; i < 36; ++i) {
3297 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3298 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00003299 }
Nico Webercf4ff5862012-10-11 10:13:44 +00003300
David Majnemerbbecd092013-08-15 19:59:14 +00003301 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00003302
David Majnemerbbecd092013-08-15 19:59:14 +00003303 llvm::Constant *Field3[8];
3304 for (unsigned Idx = 0; Idx < 8; ++Idx)
3305 Field3[Idx] = llvm::ConstantInt::get(
3306 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3307
3308 llvm::Constant *Fields[4] = {
3309 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
3310 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
3311 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3312 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3313 };
3314
3315 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00003316}