blob: c72b8665f35a72df6cce86eac95d2024358b3e80 [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"
Chris Lattner984fac52009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000016#include "CodeGenFunction.h"
Dan Gohman947c9af2010-10-14 23:06:10 +000017#include "CodeGenTBAA.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000018#include "CGCall.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000019#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000020#include "CGCXXABI.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000021#include "CGObjCRuntime.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000022#include "CGOpenCLRuntime.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000023#include "TargetInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000025#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000026#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000027#include "clang/AST/DeclObjC.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000028#include "clang/AST/DeclCXX.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000029#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000030#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000031#include "clang/AST/RecordLayout.h"
Rafael Espindolac5941352011-10-26 20:41:06 +000032#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindola4fdc1752011-12-19 14:41:01 +000033#include "clang/Basic/Builtins.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000034#include "clang/Basic/Diagnostic.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000035#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000036#include "clang/Basic/TargetInfo.h"
Steve Naroff29cae662009-04-01 15:50:34 +000037#include "clang/Basic/ConvertUTF.h"
Nate Begemanaca747a2008-03-09 03:09:36 +000038#include "llvm/CallingConv.h"
Chris Lattner1eec6602007-08-31 04:31:45 +000039#include "llvm/Module.h"
Chris Lattner09153c02007-06-22 18:48:09 +000040#include "llvm/Intrinsics.h"
Chris Lattner5e124bf2009-12-28 21:44:41 +000041#include "llvm/LLVMContext.h"
Sebastian Redl4a7eab22012-02-25 20:51:20 +000042#include "llvm/ADT/APSInt.h"
John McCallbeec5a02010-03-06 00:35:14 +000043#include "llvm/ADT/Triple.h"
Rafael Espindolaac00f5d2011-02-10 23:59:36 +000044#include "llvm/Target/Mangler.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000045#include "llvm/Target/TargetData.h"
Gabor Greifd0ef1342010-04-10 02:56:12 +000046#include "llvm/Support/CallSite.h"
Chris Lattner15275e52009-11-07 09:22:46 +000047#include "llvm/Support/ErrorHandling.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000048using namespace clang;
49using namespace CodeGen;
50
Julien Lerouge5a6b6982011-09-09 22:41:49 +000051static const char AnnotationSection[] = "llvm.metadata";
52
John McCall614dbdc2010-08-22 21:01:12 +000053static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000054 switch (CGM.getContext().getTargetInfo().getCXXABI()) {
John McCall614dbdc2010-08-22 21:01:12 +000055 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
56 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
57 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
58 }
59
60 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000061}
62
Chris Lattnerbed31442007-05-28 01:07:47 +000063
Chandler Carruthbc55fe22009-11-12 17:24:48 +000064CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall731be662010-03-04 04:29:44 +000065 llvm::Module &M, const llvm::TargetData &TD,
David Blaikie9c902b52011-09-25 23:23:43 +000066 DiagnosticsEngine &diags)
David Blaikiebbafb8a2012-03-11 07:00:24 +000067 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
John McCall731be662010-03-04 04:29:44 +000068 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
John McCall614dbdc2010-08-22 21:01:12 +000069 ABI(createCXXABI(*this)),
John McCalla729c622012-02-17 03:33:10 +000070 Types(*this),
Dan Gohman947c9af2010-10-14 23:06:10 +000071 TBAA(0),
Peter Collingbournefe883422011-10-06 18:29:37 +000072 VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
Dan Gohman515a60d2012-02-16 00:57:37 +000073 DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
74 RRData(0), CFConstantStringClassRef(0),
Peter Collingbournefe883422011-10-06 18:29:37 +000075 ConstantStringClassRef(0), NSConstantStringType(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000076 VMContext(M.getContext()),
77 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
John McCallad7c5c12011-02-08 08:22:06 +000078 BlockObjectAssign(0), BlockObjectDispose(0),
79 BlockDescriptorType(0), GenericBlockLiteralType(0) {
Chris Lattnerece04092012-02-07 00:39:47 +000080
81 // Initialize the type cache.
82 llvm::LLVMContext &LLVMContext = M.getContext();
83 VoidTy = llvm::Type::getVoidTy(LLVMContext);
84 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
85 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
86 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
87 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
88 FloatTy = llvm::Type::getFloatTy(LLVMContext);
89 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
90 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
91 PointerAlignInBytes =
92 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
93 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
94 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
95 Int8PtrTy = Int8Ty->getPointerTo(0);
96 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
97
David Blaikiebbafb8a2012-03-11 07:00:24 +000098 if (LangOpts.ObjC1)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000099 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000100 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000101 createOpenCLRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000102 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000103 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000104
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000105 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
106 if (LangOpts.ThreadSanitizer ||
107 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
108 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
Dan Gohman2e29eb52010-10-15 20:23:12 +0000109 ABI.getMangleContext());
Dan Gohman947c9af2010-10-14 23:06:10 +0000110
Nick Lewycky207bce32011-04-21 23:44:07 +0000111 // If debug info or coverage generation is enabled, create the CGDebugInfo
112 // object.
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000113 if (CodeGenOpts.DebugInfo != CodeGenOptions::NoDebugInfo ||
114 CodeGenOpts.EmitGcovArcs ||
Nick Lewycky207bce32011-04-21 23:44:07 +0000115 CodeGenOpts.EmitGcovNotes)
116 DebugInfo = new CGDebugInfo(*this);
John McCallad7c5c12011-02-08 08:22:06 +0000117
118 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000119
David Blaikiebbafb8a2012-03-11 07:00:24 +0000120 if (C.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +0000121 ARCData = new ARCEntrypoints();
122 RRData = new RREntrypoints();
Chris Lattnera087ff92008-03-01 08:45:05 +0000123}
124
125CodeGenModule::~CodeGenModule() {
Peter Collingbournee1d20992011-07-27 20:29:46 +0000126 delete ObjCRuntime;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000127 delete OpenCLRuntime;
Peter Collingbournefe883422011-10-06 18:29:37 +0000128 delete CUDARuntime;
Ted Kremenekc168e502011-10-08 05:28:26 +0000129 delete TheTargetCodeGenInfo;
John McCall614dbdc2010-08-22 21:01:12 +0000130 delete &ABI;
Dan Gohmand19ee8a2010-10-15 18:04:46 +0000131 delete TBAA;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000132 delete DebugInfo;
John McCall31168b02011-06-15 23:02:42 +0000133 delete ARCData;
134 delete RRData;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000135}
136
David Chisnall481e3a82010-01-23 02:40:42 +0000137void CodeGenModule::createObjCRuntime() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000138 if (!LangOpts.NeXTRuntime)
Peter Collingbournee1d20992011-07-27 20:29:46 +0000139 ObjCRuntime = CreateGNUObjCRuntime(*this);
David Chisnall481e3a82010-01-23 02:40:42 +0000140 else
Peter Collingbournee1d20992011-07-27 20:29:46 +0000141 ObjCRuntime = CreateMacObjCRuntime(*this);
David Chisnall481e3a82010-01-23 02:40:42 +0000142}
143
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000144void CodeGenModule::createOpenCLRuntime() {
145 OpenCLRuntime = new CGOpenCLRuntime(*this);
146}
147
Peter Collingbournefe883422011-10-06 18:29:37 +0000148void CodeGenModule::createCUDARuntime() {
149 CUDARuntime = CreateNVCUDARuntime(*this);
150}
151
Ted Kremenek2c674f62008-08-05 18:50:11 +0000152void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000153 EmitDeferred();
Eli Friedman5866fe32010-01-08 00:50:11 +0000154 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000155 EmitCXXGlobalDtorFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000156 if (ObjCRuntime)
157 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000158 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000159 EmitCtorList(GlobalCtors, "llvm.global_ctors");
160 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000161 EmitGlobalAnnotations();
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000162 EmitLLVMUsed();
John McCall09ae0322010-07-06 23:57:41 +0000163
John McCall0bdb1fd2010-09-16 06:16:50 +0000164 SimplifyPersonality();
165
John McCall09ae0322010-07-06 23:57:41 +0000166 if (getCodeGenOpts().EmitDeclMetadata)
167 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000168
169 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000170 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000171
172 if (DebugInfo)
173 DebugInfo->finalize();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000174}
175
Devang Patel945b8ae2011-03-23 16:29:39 +0000176void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
177 // Make sure that this type is translated.
178 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000179}
180
Dan Gohman947c9af2010-10-14 23:06:10 +0000181llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
182 if (!TBAA)
183 return 0;
184 return TBAA->getTBAAInfo(QTy);
185}
186
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000187llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
188 if (!TBAA)
189 return 0;
190 return TBAA->getTBAAInfoForVTablePtr();
191}
192
Dan Gohman947c9af2010-10-14 23:06:10 +0000193void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
194 llvm::MDNode *TBAAInfo) {
195 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
196}
197
John McCallbeec5a02010-03-06 00:35:14 +0000198bool CodeGenModule::isTargetDarwin() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000199 return getContext().getTargetInfo().getTriple().isOSDarwin();
John McCallbeec5a02010-03-06 00:35:14 +0000200}
201
Chandler Carruth84537952012-03-30 19:44:53 +0000202void CodeGenModule::Error(SourceLocation loc, StringRef error) {
203 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
John McCall7ef5cb32011-03-18 02:56:14 +0000204 getDiags().Report(Context.getFullLoc(loc), diagID);
205}
206
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000207/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000208/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000209void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
210 bool OmitOnError) {
211 if (OmitOnError && getDiags().hasErrorOccurred())
212 return;
David Blaikie9c902b52011-09-25 23:23:43 +0000213 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000214 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000215 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000216 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
217 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000218}
Chris Lattner41af8182007-12-02 06:27:33 +0000219
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000220/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000221/// specified decl yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000222void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
223 bool OmitOnError) {
224 if (OmitOnError && getDiags().hasErrorOccurred())
225 return;
David Blaikie9c902b52011-09-25 23:23:43 +0000226 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000227 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000228 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000229 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000230}
231
John McCall23c29fe2011-06-24 21:55:10 +0000232llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
233 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
234}
235
Mike Stump11289f42009-09-09 15:08:12 +0000236void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlssonc6a47892011-01-29 19:39:23 +0000237 const NamedDecl *D) const {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000238 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000239 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000240 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000241 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000242 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000243
John McCallc273f242010-10-30 11:50:40 +0000244 // Set visibility for definitions.
245 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000246 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
247 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000248}
249
John McCalle16adc22010-08-04 08:34:44 +0000250/// Set the symbol visibility of type information (vtable and RTTI)
251/// associated with the given type.
252void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
253 const CXXRecordDecl *RD,
Anders Carlsson265aa7c2011-01-29 20:24:48 +0000254 TypeVisibilityKind TVK) const {
Anders Carlssonc6a47892011-01-29 19:39:23 +0000255 setGlobalVisibility(GV, RD);
John McCalle16adc22010-08-04 08:34:44 +0000256
John McCallb3732bb2010-08-12 23:36:15 +0000257 if (!CodeGenOpts.HiddenWeakVTables)
258 return;
259
Anders Carlsson678632f2011-01-29 20:36:11 +0000260 // We never want to drop the visibility for RTTI names.
261 if (TVK == TVK_ForRTTIName)
262 return;
263
John McCalle16adc22010-08-04 08:34:44 +0000264 // We want to drop the visibility to hidden for weak type symbols.
265 // This isn't possible if there might be unresolved references
266 // elsewhere that rely on this symbol being visible.
267
John McCall5513fce92010-08-05 20:39:18 +0000268 // This should be kept roughly in sync with setThunkVisibility
269 // in CGVTables.cpp.
270
John McCalle16adc22010-08-04 08:34:44 +0000271 // Preconditions.
Anders Carlsson571e2ad2011-01-24 00:46:19 +0000272 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
John McCalle16adc22010-08-04 08:34:44 +0000273 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
274 return;
275
276 // Don't override an explicit visibility attribute.
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000277 if (RD->getExplicitVisibility())
John McCalle16adc22010-08-04 08:34:44 +0000278 return;
279
280 switch (RD->getTemplateSpecializationKind()) {
281 // We have to disable the optimization if this is an EI definition
282 // because there might be EI declarations in other shared objects.
283 case TSK_ExplicitInstantiationDefinition:
284 case TSK_ExplicitInstantiationDeclaration:
285 return;
286
John McCall5513fce92010-08-05 20:39:18 +0000287 // Every use of a non-template class's type information has to emit it.
John McCalle16adc22010-08-04 08:34:44 +0000288 case TSK_Undeclared:
289 break;
290
John McCall5513fce92010-08-05 20:39:18 +0000291 // In theory, implicit instantiations can ignore the possibility of
292 // an explicit instantiation declaration because there necessarily
293 // must be an EI definition somewhere with default visibility. In
294 // practice, it's possible to have an explicit instantiation for
295 // an arbitrary template class, and linkers aren't necessarily able
296 // to deal with mixed-visibility symbols.
297 case TSK_ExplicitSpecialization:
John McCalle16adc22010-08-04 08:34:44 +0000298 case TSK_ImplicitInstantiation:
John McCallb3732bb2010-08-12 23:36:15 +0000299 if (!CodeGenOpts.HiddenWeakTemplateVTables)
John McCall5513fce92010-08-05 20:39:18 +0000300 return;
John McCalle16adc22010-08-04 08:34:44 +0000301 break;
302 }
303
304 // If there's a key function, there may be translation units
305 // that don't have the key function's definition. But ignore
306 // this if we're emitting RTTI under -fno-rtti.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000307 if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
John McCalle16adc22010-08-04 08:34:44 +0000308 if (Context.getKeyFunction(RD))
309 return;
Anders Carlsson265aa7c2011-01-29 20:24:48 +0000310 }
John McCalle16adc22010-08-04 08:34:44 +0000311
312 // Otherwise, drop the visibility to hidden.
313 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1e879c2011-01-11 21:44:37 +0000314 GV->setUnnamedAddr(true);
John McCalle16adc22010-08-04 08:34:44 +0000315}
316
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000317StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000318 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
319
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000320 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000321 if (!Str.empty())
322 return Str;
323
John McCall5d865c322010-08-31 07:33:07 +0000324 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000325 IdentifierInfo *II = ND->getIdentifier();
326 assert(II && "Attempt to mangle unnamed decl.");
327
328 Str = II->getName();
329 return Str;
330 }
331
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000332 SmallString<256> Buffer;
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000333 llvm::raw_svector_ostream Out(Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000334 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000335 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000336 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000337 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000338 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000339 getCXXABI().getMangleContext().mangleBlock(BD, Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000340 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000341 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000342
343 // Allocate space for the mangled name.
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000344 Out.flush();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000345 size_t Length = Buffer.size();
346 char *Name = MangledNamesAllocator.Allocate<char>(Length);
347 std::copy(Buffer.begin(), Buffer.end(), Name);
348
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000349 Str = StringRef(Name, Length);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000350
351 return Str;
352}
353
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000354void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
355 const BlockDecl *BD) {
356 MangleContext &MangleCtx = getCXXABI().getMangleContext();
357 const Decl *D = GD.getDecl();
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000358 llvm::raw_svector_ostream Out(Buffer.getBuffer());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000359 if (D == 0)
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000360 MangleCtx.mangleGlobalBlock(BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000361 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000362 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000363 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000364 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000365 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000366 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Anders Carlsson635186a2010-06-09 02:36:32 +0000367}
368
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000369llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +0000370 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000371}
372
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000373/// AddGlobalCtor - Add a function to the list that will be called before
374/// main() runs.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000375void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000376 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000377 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000378}
379
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000380/// AddGlobalDtor - Add a function to the list that will be called
381/// when the module is unloaded.
382void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000383 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000384 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
385}
386
387void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
388 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +0000389 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000390 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000391
392 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000393 llvm::StructType *CtorStructTy =
Chris Lattnerece04092012-02-07 00:39:47 +0000394 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000395
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000396 // Construct the constructor and destructor arrays.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000397 SmallVector<llvm::Constant*, 8> Ctors;
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000398 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
Chris Lattner3def9ae2012-02-06 22:16:34 +0000399 llvm::Constant *S[] = {
400 llvm::ConstantInt::get(Int32Ty, I->second, false),
401 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
402 };
Owen Anderson0e0189d2009-07-27 22:29:56 +0000403 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000404 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000405
406 if (!Ctors.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000407 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Andersonc10c8d32009-07-08 19:05:04 +0000408 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000409 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000410 llvm::ConstantArray::get(AT, Ctors),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000411 GlobalName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000412 }
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000413}
414
John McCalld4324142010-02-19 01:32:20 +0000415llvm::GlobalValue::LinkageTypes
416CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000417 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +0000418
Chris Lattner749b8ed2010-06-30 16:58:07 +0000419 if (Linkage == GVA_Internal)
John McCalld4324142010-02-19 01:32:20 +0000420 return llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000421
422 if (D->hasAttr<DLLExportAttr>())
John McCalld4324142010-02-19 01:32:20 +0000423 return llvm::Function::DLLExportLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000424
425 if (D->hasAttr<WeakAttr>())
John McCalld4324142010-02-19 01:32:20 +0000426 return llvm::Function::WeakAnyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000427
428 // In C99 mode, 'inline' functions are guaranteed to have a strong
429 // definition somewhere else, so we can use available_externally linkage.
430 if (Linkage == GVA_C99Inline)
Fariborz Jahanian7cadb2f2011-02-04 00:08:13 +0000431 return llvm::Function::AvailableExternallyLinkage;
John McCall28a5b322011-09-19 18:05:26 +0000432
433 // Note that Apple's kernel linker doesn't support symbol
434 // coalescing, so we need to avoid linkonce and weak linkages there.
435 // Normally, this means we just map to internal, but for explicit
436 // instantiations we'll map to external.
437
Chris Lattner749b8ed2010-06-30 16:58:07 +0000438 // In C++, the compiler has to emit a definition in every translation unit
439 // that references the function. We should use linkonce_odr because
440 // a) if all references in this translation unit are optimized away, we
441 // don't need to codegen it. b) if the function persists, it needs to be
442 // merged with other definitions. c) C++ has the ODR, so we know the
443 // definition is dependable.
444 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000445 return !Context.getLangOpts().AppleKext
Fariborz Jahanianf7f04452011-02-04 00:01:24 +0000446 ? llvm::Function::LinkOnceODRLinkage
447 : llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000448
449 // An explicit instantiation of a template has weak linkage, since
450 // explicit instantiations can occur in multiple translation units
451 // and must all be equivalent. However, we are not allowed to
452 // throw away these explicit instantiations.
453 if (Linkage == GVA_ExplicitTemplateInstantiation)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000454 return !Context.getLangOpts().AppleKext
Fariborz Jahanianf7f04452011-02-04 00:01:24 +0000455 ? llvm::Function::WeakODRLinkage
John McCall28a5b322011-09-19 18:05:26 +0000456 : llvm::Function::ExternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000457
458 // Otherwise, we have strong external linkage.
459 assert(Linkage == GVA_StrongExternal);
460 return llvm::Function::ExternalLinkage;
John McCalld4324142010-02-19 01:32:20 +0000461}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000462
John McCalld4324142010-02-19 01:32:20 +0000463
464/// SetFunctionDefinitionAttributes - Set attributes for a global.
465///
466/// FIXME: This is currently only done for aliases and functions, but not for
467/// variables (these details are set in EmitGlobalVarDefinition for variables).
468void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
469 llvm::GlobalValue *GV) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000470 SetCommonAttributes(D, GV);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000471}
472
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000473void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000474 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000475 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000476 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +0000477 AttributeListType AttributeList;
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000478 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Chris Lattnera2db6f22012-05-28 01:47:53 +0000479 F->setAttributes(llvm::AttrListPtr::get(AttributeList));
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000480 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000481}
482
John McCall9b0a7ce2011-10-02 01:16:38 +0000483/// Determines whether the language options require us to model
484/// unwind exceptions. We treat -fexceptions as mandating this
485/// except under the fragile ObjC ABI with only ObjC exceptions
486/// enabled. This means, for example, that C with -fexceptions
487/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000488static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +0000489 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000490 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +0000491
492 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000493 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +0000494
495 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000496 if (LangOpts.ObjCExceptions) {
497 if (!LangOpts.ObjCNonFragileABI) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +0000498 }
499
500 return true;
501}
502
Daniel Dunbar38932572009-04-14 08:05:55 +0000503void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
504 llvm::Function *F) {
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000505 if (CodeGenOpts.UnwindTables)
506 F->setHasUWTable();
507
David Blaikiebbafb8a2012-03-11 07:00:24 +0000508 if (!hasUnwindExceptions(LangOpts))
Mike Stump11289f42009-09-09 15:08:12 +0000509 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000510
Eli Friedmanc55efe42011-08-22 23:55:33 +0000511 if (D->hasAttr<NakedAttr>()) {
512 // Naked implies noinline: we should not be inlining such functions.
Daniel Dunbar8caf6412010-09-29 18:20:25 +0000513 F->addFnAttr(llvm::Attribute::Naked);
Eli Friedmanc55efe42011-08-22 23:55:33 +0000514 F->addFnAttr(llvm::Attribute::NoInline);
515 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +0000516
Mike Stump3722f582009-08-26 22:31:08 +0000517 if (D->hasAttr<NoInlineAttr>())
Anders Carlssonf96954c2009-02-19 19:22:11 +0000518 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpc5e153c2009-10-05 21:58:44 +0000519
Eli Friedmanc55efe42011-08-22 23:55:33 +0000520 // (noinline wins over always_inline, and we can't specify both in IR)
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +0000521 if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
Eli Friedmanc55efe42011-08-22 23:55:33 +0000522 !F->hasFnAttr(llvm::Attribute::NoInline))
523 F->addFnAttr(llvm::Attribute::AlwaysInline);
524
Benjamin Kramer29c2b432012-05-12 21:10:52 +0000525 // FIXME: Communicate hot and cold attributes to LLVM more directly.
526 if (D->hasAttr<ColdAttr>())
527 F->addFnAttr(llvm::Attribute::OptimizeForSize);
528
Rafael Espindola0ee986c1f2011-01-11 00:26:26 +0000529 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
530 F->setUnnamedAddr(true);
531
David Blaikiebbafb8a2012-03-11 07:00:24 +0000532 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
Anders Carlsson0d82fa62009-11-16 16:56:03 +0000533 F->addFnAttr(llvm::Attribute::StackProtect);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000534 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
Anders Carlsson0d82fa62009-11-16 16:56:03 +0000535 F->addFnAttr(llvm::Attribute::StackProtectReq);
536
David Blaikiebbafb8a2012-03-11 07:00:24 +0000537 if (LangOpts.AddressSanitizer) {
Alexander Potapenkoef41fd32012-02-02 11:49:28 +0000538 // When AddressSanitizer is enabled, set AddressSafety attribute
539 // unless __attribute__((no_address_safety_analysis)) is used.
540 if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
541 F->addFnAttr(llvm::Attribute::AddressSafety);
542 }
543
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000544 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
545 if (alignment)
546 F->setAlignment(alignment);
547
Mike Stump3472ae52009-10-05 22:49:20 +0000548 // C++ ABI requires 2-byte alignment for member functions.
Mike Stump916c0062009-10-05 23:08:21 +0000549 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
550 F->setAlignment(2);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000551}
552
Mike Stump11289f42009-09-09 15:08:12 +0000553void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +0000554 llvm::GlobalValue *GV) {
Anders Carlsson072ef742011-01-29 19:41:00 +0000555 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
556 setGlobalVisibility(GV, ND);
John McCall457a04e2010-10-22 21:05:15 +0000557 else
558 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +0000559
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000560 if (D->hasAttr<UsedAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000561 AddUsedGlobal(GV);
562
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000563 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000564 GV->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000565
566 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +0000567}
568
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000569void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
570 llvm::Function *F,
571 const CGFunctionInfo &FI) {
572 SetLLVMFunctionAttributes(D, FI, F);
573 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +0000574
575 F->setLinkage(llvm::Function::InternalLinkage);
576
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000577 SetCommonAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000578}
579
Anders Carlsson6710c532010-02-06 02:44:09 +0000580void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedman895771a2009-05-26 01:22:57 +0000581 llvm::Function *F,
582 bool IsIncompleteFunction) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +0000583 if (unsigned IID = F->getIntrinsicID()) {
584 // If this is an intrinsic function, set the function's attributes
585 // to the intrinsic's attributes.
586 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
587 return;
588 }
589
Anders Carlsson6710c532010-02-06 02:44:09 +0000590 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
591
Eli Friedman895771a2009-05-26 01:22:57 +0000592 if (!IsIncompleteFunction)
John McCalla729c622012-02-17 03:33:10 +0000593 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +0000594
Daniel Dunbar38932572009-04-14 08:05:55 +0000595 // Only a few attributes are set on declarations; these may later be
596 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +0000597
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000598 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000599 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump11289f42009-09-09 15:08:12 +0000600 } else if (FD->hasAttr<WeakAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000601 FD->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000602 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump11289f42009-09-09 15:08:12 +0000603 // separate linkage types for this.
Daniel Dunbar38932572009-04-14 08:05:55 +0000604 F->setLinkage(llvm::Function::ExternalWeakLinkage);
605 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000606 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallc273f242010-10-30 11:50:40 +0000607
608 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
609 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
610 F->setVisibility(GetLLVMVisibility(LV.visibility()));
611 }
Daniel Dunbar38932572009-04-14 08:05:55 +0000612 }
613
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000614 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000615 F->setSection(SA->getName());
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000616}
617
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000618void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +0000619 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000620 "Only globals with definition can force usage.");
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000621 LLVMUsed.push_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000622}
623
624void CodeGenModule::EmitLLVMUsed() {
625 // Don't create llvm.used if there is no need.
Chris Lattnerf56501c2009-07-17 23:57:13 +0000626 if (LLVMUsed.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000627 return;
628
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000629 // Convert LLVMUsed to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000630 SmallVector<llvm::Constant*, 8> UsedArray;
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000631 UsedArray.resize(LLVMUsed.size());
632 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000633 UsedArray[i] =
634 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Chris Lattner3def9ae2012-02-06 22:16:34 +0000635 Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000636 }
Mike Stump11289f42009-09-09 15:08:12 +0000637
Fariborz Jahanian248c7192009-06-23 21:47:46 +0000638 if (UsedArray.empty())
639 return;
Chris Lattner3def9ae2012-02-06 22:16:34 +0000640 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +0000641
642 llvm::GlobalVariable *GV =
643 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000644 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000645 llvm::ConstantArray::get(ATy, UsedArray),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000646 "llvm.used");
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000647
648 GV->setSection("llvm.metadata");
649}
650
651void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +0000652 // Emit code for any potentially referenced deferred decls. Since a
653 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +0000654 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000655
Anders Carlsson11e51402010-04-17 20:15:18 +0000656 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
657 if (!DeferredVTables.empty()) {
658 const CXXRecordDecl *RD = DeferredVTables.back();
659 DeferredVTables.pop_back();
660 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000661 continue;
662 }
663
Anders Carlssondae1abc2009-05-05 04:44:02 +0000664 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner45470942009-03-21 09:44:56 +0000665 DeferredDeclsToEmit.pop_back();
666
John McCallc2af9392010-05-27 01:45:30 +0000667 // Check to see if we've already emitted this. This is necessary
668 // for a couple of reasons: first, decls can end up in the
669 // deferred-decls queue multiple times, and second, decls can end
670 // up with definitions in unusual ways (e.g. by an extern inline
671 // function acquiring a strong function redefinition). Just
672 // ignore these cases.
673 //
674 // TODO: That said, looking this up multiple times is very wasteful.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000675 StringRef Name = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +0000676 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner45470942009-03-21 09:44:56 +0000677 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump11289f42009-09-09 15:08:12 +0000678
Chris Lattner45470942009-03-21 09:44:56 +0000679 if (!CGRef->isDeclaration())
680 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000681
John McCallc2af9392010-05-27 01:45:30 +0000682 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
683 // purposes an alias counts as a definition.
684 if (isa<llvm::GlobalAlias>(CGRef))
685 continue;
686
Chris Lattner45470942009-03-21 09:44:56 +0000687 // Otherwise, emit the definition and move on to the next one.
688 EmitGlobalDefinition(D);
689 }
Chris Lattnerbed31442007-05-28 01:07:47 +0000690}
Chris Lattner09153c02007-06-22 18:48:09 +0000691
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000692void CodeGenModule::EmitGlobalAnnotations() {
693 if (Annotations.empty())
694 return;
695
696 // Create a new global variable for the ConstantStruct in the Module.
697 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
698 Annotations[0]->getType(), Annotations.size()), Annotations);
699 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
700 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
701 "llvm.global.annotations");
702 gv->setSection(AnnotationSection);
703}
704
705llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
706 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
707 if (i != AnnotationStrings.end())
708 return i->second;
709
710 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +0000711 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000712 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
713 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
714 gv->setSection(AnnotationSection);
715 gv->setUnnamedAddr(true);
716 AnnotationStrings[Str] = gv;
717 return gv;
718}
719
720llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
721 SourceManager &SM = getContext().getSourceManager();
722 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
723 if (PLoc.isValid())
724 return EmitAnnotationString(PLoc.getFilename());
725 return EmitAnnotationString(SM.getBufferName(Loc));
726}
727
728llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
729 SourceManager &SM = getContext().getSourceManager();
730 PresumedLoc PLoc = SM.getPresumedLoc(L);
731 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
732 SM.getExpansionLineNumber(L);
733 return llvm::ConstantInt::get(Int32Ty, LineNo);
734}
735
Mike Stump11289f42009-09-09 15:08:12 +0000736llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +0000737 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000738 SourceLocation L) {
739 // Get the globals for file name, annotation, and the line number.
740 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
741 *UnitGV = EmitAnnotationUnit(L),
742 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +0000743
Daniel Dunbar346892a2009-04-14 22:41:13 +0000744 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +0000745 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000746 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
747 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
748 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
749 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +0000750 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000751 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +0000752}
753
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000754void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
755 llvm::GlobalValue *GV) {
756 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
757 // Get the struct elements for these annotations.
758 for (specific_attr_iterator<AnnotateAttr>
759 ai = D->specific_attr_begin<AnnotateAttr>(),
760 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
761 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
762}
763
Argyrios Kyrtzidisc0279a92010-07-27 22:37:14 +0000764bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000765 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000766 if (LangOpts.EmitAllDecls)
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000767 return false;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000768
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +0000769 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000770}
771
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000772llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
773 const AliasAttr *AA = VD->getAttr<AliasAttr>();
774 assert(AA && "No alias?");
775
Chris Lattner2192fe52011-07-18 04:24:23 +0000776 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000777
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000778 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +0000779 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000780
781 llvm::Constant *Aliasee;
782 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson3c239482011-02-05 04:35:53 +0000783 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
784 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000785 else
John McCall7ec50432010-03-19 23:29:14 +0000786 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000787 llvm::PointerType::getUnqual(DeclTy), 0);
788 if (!Entry) {
789 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
790 F->setLinkage(llvm::Function::ExternalWeakLinkage);
791 WeakRefReferences.insert(F);
792 }
793
794 return Aliasee;
795}
796
Chris Lattnere0be0df2009-05-12 21:21:08 +0000797void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000798 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000799
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000800 // Weak references don't produce any output by themselves.
801 if (Global->hasAttr<WeakRefAttr>())
802 return;
803
Chris Lattner54041692009-03-22 21:47:11 +0000804 // If this is an alias definition (which otherwise looks like a declaration)
805 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000806 if (Global->hasAttr<AliasAttr>())
John McCall7ec50432010-03-19 23:29:14 +0000807 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000808
Peter Collingbournea9455ec2011-10-06 18:29:46 +0000809 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000810 if (LangOpts.CUDA) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +0000811 if (CodeGenOpts.CUDAIsDevice) {
812 if (!Global->hasAttr<CUDADeviceAttr>() &&
813 !Global->hasAttr<CUDAGlobalAttr>() &&
814 !Global->hasAttr<CUDAConstantAttr>() &&
815 !Global->hasAttr<CUDASharedAttr>())
816 return;
817 } else {
818 if (!Global->hasAttr<CUDAHostAttr>() && (
819 Global->hasAttr<CUDADeviceAttr>() ||
820 Global->hasAttr<CUDAConstantAttr>() ||
821 Global->hasAttr<CUDASharedAttr>()))
822 return;
823 }
824 }
825
Chris Lattner45470942009-03-21 09:44:56 +0000826 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar4e004ed2009-03-19 08:27:24 +0000827 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000828 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +0000829 if (!FD->doesThisDeclarationHaveABody()) {
830 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
831 return;
832
833 const FunctionDecl *InlineDefinition = 0;
834 FD->getBody(InlineDefinition);
835
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000836 StringRef MangledName = getMangledName(GD);
Benjamin Kramere894e092012-03-24 18:22:12 +0000837 DeferredDecls.erase(MangledName);
Nick Lewycky26da4dd2011-07-18 05:26:13 +0000838 EmitGlobalDefinition(InlineDefinition);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000839 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +0000840 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000841 } else {
842 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000843 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
844
Douglas Gregor61f6db52010-02-06 05:15:45 +0000845 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorbeecd582009-04-21 17:11:58 +0000846 return;
Nate Begeman8e8d4982008-04-20 06:29:50 +0000847 }
848
Chris Lattner45470942009-03-21 09:44:56 +0000849 // Defer code generation when possible if this is a static definition, inline
850 // function etc. These we only want to emit if they are used.
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000851 if (!MayDeferGeneration(Global)) {
852 // Emit the definition if it can't be deferred.
853 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000854 return;
855 }
John McCall70013b62010-07-15 23:40:35 +0000856
857 // If we're deferring emission of a C++ variable with an
858 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000859 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +0000860 cast<VarDecl>(Global)->hasInit()) {
861 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
862 CXXGlobalInits.push_back(0);
863 }
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000864
865 // If the value has already been used, add it directly to the
866 // DeferredDeclsToEmit list.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000867 StringRef MangledName = getMangledName(GD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000868 if (GetGlobalValue(MangledName))
869 DeferredDeclsToEmit.push_back(GD);
870 else {
871 // Otherwise, remember that we saw a deferred decl with this name. The
872 // first use of the mangled name will cause it to move into
873 // DeferredDeclsToEmit.
874 DeferredDecls[MangledName] = GD;
875 }
Nate Begeman8e8d4982008-04-20 06:29:50 +0000876}
877
Rafael Espindolac5941352011-10-26 20:41:06 +0000878namespace {
879 struct FunctionIsDirectlyRecursive :
880 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
881 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +0000882 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +0000883 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +0000884 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
885 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +0000886 }
887 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
888
889 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +0000890 const FunctionDecl *FD = E->getDirectCallee();
891 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +0000892 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +0000893 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
894 if (Attr && Name == Attr->getLabel()) {
895 Result = true;
896 return false;
897 }
898 unsigned BuiltinID = FD->getBuiltinID();
899 if (!BuiltinID)
Rafael Espindolac5941352011-10-26 20:41:06 +0000900 return true;
Nick Lewycky9ed5b152012-01-18 03:41:19 +0000901 StringRef BuiltinName = BI.GetName(BuiltinID);
902 if (BuiltinName.startswith("__builtin_") &&
903 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +0000904 Result = true;
905 return false;
906 }
907 return true;
908 }
909 };
910}
911
Rafael Espindola4fdc1752011-12-19 14:41:01 +0000912// isTriviallyRecursive - Check if this function calls another
913// decl that, because of the asm attribute or the other decl being a builtin,
914// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +0000915bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +0000916CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
917 StringRef Name;
918 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +0000919 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +0000920 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
921 if (!Attr)
922 return false;
923 Name = Attr->getLabel();
924 } else {
925 Name = FD->getName();
926 }
Rafael Espindolac5941352011-10-26 20:41:06 +0000927
Rafael Espindola4fdc1752011-12-19 14:41:01 +0000928 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
929 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +0000930 return Walker.Result;
931}
932
933bool
934CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
935 if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
936 return true;
Rafael Espindolafffc1ce2011-10-28 20:43:56 +0000937 if (CodeGenOpts.OptimizationLevel == 0 &&
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +0000938 !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +0000939 return false;
940 // PR9614. Avoid cases where the source code is lying to us. An available
941 // externally function should have an equivalent function somewhere else,
942 // but a function that calls itself is clearly not equivalent to the real
943 // implementation.
944 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +0000945 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +0000946}
947
Chris Lattnere0be0df2009-05-12 21:21:08 +0000948void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000949 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000950
Dan Gohman145f3f12010-04-19 16:39:44 +0000951 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +0000952 Context.getSourceManager(),
953 "Generating code for declaration");
954
Douglas Gregora700f682010-07-13 06:02:28 +0000955 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
956 // At -O0, don't generate IR for functions with available_externally
957 // linkage.
Rafael Espindolac5941352011-10-26 20:41:06 +0000958 if (!shouldEmitFunction(Function))
Douglas Gregora700f682010-07-13 06:02:28 +0000959 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +0000960
Douglas Gregora700f682010-07-13 06:02:28 +0000961 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman49a94b12011-05-06 17:27:27 +0000962 // Make sure to emit the definition(s) before we emit the thunks.
963 // This is necessary for the generation of certain thunks.
964 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
965 EmitCXXConstructor(CD, GD.getCtorType());
966 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
967 EmitCXXDestructor(DD, GD.getDtorType());
968 else
969 EmitGlobalFunctionDefinition(GD);
970
Douglas Gregora700f682010-07-13 06:02:28 +0000971 if (Method->isVirtual())
972 getVTables().EmitThunks(GD);
973
Eli Friedman49a94b12011-05-06 17:27:27 +0000974 return;
Douglas Gregora700f682010-07-13 06:02:28 +0000975 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000976
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000977 return EmitGlobalFunctionDefinition(GD);
Douglas Gregora700f682010-07-13 06:02:28 +0000978 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000979
980 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
981 return EmitGlobalVarDefinition(VD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000982
David Blaikie83d382b2011-09-23 05:06:16 +0000983 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +0000984}
985
Chris Lattnerd4808922009-03-22 21:03:39 +0000986/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
987/// module, create and return an llvm Function with the specified type. If there
988/// is something in the module with the specified name, return it potentially
989/// bitcasted to the right type.
990///
991/// If D is non-null, it specifies a decl that correspond to this. This is used
992/// to set the attributes on the function when it is first created.
John McCall7ec50432010-03-19 23:29:14 +0000993llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000994CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +0000995 llvm::Type *Ty,
John McCall31168b02011-06-15 23:02:42 +0000996 GlobalDecl D, bool ForVTable,
997 llvm::Attributes ExtraAttrs) {
Chris Lattnera85d68e2009-03-21 09:25:43 +0000998 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +0000999 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001000 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001001 if (WeakRefReferences.count(Entry)) {
1002 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
1003 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001004 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001005
1006 WeakRefReferences.erase(Entry);
1007 }
1008
Chris Lattnera85d68e2009-03-21 09:25:43 +00001009 if (Entry->getType()->getElementType() == Ty)
1010 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001011
Chris Lattnera85d68e2009-03-21 09:25:43 +00001012 // Make sure the result is of the correct type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001013 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00001014 }
Mike Stump11289f42009-09-09 15:08:12 +00001015
Eli Friedmancc522d92009-11-09 05:07:37 +00001016 // This function doesn't have a complete type (for example, the return
1017 // type is an incomplete struct). Use a fake type instead, and make
1018 // sure not to try to set attributes.
1019 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00001020
Chris Lattner2192fe52011-07-18 04:24:23 +00001021 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00001022 if (isa<llvm::FunctionType>(Ty)) {
1023 FTy = cast<llvm::FunctionType>(Ty);
1024 } else {
John McCall9dc0db22011-05-15 01:53:33 +00001025 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00001026 IsIncompleteFunction = true;
1027 }
Chris Lattner5c740f12010-06-30 19:14:05 +00001028
John McCalld06fb862010-04-28 00:00:30 +00001029 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedmancc522d92009-11-09 05:07:37 +00001030 llvm::Function::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +00001031 MangledName, &getModule());
1032 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedmancc522d92009-11-09 05:07:37 +00001033 if (D.getDecl())
Anders Carlsson6710c532010-02-06 02:44:09 +00001034 SetFunctionAttributes(D, F, IsIncompleteFunction);
John McCall31168b02011-06-15 23:02:42 +00001035 if (ExtraAttrs != llvm::Attribute::None)
1036 F->addFnAttr(ExtraAttrs);
Eli Friedmancc522d92009-11-09 05:07:37 +00001037
Chris Lattner45470942009-03-21 09:44:56 +00001038 // This is the first use or definition of a mangled name. If there is a
1039 // deferred decl with this name, remember that we need to emit it at the end
1040 // of the file.
John McCall7ec50432010-03-19 23:29:14 +00001041 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00001042 if (DDI != DeferredDecls.end()) {
1043 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1044 // list, and remove it from DeferredDecls (since we don't need it anymore).
1045 DeferredDeclsToEmit.push_back(DDI->second);
1046 DeferredDecls.erase(DDI);
John McCall357d0f32010-12-15 04:00:32 +00001047
1048 // Otherwise, there are cases we have to worry about where we're
1049 // using a declaration for which we must emit a definition but where
1050 // we might not find a top-level definition:
1051 // - member functions defined inline in their classes
1052 // - friend functions defined inline in some class
1053 // - special member functions with implicit definitions
1054 // If we ever change our AST traversal to walk into class methods,
1055 // this will be unnecessary.
Anders Carlsson3c239482011-02-05 04:35:53 +00001056 //
1057 // We also don't emit a definition for a function if it's going to be an entry
1058 // in a vtable, unless it's already marked as used.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001059 } else if (getLangOpts().CPlusPlus && D.getDecl()) {
John McCall357d0f32010-12-15 04:00:32 +00001060 // Look for a declaration that's lexically in a record.
1061 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
1062 do {
1063 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Anders Carlsson3c239482011-02-05 04:35:53 +00001064 if (FD->isImplicit() && !ForVTable) {
John McCall357d0f32010-12-15 04:00:32 +00001065 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
Douglas Gregor25756312011-02-09 02:03:05 +00001066 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCall357d0f32010-12-15 04:00:32 +00001067 break;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001068 } else if (FD->doesThisDeclarationHaveABody()) {
Douglas Gregor25756312011-02-09 02:03:05 +00001069 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCall357d0f32010-12-15 04:00:32 +00001070 break;
1071 }
Rafael Espindola70e040d2010-03-02 21:28:26 +00001072 }
Douglas Gregorec9fd132012-01-14 16:38:05 +00001073 FD = FD->getPreviousDecl();
John McCall357d0f32010-12-15 04:00:32 +00001074 } while (FD);
Chris Lattner45470942009-03-21 09:44:56 +00001075 }
Mike Stump11289f42009-09-09 15:08:12 +00001076
John McCalld06fb862010-04-28 00:00:30 +00001077 // Make sure the result is of the requested type.
1078 if (!IsIncompleteFunction) {
1079 assert(F->getType()->getElementType() == Ty);
1080 return F;
1081 }
1082
Chris Lattnera5f58b02011-07-09 17:41:47 +00001083 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00001084 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001085}
1086
Chris Lattnerd4808922009-03-22 21:03:39 +00001087/// GetAddrOfFunction - Return the address of the given function. If Ty is
1088/// non-null, then this function will use the specified type if it has to
1089/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00001090llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00001091 llvm::Type *Ty,
Anders Carlsson3c239482011-02-05 04:35:53 +00001092 bool ForVTable) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001093 // If there was no specific requested type, just convert it now.
1094 if (!Ty)
Anders Carlsson38988d72009-09-10 23:38:47 +00001095 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattner5c740f12010-06-30 19:14:05 +00001096
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001097 StringRef MangledName = getMangledName(GD);
Anders Carlsson3c239482011-02-05 04:35:53 +00001098 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
Chris Lattnerd4808922009-03-22 21:03:39 +00001099}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001100
Chris Lattnerd4808922009-03-22 21:03:39 +00001101/// CreateRuntimeFunction - Create a new runtime function with the specified
1102/// type and name.
1103llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001104CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001105 StringRef Name,
John McCall31168b02011-06-15 23:02:42 +00001106 llvm::Attributes ExtraAttrs) {
1107 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1108 ExtraAttrs);
Chris Lattnerd4808922009-03-22 21:03:39 +00001109}
Daniel Dunbar9c426522008-07-29 23:18:29 +00001110
Richard Smithe070fd22012-02-17 06:48:11 +00001111/// isTypeConstant - Determine whether an object of this type can be emitted
1112/// as a constant.
1113///
1114/// If ExcludeCtor is true, the duration when the object's constructor runs
1115/// will not be considered. The caller will need to verify that the object is
1116/// not written to during its construction.
1117bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1118 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00001119 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00001120
David Blaikiebbafb8a2012-03-11 07:00:24 +00001121 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00001122 if (const CXXRecordDecl *Record
1123 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1124 return ExcludeCtor && !Record->hasMutableFields() &&
1125 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00001126 }
Richard Smithe070fd22012-02-17 06:48:11 +00001127
Eli Friedmanb095e152009-12-11 21:23:03 +00001128 return true;
1129}
1130
Chris Lattnerd4808922009-03-22 21:03:39 +00001131/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1132/// create and return an llvm GlobalVariable with the specified type. If there
1133/// is something in the module with the specified name, return it potentially
1134/// bitcasted to the right type.
1135///
1136/// If D is non-null, it specifies a decl that correspond to this. This is used
1137/// to set the attributes on the global when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001138llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001139CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00001140 llvm::PointerType *Ty,
Rafael Espindolad661a852011-01-18 21:07:57 +00001141 const VarDecl *D,
1142 bool UnnamedAddr) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00001143 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001144 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00001145 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001146 if (WeakRefReferences.count(Entry)) {
1147 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001148 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001149
1150 WeakRefReferences.erase(Entry);
1151 }
1152
Rafael Espindolad661a852011-01-18 21:07:57 +00001153 if (UnnamedAddr)
1154 Entry->setUnnamedAddr(true);
1155
Chris Lattnerd4808922009-03-22 21:03:39 +00001156 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00001157 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001158
Chris Lattner3bfce182009-03-21 08:03:33 +00001159 // Make sure the result is of the correct type.
Owen Andersonade90fd2009-07-29 18:54:39 +00001160 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00001161 }
Mike Stump11289f42009-09-09 15:08:12 +00001162
Chris Lattner45470942009-03-21 09:44:56 +00001163 // This is the first use or definition of a mangled name. If there is a
1164 // deferred decl with this name, remember that we need to emit it at the end
1165 // of the file.
John McCall7ec50432010-03-19 23:29:14 +00001166 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00001167 if (DDI != DeferredDecls.end()) {
1168 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1169 // list, and remove it from DeferredDecls (since we don't need it anymore).
1170 DeferredDeclsToEmit.push_back(DDI->second);
1171 DeferredDecls.erase(DDI);
1172 }
Mike Stump11289f42009-09-09 15:08:12 +00001173
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001174 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
Mike Stump11289f42009-09-09 15:08:12 +00001175 llvm::GlobalVariable *GV =
1176 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner3bfce182009-03-21 08:03:33 +00001177 llvm::GlobalValue::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +00001178 0, MangledName, 0,
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001179 false, AddrSpace);
Chris Lattner3bfce182009-03-21 08:03:33 +00001180
1181 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00001182 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +00001183 // FIXME: This code is overly simple and should be merged with other global
1184 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00001185 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00001186
John McCall37bb6c92010-10-29 22:22:43 +00001187 // Set linkage and visibility in case we never see a definition.
John McCallc273f242010-10-30 11:50:40 +00001188 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1189 if (LV.linkage() != ExternalLinkage) {
John McCall83779672011-02-19 02:53:41 +00001190 // Don't set internal linkage on declarations.
John McCall37bb6c92010-10-29 22:22:43 +00001191 } else {
1192 if (D->hasAttr<DLLImportAttr>())
1193 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001194 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
John McCall37bb6c92010-10-29 22:22:43 +00001195 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner3bfce182009-03-21 08:03:33 +00001196
John McCallc273f242010-10-30 11:50:40 +00001197 // Set visibility on a declaration only if it's explicit.
1198 if (LV.visibilityExplicit())
1199 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall37bb6c92010-10-29 22:22:43 +00001200 }
Eli Friedman4f856742009-04-19 21:05:03 +00001201
1202 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattnerd4808922009-03-22 21:03:39 +00001203 }
Mike Stump11289f42009-09-09 15:08:12 +00001204
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001205 if (AddrSpace != Ty->getAddressSpace())
1206 return llvm::ConstantExpr::getBitCast(GV, Ty);
1207 else
1208 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001209}
1210
Chris Lattnerd4808922009-03-22 21:03:39 +00001211
Anders Carlssonda80af32011-01-29 18:20:20 +00001212llvm::GlobalVariable *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001213CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2192fe52011-07-18 04:24:23 +00001214 llvm::Type *Ty,
Anders Carlssonda80af32011-01-29 18:20:20 +00001215 llvm::GlobalValue::LinkageTypes Linkage) {
1216 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1217 llvm::GlobalVariable *OldGV = 0;
1218
1219
1220 if (GV) {
1221 // Check if the variable has the right type.
1222 if (GV->getType()->getElementType() == Ty)
1223 return GV;
1224
1225 // Because C++ name mangling, the only way we can end up with an already
1226 // existing global with the same name is if it has been declared extern "C".
Anders Carlsson93be9a92011-01-29 18:25:07 +00001227 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00001228 OldGV = GV;
1229 }
1230
1231 // Create a new variable.
1232 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1233 Linkage, 0, Name);
1234
1235 if (OldGV) {
1236 // Replace occurrences of the old variable if needed.
1237 GV->takeName(OldGV);
1238
1239 if (!OldGV->use_empty()) {
1240 llvm::Constant *NewPtrForOldDecl =
1241 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1242 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1243 }
1244
1245 OldGV->eraseFromParent();
1246 }
1247
1248 return GV;
1249}
1250
Chris Lattnerd4808922009-03-22 21:03:39 +00001251/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1252/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00001253/// then it will be created with the specified type instead of whatever the
Chris Lattnerd4808922009-03-22 21:03:39 +00001254/// normal requested type would be.
1255llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2192fe52011-07-18 04:24:23 +00001256 llvm::Type *Ty) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001257 assert(D->hasGlobalStorage() && "Not a global variable");
1258 QualType ASTTy = D->getType();
1259 if (Ty == 0)
1260 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00001261
Chris Lattner2192fe52011-07-18 04:24:23 +00001262 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001263 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00001264
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001265 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001266 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001267}
1268
1269/// CreateRuntimeVariable - Create a new runtime global variable with the
1270/// specified type and name.
1271llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001272CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001273 StringRef Name) {
John McCall31996342011-04-07 08:22:57 +00001274 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
Rafael Espindolad661a852011-01-18 21:07:57 +00001275 true);
Chris Lattnerd4808922009-03-22 21:03:39 +00001276}
1277
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001278void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1279 assert(!D->getInit() && "Cannot emit definite definitions here!");
1280
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001281 if (MayDeferGeneration(D)) {
1282 // If we have not seen a reference to this variable yet, place it
1283 // into the deferred declarations table to be emitted if needed
1284 // later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001285 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001286 if (!GetGlobalValue(MangledName)) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001287 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001288 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001289 }
1290 }
1291
1292 // The tentative definition is the only definition.
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001293 EmitGlobalVarDefinition(D);
1294}
1295
Douglas Gregor88d292c2010-05-13 16:44:06 +00001296void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1297 if (DefinitionRequired)
1298 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1299}
1300
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001301llvm::GlobalVariable::LinkageTypes
Anders Carlsson11e51402010-04-17 20:15:18 +00001302CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Eli Friedman300f55d2011-06-10 21:53:06 +00001303 if (RD->getLinkage() != ExternalLinkage)
Douglas Gregor2a34df32010-01-06 22:00:56 +00001304 return llvm::GlobalVariable::InternalLinkage;
1305
1306 if (const CXXMethodDecl *KeyFunction
1307 = RD->getASTContext().getKeyFunction(RD)) {
1308 // If this class has a key function, use that to determine the linkage of
1309 // the vtable.
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001310 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001311 if (KeyFunction->hasBody(Def))
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001312 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregor2a34df32010-01-06 22:00:56 +00001313
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001314 switch (KeyFunction->getTemplateSpecializationKind()) {
1315 case TSK_Undeclared:
1316 case TSK_ExplicitSpecialization:
Anders Carlssona03f3a82011-01-30 20:45:54 +00001317 // When compiling with optimizations turned on, we emit all vtables,
1318 // even if the key function is not defined in the current translation
1319 // unit. If this is the case, use available_externally linkage.
1320 if (!Def && CodeGenOpts.OptimizationLevel)
1321 return llvm::GlobalVariable::AvailableExternallyLinkage;
1322
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001323 if (KeyFunction->isInlined())
David Blaikiebbafb8a2012-03-11 07:00:24 +00001324 return !Context.getLangOpts().AppleKext ?
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00001325 llvm::GlobalVariable::LinkOnceODRLinkage :
1326 llvm::Function::InternalLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001327
1328 return llvm::GlobalVariable::ExternalLinkage;
1329
1330 case TSK_ImplicitInstantiation:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001331 return !Context.getLangOpts().AppleKext ?
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00001332 llvm::GlobalVariable::LinkOnceODRLinkage :
1333 llvm::Function::InternalLinkage;
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001334
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001335 case TSK_ExplicitInstantiationDefinition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001336 return !Context.getLangOpts().AppleKext ?
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00001337 llvm::GlobalVariable::WeakODRLinkage :
1338 llvm::Function::InternalLinkage;
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001339
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001340 case TSK_ExplicitInstantiationDeclaration:
1341 // FIXME: Use available_externally linkage. However, this currently
1342 // breaks LLVM's build due to undefined symbols.
1343 // return llvm::GlobalVariable::AvailableExternallyLinkage;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001344 return !Context.getLangOpts().AppleKext ?
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00001345 llvm::GlobalVariable::LinkOnceODRLinkage :
1346 llvm::Function::InternalLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001347 }
Douglas Gregor2a34df32010-01-06 22:00:56 +00001348 }
1349
David Blaikiebbafb8a2012-03-11 07:00:24 +00001350 if (Context.getLangOpts().AppleKext)
Fariborz Jahaniane28342c2011-02-04 00:32:39 +00001351 return llvm::Function::InternalLinkage;
1352
Douglas Gregor2a34df32010-01-06 22:00:56 +00001353 switch (RD->getTemplateSpecializationKind()) {
1354 case TSK_Undeclared:
1355 case TSK_ExplicitSpecialization:
1356 case TSK_ImplicitInstantiation:
Douglas Gregor2a34df32010-01-06 22:00:56 +00001357 // FIXME: Use available_externally linkage. However, this currently
1358 // breaks LLVM's build due to undefined symbols.
1359 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00001360 case TSK_ExplicitInstantiationDeclaration:
Fariborz Jahaniane28342c2011-02-04 00:32:39 +00001361 return llvm::GlobalVariable::LinkOnceODRLinkage;
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00001362
1363 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahaniane28342c2011-02-04 00:32:39 +00001364 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001365 }
David Blaikiee4d798f2012-01-20 21:50:17 +00001366
1367 llvm_unreachable("Invalid TemplateSpecializationKind!");
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001368}
1369
Chris Lattner2192fe52011-07-18 04:24:23 +00001370CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck9a648692011-01-18 02:01:14 +00001371 return Context.toCharUnitsFromBits(
1372 TheTargetData.getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00001373}
1374
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001375llvm::Constant *
1376CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1377 const Expr *rawInit) {
1378 ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
1379 if (const ExprWithCleanups *withCleanups =
1380 dyn_cast<ExprWithCleanups>(rawInit)) {
1381 cleanups = withCleanups->getObjects();
1382 rawInit = withCleanups->getSubExpr();
1383 }
1384
1385 const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
1386 if (!init || !init->initializesStdInitializerList() ||
1387 init->getNumInits() == 0)
1388 return 0;
1389
1390 ASTContext &ctx = getContext();
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001391 unsigned numInits = init->getNumInits();
Sebastian Redla235e2d2012-02-27 23:20:01 +00001392 // FIXME: This check is here because we would otherwise silently miscompile
1393 // nested global std::initializer_lists. Better would be to have a real
1394 // implementation.
1395 for (unsigned i = 0; i < numInits; ++i) {
1396 const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1397 if (inner && inner->initializesStdInitializerList()) {
1398 ErrorUnsupported(inner, "nested global std::initializer_list");
1399 return 0;
1400 }
1401 }
1402
1403 // Synthesize a fake VarDecl for the array and initialize that.
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001404 QualType elementType = init->getInit(0)->getType();
1405 llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
1406 QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
1407 ArrayType::Normal, 0);
1408
1409 IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
1410 TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
1411 arrayType, D->getLocation());
1412 VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
1413 D->getDeclContext()),
1414 D->getLocStart(), D->getLocation(),
1415 name, arrayType, sourceInfo,
1416 SC_Static, SC_Static);
1417
1418 // Now clone the InitListExpr to initialize the array instead.
1419 // Incredible hack: we want to use the existing InitListExpr here, so we need
1420 // to tell it that it no longer initializes a std::initializer_list.
1421 Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(),
1422 const_cast<InitListExpr*>(init)->getInits(),
1423 init->getNumInits(),
1424 init->getRBraceLoc());
1425 arrayInit->setType(arrayType);
1426
1427 if (!cleanups.empty())
1428 arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
1429
1430 backingArray->setInit(arrayInit);
1431
1432 // Emit the definition of the array.
1433 EmitGlobalVarDefinition(backingArray);
1434
1435 // Inspect the initializer list to validate it and determine its type.
1436 // FIXME: doing this every time is probably inefficient; caching would be nice
1437 RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
1438 RecordDecl::field_iterator field = record->field_begin();
1439 if (field == record->field_end()) {
1440 ErrorUnsupported(D, "weird std::initializer_list");
1441 return 0;
1442 }
1443 QualType elementPtr = ctx.getPointerType(elementType.withConst());
1444 // Start pointer.
1445 if (!ctx.hasSameType(field->getType(), elementPtr)) {
1446 ErrorUnsupported(D, "weird std::initializer_list");
1447 return 0;
1448 }
1449 ++field;
1450 if (field == record->field_end()) {
1451 ErrorUnsupported(D, "weird std::initializer_list");
1452 return 0;
1453 }
1454 bool isStartEnd = false;
1455 if (ctx.hasSameType(field->getType(), elementPtr)) {
1456 // End pointer.
1457 isStartEnd = true;
1458 } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
1459 ErrorUnsupported(D, "weird std::initializer_list");
1460 return 0;
1461 }
1462
1463 // Now build an APValue representing the std::initializer_list.
1464 APValue initListValue(APValue::UninitStruct(), 0, 2);
1465 APValue &startField = initListValue.getStructField(0);
1466 APValue::LValuePathEntry startOffsetPathEntry;
1467 startOffsetPathEntry.ArrayIndex = 0;
1468 startField = APValue(APValue::LValueBase(backingArray),
1469 CharUnits::fromQuantity(0),
1470 llvm::makeArrayRef(startOffsetPathEntry),
1471 /*IsOnePastTheEnd=*/false, 0);
1472
1473 if (isStartEnd) {
1474 APValue &endField = initListValue.getStructField(1);
1475 APValue::LValuePathEntry endOffsetPathEntry;
1476 endOffsetPathEntry.ArrayIndex = numInits;
1477 endField = APValue(APValue::LValueBase(backingArray),
1478 ctx.getTypeSizeInChars(elementType) * numInits,
1479 llvm::makeArrayRef(endOffsetPathEntry),
1480 /*IsOnePastTheEnd=*/true, 0);
1481 } else {
1482 APValue &sizeField = initListValue.getStructField(1);
1483 sizeField = APValue(llvm::APSInt(numElements));
1484 }
1485
1486 // Emit the constant for the initializer_list.
Richard Smithbc6387672012-03-02 23:27:11 +00001487 llvm::Constant *llvmInit =
1488 EmitConstantValueForMemory(initListValue, D->getType());
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001489 assert(llvmInit && "failed to initialize as constant");
1490 return llvmInit;
1491}
1492
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001493unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1494 unsigned AddrSpace) {
1495 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1496 if (D->hasAttr<CUDAConstantAttr>())
1497 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1498 else if (D->hasAttr<CUDASharedAttr>())
1499 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1500 else
1501 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1502 }
1503
1504 return AddrSpace;
1505}
1506
Daniel Dunbar9c426522008-07-29 23:18:29 +00001507void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001508 llvm::Constant *Init = 0;
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001509 QualType ASTTy = D->getType();
Richard Smith6331c402012-02-13 22:16:19 +00001510 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1511 bool NeedsGlobalCtor = false;
1512 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00001513
Richard Smithdafff942012-01-14 04:30:29 +00001514 const VarDecl *InitDecl;
1515 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001516
Anders Carlssonca4a5452010-01-26 17:43:42 +00001517 if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00001518 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001519 // implicitly initialized with { 0 }.
1520 //
1521 // Note that tentative definitions are only emitted at the end of
1522 // a translation unit, so they should never have incomplete
1523 // type. In addition, EmitTentativeDefinition makes sure that we
1524 // never attempt to emit a tentative definition if a real one
1525 // exists. A use may still exists, however, so we still may need
1526 // to do a RAUW.
1527 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00001528 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001529 } else {
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001530 // If this is a std::initializer_list, emit the special initializer.
1531 Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
1532 // An empty init list will perform zero-initialization, which happens
1533 // to be exactly what we want.
1534 // FIXME: It does so in a global constructor, which is *not* what we
1535 // want.
1536
1537 if (!Init)
1538 Init = EmitConstantInit(*InitDecl);
Eli Friedman719ed1a2009-02-20 01:18:21 +00001539 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00001540 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00001541 if (D->getType()->isReferenceType())
1542 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00001543
David Blaikiebbafb8a2012-03-11 07:00:24 +00001544 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001545 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00001546 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001547 } else {
1548 ErrorUnsupported(D, "static initializer");
1549 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1550 }
John McCall70013b62010-07-15 23:40:35 +00001551 } else {
1552 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00001553 // initializer position (just in case this entry was delayed) if we
1554 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001555 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00001556 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00001557 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001558 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001559
Chris Lattner2192fe52011-07-18 04:24:23 +00001560 llvm::Type* InitType = Init->getType();
Chris Lattner149927c2009-03-21 09:16:30 +00001561 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump11289f42009-09-09 15:08:12 +00001562
Chris Lattner149927c2009-03-21 09:16:30 +00001563 // Strip off a bitcast if we got one back.
1564 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00001565 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1566 // all zero index gep.
1567 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00001568 Entry = CE->getOperand(0);
1569 }
Mike Stump11289f42009-09-09 15:08:12 +00001570
Chris Lattner149927c2009-03-21 09:16:30 +00001571 // Entry is now either a Function or GlobalVariable.
1572 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001573
Chris Lattner149927c2009-03-21 09:16:30 +00001574 // We have a definition after a declaration with the wrong type.
1575 // We must make a new GlobalVariable* and update everything that used OldGV
1576 // (a declaration or tentative definition) with the new GlobalVariable*
1577 // (which will be a definition).
1578 //
1579 // This happens if there is a prototype for a global (e.g.
1580 // "extern int x[];") and then a definition of a different type (e.g.
1581 // "int x[10];"). This also happens when an initializer has a different type
1582 // from the type of the global (this happens with unions).
Chris Lattner149927c2009-03-21 09:16:30 +00001583 if (GV == 0 ||
1584 GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001585 GV->getType()->getAddressSpace() !=
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001586 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump11289f42009-09-09 15:08:12 +00001587
John McCall7ec50432010-03-19 23:29:14 +00001588 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001589 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00001590
Chris Lattner149927c2009-03-21 09:16:30 +00001591 // Make a new global with the correct type, this is now guaranteed to work.
1592 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattnera85d68e2009-03-21 09:25:43 +00001593
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001594 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00001595 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001596 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00001597 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001598
1599 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00001600 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001601 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00001602
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001603 if (D->hasAttr<AnnotateAttr>())
1604 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00001605
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001606 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001607
1608 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00001609 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1610 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00001611
Ken Dyck160146e2010-01-27 17:10:57 +00001612 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00001613
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001614 // Set the llvm linkage type as appropriate.
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001615 llvm::GlobalValue::LinkageTypes Linkage =
1616 GetLLVMLinkageVarDefinition(D, GV);
1617 GV->setLinkage(Linkage);
1618 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnerf49573d2009-08-05 05:20:29 +00001619 // common vars aren't constant even if declared const.
1620 GV->setConstant(false);
Daniel Dunbard272cca2009-04-10 20:26:50 +00001621
Daniel Dunbar38932572009-04-14 08:05:55 +00001622 SetCommonAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001623
John McCallcdf7ef52010-11-06 09:44:32 +00001624 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00001625 if (NeedsGlobalCtor || NeedsGlobalDtor)
1626 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00001627
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001628 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00001629 if (CGDebugInfo *DI = getModuleDebugInfo())
Alexey Samsonov74a38682012-05-04 07:39:27 +00001630 if (getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo)
1631 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001632}
Chris Lattner09153c02007-06-22 18:48:09 +00001633
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001634llvm::GlobalValue::LinkageTypes
1635CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1636 llvm::GlobalVariable *GV) {
1637 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1638 if (Linkage == GVA_Internal)
1639 return llvm::Function::InternalLinkage;
1640 else if (D->hasAttr<DLLImportAttr>())
1641 return llvm::Function::DLLImportLinkage;
1642 else if (D->hasAttr<DLLExportAttr>())
1643 return llvm::Function::DLLExportLinkage;
1644 else if (D->hasAttr<WeakAttr>()) {
1645 if (GV->isConstant())
1646 return llvm::GlobalVariable::WeakODRLinkage;
1647 else
1648 return llvm::GlobalVariable::WeakAnyLinkage;
1649 } else if (Linkage == GVA_TemplateInstantiation ||
1650 Linkage == GVA_ExplicitTemplateInstantiation)
John McCalla97f3292011-04-12 01:46:54 +00001651 return llvm::GlobalVariable::WeakODRLinkage;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001652 else if (!getLangOpts().CPlusPlus &&
Eric Christopher8a2ee392010-12-02 02:45:55 +00001653 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1654 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001655 !D->hasExternalStorage() && !D->getInit() &&
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00001656 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1657 !D->getAttr<WeakImportAttr>()) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001658 // Thread local vars aren't considered common linkage.
1659 return llvm::GlobalVariable::CommonLinkage;
1660 }
1661 return llvm::GlobalVariable::ExternalLinkage;
1662}
1663
Chris Lattner36797ab2009-05-05 06:16:31 +00001664/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1665/// implement a function with no prototype, e.g. "int foo() {}". If there are
1666/// existing call uses of the old function in the module, this adjusts them to
1667/// call the new function directly.
1668///
1669/// This is not just a cleanup: the always_inline pass requires direct calls to
1670/// functions to be able to inline them. If there is a bitcast in the way, it
1671/// won't inline them. Instcombine normally deletes these calls, but it isn't
1672/// run at -O0.
1673static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1674 llvm::Function *NewFn) {
1675 // If we're redefining a global as a function, don't transform it.
1676 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1677 if (OldFn == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +00001678
Chris Lattner2192fe52011-07-18 04:24:23 +00001679 llvm::Type *NewRetTy = NewFn->getReturnType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001680 SmallVector<llvm::Value*, 4> ArgList;
Chris Lattner36797ab2009-05-05 06:16:31 +00001681
1682 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001683 UI != E; ) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001684 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001685 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1686 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greif79ac9ed2010-07-28 09:19:33 +00001687 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
Gabor Greifd394aec2010-04-10 03:45:50 +00001688 llvm::CallSite CS(CI);
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001689 if (!CI || !CS.isCallee(I)) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001690
Chris Lattner36797ab2009-05-05 06:16:31 +00001691 // If the return types don't match exactly, and if the call isn't dead, then
1692 // we can't transform this call.
1693 if (CI->getType() != NewRetTy && !CI->use_empty())
1694 continue;
1695
John McCall625ed882011-08-03 00:43:55 +00001696 // Get the attribute list.
1697 llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
1698 llvm::AttrListPtr AttrList = CI->getAttributes();
1699
1700 // Get any return attributes.
1701 llvm::Attributes RAttrs = AttrList.getRetAttributes();
1702
1703 // Add the return attributes.
1704 if (RAttrs)
1705 AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
1706
Chris Lattner36797ab2009-05-05 06:16:31 +00001707 // If the function was passed too few arguments, don't transform. If extra
1708 // arguments were passed, we silently drop them. If any of the types
1709 // mismatch, we don't transform.
1710 unsigned ArgNo = 0;
1711 bool DontTransform = false;
1712 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1713 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greifd394aec2010-04-10 03:45:50 +00001714 if (CS.arg_size() == ArgNo ||
1715 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001716 DontTransform = true;
1717 break;
1718 }
John McCall625ed882011-08-03 00:43:55 +00001719
1720 // Add any parameter attributes.
1721 if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
1722 AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
Chris Lattner36797ab2009-05-05 06:16:31 +00001723 }
1724 if (DontTransform)
1725 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001726
John McCall625ed882011-08-03 00:43:55 +00001727 if (llvm::Attributes FnAttrs = AttrList.getFnAttributes())
1728 AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
1729
Chris Lattner36797ab2009-05-05 06:16:31 +00001730 // Okay, we can transform this. Create the new call instruction and copy
1731 // over the required information.
Gabor Greifd0ef1342010-04-10 02:56:12 +00001732 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Jay Foad5bd375a2011-07-15 08:37:34 +00001733 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
Chris Lattner36797ab2009-05-05 06:16:31 +00001734 ArgList.clear();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00001735 if (!NewCall->getType()->isVoidTy())
Chris Lattner36797ab2009-05-05 06:16:31 +00001736 NewCall->takeName(CI);
Chris Lattnera2db6f22012-05-28 01:47:53 +00001737 NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec));
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001738 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattner36797ab2009-05-05 06:16:31 +00001739
1740 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner734351d2009-10-14 05:49:21 +00001741 if (!CI->use_empty())
1742 CI->replaceAllUsesWith(NewCall);
Devang Patel74684892009-10-13 17:02:04 +00001743
Chris Lattnere675d0f2010-04-01 06:31:43 +00001744 // Copy debug location attached to CI.
1745 if (!CI->getDebugLoc().isUnknown())
1746 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattner36797ab2009-05-05 06:16:31 +00001747 CI->eraseFromParent();
1748 }
1749}
1750
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00001751void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
1752 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
1753 // If we have a definition, this might be a deferred decl. If the
1754 // instantiation is explicit, make sure we emit it at the end.
1755 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
1756 GetAddrOfGlobalVar(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00001757}
Daniel Dunbar9c426522008-07-29 23:18:29 +00001758
Chris Lattnere0be0df2009-05-12 21:21:08 +00001759void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnere0be0df2009-05-12 21:21:08 +00001760 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00001761
John McCall46288ef2011-03-09 08:12:35 +00001762 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00001763 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1764 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00001765
Chris Lattnereb7466d2009-05-12 20:58:15 +00001766 // Get or create the prototype for the function.
Chris Lattnere0be0df2009-05-12 21:21:08 +00001767 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001768
Chris Lattnera85d68e2009-03-21 09:25:43 +00001769 // Strip off a bitcast if we got one back.
1770 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1771 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1772 Entry = CE->getOperand(0);
1773 }
Mike Stump11289f42009-09-09 15:08:12 +00001774
1775
Chris Lattnera85d68e2009-03-21 09:25:43 +00001776 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001777 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001778
Daniel Dunbar99d28352009-03-09 23:53:08 +00001779 // If the types mismatch then we have to rewrite the definition.
Chris Lattner36797ab2009-05-05 06:16:31 +00001780 assert(OldFn->isDeclaration() &&
Chris Lattnera85d68e2009-03-21 09:25:43 +00001781 "Shouldn't replace non-declaration");
Chris Lattner832323e2009-03-21 08:53:37 +00001782
Chris Lattner5eaee562009-03-21 08:38:50 +00001783 // F is the Function* for the one with the wrong type, we must make a new
1784 // Function* and update everything that used F (a declaration) with the new
1785 // Function* (which will be a definition).
1786 //
1787 // This happens if there is a prototype for a function
1788 // (e.g. "int f()") and then a definition of a different type
John McCall7ec50432010-03-19 23:29:14 +00001789 // (e.g. "int f(int x)"). Move the old function aside so that it
1790 // doesn't interfere with GetAddrOfFunction.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001791 OldFn->setName(StringRef());
Chris Lattnere0be0df2009-05-12 21:21:08 +00001792 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump11289f42009-09-09 15:08:12 +00001793
Chris Lattner36797ab2009-05-05 06:16:31 +00001794 // If this is an implementation of a function without a prototype, try to
1795 // replace any existing uses of the function (which may be calls) with uses
1796 // of the new function
Chris Lattnereb7466d2009-05-12 20:58:15 +00001797 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001798 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattnereb7466d2009-05-12 20:58:15 +00001799 OldFn->removeDeadConstantUsers();
1800 }
Mike Stump11289f42009-09-09 15:08:12 +00001801
Chris Lattner5eaee562009-03-21 08:38:50 +00001802 // Replace uses of F with the Function we will endow with a body.
Chris Lattner36797ab2009-05-05 06:16:31 +00001803 if (!Entry->use_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00001804 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001805 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattner36797ab2009-05-05 06:16:31 +00001806 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1807 }
Mike Stump11289f42009-09-09 15:08:12 +00001808
Chris Lattner5eaee562009-03-21 08:38:50 +00001809 // Ok, delete the old function now, which is dead.
Chris Lattner36797ab2009-05-05 06:16:31 +00001810 OldFn->eraseFromParent();
Mike Stump11289f42009-09-09 15:08:12 +00001811
Chris Lattnera85d68e2009-03-21 09:25:43 +00001812 Entry = NewFn;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001813 }
Mike Stump11289f42009-09-09 15:08:12 +00001814
John McCall8e7cb6d2010-11-02 21:04:24 +00001815 // We need to set linkage and visibility on the function before
1816 // generating code for it because various parts of IR generation
1817 // want to propagate this information down (e.g. to local static
1818 // declarations).
Chris Lattnera85d68e2009-03-21 09:25:43 +00001819 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall7cb02202010-05-25 04:30:21 +00001820 setFunctionLinkage(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001821
John McCall8e7cb6d2010-11-02 21:04:24 +00001822 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlssonc6a47892011-01-29 19:39:23 +00001823 setGlobalVisibility(Fn, D);
John McCall8e7cb6d2010-11-02 21:04:24 +00001824
John McCalla738c252011-03-09 04:27:21 +00001825 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001826
Daniel Dunbar38932572009-04-14 08:05:55 +00001827 SetFunctionDefinitionAttributes(D, Fn);
1828 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00001829
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001830 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001831 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001832 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001833 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001834 if (D->hasAttr<AnnotateAttr>())
1835 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001836}
1837
John McCall7ec50432010-03-19 23:29:14 +00001838void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1839 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001840 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00001841 assert(AA && "Not an alias?");
1842
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001843 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00001844
John McCall7ec50432010-03-19 23:29:14 +00001845 // If there is a definition in the module, then it wins over the alias.
1846 // This is dubious, but allow it to be safe. Just ignore the alias.
1847 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1848 if (Entry && !Entry->isDeclaration())
1849 return;
1850
Chris Lattner2192fe52011-07-18 04:24:23 +00001851 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00001852
1853 // Create a reference to the named value. This ensures that it is emitted
1854 // if a deferred decl.
1855 llvm::Constant *Aliasee;
1856 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson3c239482011-02-05 04:35:53 +00001857 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1858 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00001859 else
John McCall7ec50432010-03-19 23:29:14 +00001860 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson9793f0e2009-07-29 22:16:19 +00001861 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattner54041692009-03-22 21:47:11 +00001862
1863 // Create the new alias itself, but don't set a name yet.
Mike Stump11289f42009-09-09 15:08:12 +00001864 llvm::GlobalValue *GA =
Chris Lattner54041692009-03-22 21:47:11 +00001865 new llvm::GlobalAlias(Aliasee->getType(),
1866 llvm::Function::ExternalLinkage,
1867 "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00001868
Chris Lattner54041692009-03-22 21:47:11 +00001869 if (Entry) {
John McCall7ec50432010-03-19 23:29:14 +00001870 assert(Entry->isDeclaration());
1871
Chris Lattner54041692009-03-22 21:47:11 +00001872 // If there is a declaration in the module, then we had an extern followed
1873 // by the alias, as in:
1874 // extern int test6();
1875 // ...
1876 // int test6() __attribute__((alias("test7")));
1877 //
1878 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00001879 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001880
Owen Andersonade90fd2009-07-29 18:54:39 +00001881 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00001882 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00001883 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00001884 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00001885 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00001886 }
Mike Stump11289f42009-09-09 15:08:12 +00001887
Daniel Dunbar38932572009-04-14 08:05:55 +00001888 // Set attributes which are particular to an alias; this is a
1889 // specialization of the attributes which may be set on a global
1890 // variable/function.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001891 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001892 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1893 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001894 if (FD->hasBody())
Daniel Dunbar38932572009-04-14 08:05:55 +00001895 GA->setLinkage(llvm::Function::DLLExportLinkage);
1896 } else {
1897 GA->setLinkage(llvm::Function::DLLExportLinkage);
1898 }
Mike Stump11289f42009-09-09 15:08:12 +00001899 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindolac18086a2010-02-23 22:00:30 +00001900 D->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001901 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001902 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1903 }
1904
1905 SetCommonAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00001906}
1907
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00001908llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00001909 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00001910 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00001911 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00001912}
Chris Lattner1eec6602007-08-31 04:31:45 +00001913
Daniel Dunbar64509b22009-07-23 22:52:48 +00001914static llvm::StringMapEntry<llvm::Constant*> &
1915GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1916 const StringLiteral *Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001917 bool TargetIsLSB,
Daniel Dunbar64509b22009-07-23 22:52:48 +00001918 bool &IsUTF16,
1919 unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001920 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001921 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00001922
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001923 // Check for simple case.
1924 if (!Literal->containsNonAsciiOrNull()) {
1925 StringLength = NumBytes;
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001926 return Map.GetOrCreateValue(String);
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001927 }
1928
Bill Wendling82b87f12012-03-30 00:26:17 +00001929 // Otherwise, convert the UTF8 literals into a string of shorts.
1930 IsUTF16 = true;
1931
1932 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001933 const UTF8 *FromPtr = (UTF8 *)String.data();
Daniel Dunbar64509b22009-07-23 22:52:48 +00001934 UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00001935
Fariborz Jahanian535618b2010-09-07 19:57:04 +00001936 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1937 &ToPtr, ToPtr + NumBytes,
1938 strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00001939
Daniel Dunbar91ade142009-07-23 23:41:22 +00001940 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00001941 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00001942
Bill Wendling82b87f12012-03-30 00:26:17 +00001943 // Add an explicit null.
1944 *ToPtr = 0;
1945 return Map.
1946 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
1947 (StringLength + 1) * 2));
Daniel Dunbar64509b22009-07-23 22:52:48 +00001948}
1949
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00001950static llvm::StringMapEntry<llvm::Constant*> &
1951GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
Bill Wendling07635cc2012-03-29 22:12:09 +00001952 const StringLiteral *Literal,
1953 unsigned &StringLength) {
1954 StringRef String = Literal->getString();
1955 StringLength = String.size();
1956 return Map.GetOrCreateValue(String);
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00001957}
1958
Daniel Dunbar64509b22009-07-23 22:52:48 +00001959llvm::Constant *
1960CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1961 unsigned StringLength = 0;
1962 bool isUTF16 = false;
1963 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump11289f42009-09-09 15:08:12 +00001964 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001965 getTargetData().isLittleEndian(),
1966 isUTF16, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00001967
Daniel Dunbar64509b22009-07-23 22:52:48 +00001968 if (llvm::Constant *C = Entry.getValue())
1969 return C;
Mike Stump11289f42009-09-09 15:08:12 +00001970
Chris Lattnerece04092012-02-07 00:39:47 +00001971 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00001972 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump11289f42009-09-09 15:08:12 +00001973
Chris Lattneraa64ca22009-07-16 16:48:25 +00001974 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00001975 if (!CFConstantStringClassRef) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001976 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001977 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001978 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattneraa64ca22009-07-16 16:48:25 +00001979 "__CFConstantStringClassReference");
Daniel Dunbard644ad62008-08-23 18:37:06 +00001980 // Decay array -> ptr
1981 CFConstantStringClassRef =
Jay Foaded8db7d2011-07-21 14:31:17 +00001982 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlssonb04ea612007-08-21 00:21:21 +00001983 }
Mike Stump11289f42009-09-09 15:08:12 +00001984
Anders Carlssonc2480a52008-11-15 18:54:24 +00001985 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00001986
Chris Lattner2192fe52011-07-18 04:24:23 +00001987 llvm::StructType *STy =
Anders Carlssonc2480a52008-11-15 18:54:24 +00001988 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1989
Benjamin Kramer22d24c22011-10-15 12:20:02 +00001990 llvm::Constant *Fields[4];
Douglas Gregor91f84212008-12-11 16:49:14 +00001991
Anders Carlssonb04ea612007-08-21 00:21:21 +00001992 // Class pointer.
Anders Carlsson157c3212009-08-16 05:55:31 +00001993 Fields[0] = CFConstantStringClassRef;
Mike Stump11289f42009-09-09 15:08:12 +00001994
Anders Carlssonb04ea612007-08-21 00:21:21 +00001995 // Flags.
Chris Lattner2192fe52011-07-18 04:24:23 +00001996 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump11289f42009-09-09 15:08:12 +00001997 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson157c3212009-08-16 05:55:31 +00001998 llvm::ConstantInt::get(Ty, 0x07C8);
1999
Anders Carlssonb04ea612007-08-21 00:21:21 +00002000 // String pointer.
Bill Wendling82b87f12012-03-30 00:26:17 +00002001 llvm::Constant *C = 0;
2002 if (isUTF16) {
2003 ArrayRef<uint16_t> Arr =
2004 llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
2005 Entry.getKey().size() / 2);
2006 C = llvm::ConstantDataArray::get(VMContext, Arr);
2007 } else {
2008 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2009 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002010
Chris Lattner3afa3e12009-07-16 05:03:48 +00002011 llvm::GlobalValue::LinkageTypes Linkage;
Bill Wendling86131f22012-01-10 08:46:39 +00002012 if (isUTF16)
Chris Lattner4f8a2e22009-10-14 05:55:45 +00002013 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner3afa3e12009-07-16 05:03:48 +00002014 Linkage = llvm::GlobalValue::InternalLinkage;
Bill Wendling86131f22012-01-10 08:46:39 +00002015 else
Rafael Espindola7a6cf012011-03-14 17:55:00 +00002016 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2017 // when using private linkage. It is not clear if this is a bug in ld
2018 // or a reasonable new restriction.
Rafael Espindola0c1f0982011-03-14 21:08:19 +00002019 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00002020
Bill Wendling86131f22012-01-10 08:46:39 +00002021 // Note: -fwritable-strings doesn't make the backing store strings of
2022 // CFStrings writable. (See <rdar://problem/10657500>)
Mike Stump11289f42009-09-09 15:08:12 +00002023 llvm::GlobalVariable *GV =
Bill Wendling86131f22012-01-10 08:46:39 +00002024 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2025 Linkage, C, ".str");
Rafael Espindolae79d43da2011-01-17 16:31:00 +00002026 GV->setUnnamedAddr(true);
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002027 if (isUTF16) {
Ken Dycka0f99ff2010-01-26 18:46:23 +00002028 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2029 GV->setAlignment(Align.getQuantity());
Daniel Dunbar9c8cd4c2011-04-12 23:30:52 +00002030 } else {
2031 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2032 GV->setAlignment(Align.getQuantity());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002033 }
Bill Wendling82b87f12012-03-30 00:26:17 +00002034
2035 // String.
Jay Foaded8db7d2011-07-21 14:31:17 +00002036 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00002037
Bill Wendling82b87f12012-03-30 00:26:17 +00002038 if (isUTF16)
2039 // Cast the UTF16 string to the correct type.
2040 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2041
Anders Carlssonb04ea612007-08-21 00:21:21 +00002042 // String length.
2043 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson157c3212009-08-16 05:55:31 +00002044 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00002045
Anders Carlssonb04ea612007-08-21 00:21:21 +00002046 // The struct.
Owen Anderson0e0189d2009-07-27 22:29:56 +00002047 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump11289f42009-09-09 15:08:12 +00002048 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2049 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner3afa3e12009-07-16 05:03:48 +00002050 "_unnamed_cfstring_");
Douglas Gregore8bbc122011-09-02 00:18:52 +00002051 if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002052 GV->setSection(Sect);
Daniel Dunbar64509b22009-07-23 22:52:48 +00002053 Entry.setValue(GV);
Mike Stump11289f42009-09-09 15:08:12 +00002054
Anders Carlsson41b7c6b2007-11-01 00:41:52 +00002055 return GV;
Anders Carlssonb04ea612007-08-21 00:21:21 +00002056}
Chris Lattnerfb300092007-11-28 05:34:05 +00002057
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002058static RecordDecl *
2059CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2060 DeclContext *DC, IdentifierInfo *Id) {
2061 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002062 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002063 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2064 else
2065 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2066}
2067
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002068llvm::Constant *
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002069CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002070 unsigned StringLength = 0;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002071 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002072 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002073
2074 if (llvm::Constant *C = Entry.getValue())
2075 return C;
2076
Chris Lattner00a10ca2012-02-06 22:47:00 +00002077 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002078 llvm::Constant *Zeros[] = { Zero, Zero };
2079
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00002080 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002081 if (!ConstantStringClassRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002082 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Chris Lattner2192fe52011-07-18 04:24:23 +00002083 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002084 llvm::Constant *GV;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002085 if (LangOpts.ObjCNonFragileABI) {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002086 std::string str =
2087 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2088 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002089 GV = getObjCRuntime().GetClassGlobal(str);
2090 // Make sure the result is of the correct type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002091 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002092 ConstantStringClassRef =
2093 llvm::ConstantExpr::getBitCast(GV, PTy);
2094 } else {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002095 std::string str =
2096 StringClass.empty() ? "_NSConstantStringClassReference"
2097 : "_" + StringClass + "ClassReference";
Chris Lattner2192fe52011-07-18 04:24:23 +00002098 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002099 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002100 // Decay array -> ptr
2101 ConstantStringClassRef =
Jay Foaded8db7d2011-07-21 14:31:17 +00002102 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002103 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002104 }
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002105
2106 if (!NSConstantStringType) {
2107 // Construct the type for a constant NSString.
2108 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2109 Context.getTranslationUnitDecl(),
2110 &Context.Idents.get("__builtin_NSString"));
2111 D->startDefinition();
2112
2113 QualType FieldTypes[3];
2114
2115 // const int *isa;
2116 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2117 // const char *str;
2118 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2119 // unsigned int length;
2120 FieldTypes[2] = Context.UnsignedIntTy;
2121
2122 // Create fields
2123 for (unsigned i = 0; i < 3; ++i) {
2124 FieldDecl *Field = FieldDecl::Create(Context, D,
2125 SourceLocation(),
2126 SourceLocation(), 0,
2127 FieldTypes[i], /*TInfo=*/0,
2128 /*BitWidth=*/0,
2129 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002130 ICIS_NoInit);
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002131 Field->setAccess(AS_public);
2132 D->addDecl(Field);
2133 }
2134
2135 D->completeDefinition();
2136 QualType NSTy = Context.getTagDeclType(D);
2137 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2138 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002139
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002140 llvm::Constant *Fields[3];
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002141
2142 // Class pointer.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002143 Fields[0] = ConstantStringClassRef;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002144
2145 // String pointer.
Chris Lattner9c818332012-02-05 02:30:40 +00002146 llvm::Constant *C =
2147 llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002148
2149 llvm::GlobalValue::LinkageTypes Linkage;
2150 bool isConstant;
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002151 Linkage = llvm::GlobalValue::PrivateLinkage;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002152 isConstant = !LangOpts.WritableStrings;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002153
2154 llvm::GlobalVariable *GV =
2155 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2156 ".str");
Rafael Espindolade089d42011-01-17 22:11:21 +00002157 GV->setUnnamedAddr(true);
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002158 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2159 GV->setAlignment(Align.getQuantity());
Jay Foaded8db7d2011-07-21 14:31:17 +00002160 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002161
2162 // String length.
Chris Lattner2192fe52011-07-18 04:24:23 +00002163 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002164 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2165
2166 // The struct.
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002167 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002168 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2169 llvm::GlobalVariable::PrivateLinkage, C,
2170 "_unnamed_nsstring_");
2171 // FIXME. Fix section.
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00002172 if (const char *Sect =
David Blaikiebbafb8a2012-03-11 07:00:24 +00002173 LangOpts.ObjCNonFragileABI
Douglas Gregore8bbc122011-09-02 00:18:52 +00002174 ? getContext().getTargetInfo().getNSStringNonFragileABISection()
2175 : getContext().getTargetInfo().getNSStringSection())
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002176 GV->setSection(Sect);
2177 Entry.setValue(GV);
2178
2179 return GV;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002180}
2181
Douglas Gregor636e2002011-08-09 17:23:49 +00002182QualType CodeGenModule::getObjCFastEnumerationStateType() {
2183 if (ObjCFastEnumerationStateType.isNull()) {
2184 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2185 Context.getTranslationUnitDecl(),
2186 &Context.Idents.get("__objcFastEnumerationState"));
2187 D->startDefinition();
2188
2189 QualType FieldTypes[] = {
2190 Context.UnsignedLongTy,
2191 Context.getPointerType(Context.getObjCIdType()),
2192 Context.getPointerType(Context.UnsignedLongTy),
2193 Context.getConstantArrayType(Context.UnsignedLongTy,
2194 llvm::APInt(32, 5), ArrayType::Normal, 0)
2195 };
2196
2197 for (size_t i = 0; i < 4; ++i) {
2198 FieldDecl *Field = FieldDecl::Create(Context,
2199 D,
2200 SourceLocation(),
2201 SourceLocation(), 0,
2202 FieldTypes[i], /*TInfo=*/0,
2203 /*BitWidth=*/0,
2204 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002205 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00002206 Field->setAccess(AS_public);
2207 D->addDecl(Field);
2208 }
2209
2210 D->completeDefinition();
2211 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2212 }
2213
2214 return ObjCFastEnumerationStateType;
2215}
2216
Eli Friedmanfcec6302011-11-01 02:23:42 +00002217llvm::Constant *
2218CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2219 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2220
2221 // Don't emit it as the address of the string, emit the string data itself
2222 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00002223 if (E->getCharByteWidth() == 1) {
2224 SmallString<64> Str(E->getString());
2225
2226 // Resize the string to the right size, which is indicated by its type.
2227 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2228 Str.resize(CAT->getSize().getZExtValue());
2229 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2230 }
Chris Lattner9c818332012-02-05 02:30:40 +00002231
2232 llvm::ArrayType *AType =
2233 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2234 llvm::Type *ElemTy = AType->getElementType();
2235 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00002236
2237 // Wide strings have either 2-byte or 4-byte elements.
2238 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2239 SmallVector<uint16_t, 32> Elements;
2240 Elements.reserve(NumElements);
2241
2242 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2243 Elements.push_back(E->getCodeUnit(i));
2244 Elements.resize(NumElements);
2245 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00002246 }
2247
Chris Lattner02cb1712012-02-06 22:52:04 +00002248 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2249 SmallVector<uint32_t, 32> Elements;
2250 Elements.reserve(NumElements);
2251
2252 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2253 Elements.push_back(E->getCodeUnit(i));
2254 Elements.resize(NumElements);
2255 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00002256}
2257
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002258/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2259/// constant array for the given string literal.
2260llvm::Constant *
2261CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
John McCall9b24df42011-08-04 01:03:22 +00002262 CharUnits Align = getContext().getTypeAlignInChars(S->getType());
Eli Friedmanfcec6302011-11-01 02:23:42 +00002263 if (S->isAscii() || S->isUTF8()) {
Chris Lattner00a10ca2012-02-06 22:47:00 +00002264 SmallString<64> Str(S->getString());
2265
2266 // Resize the string to the right size, which is indicated by its type.
2267 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2268 Str.resize(CAT->getSize().getZExtValue());
2269 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
Eli Friedman49ddc5f2009-11-16 05:55:46 +00002270 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00002271
Chris Lattner00a10ca2012-02-06 22:47:00 +00002272 // FIXME: the following does not memoize wide strings.
Eli Friedmanfcec6302011-11-01 02:23:42 +00002273 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2274 llvm::GlobalVariable *GV =
2275 new llvm::GlobalVariable(getModule(),C->getType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002276 !LangOpts.WritableStrings,
Eli Friedmanfcec6302011-11-01 02:23:42 +00002277 llvm::GlobalValue::PrivateLinkage,
2278 C,".str");
Seth Cantrellc9196652012-01-18 12:11:32 +00002279
Eli Friedmanfcec6302011-11-01 02:23:42 +00002280 GV->setAlignment(Align.getQuantity());
2281 GV->setUnnamedAddr(true);
Eli Friedmanfcec6302011-11-01 02:23:42 +00002282 return GV;
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002283}
2284
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002285/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2286/// array for the given ObjCEncodeExpr node.
2287llvm::Constant *
2288CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2289 std::string Str;
2290 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00002291
2292 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002293}
2294
2295
Chris Lattner36fc8792008-02-11 00:02:17 +00002296/// GenerateWritableString -- Creates storage for a string literal.
John McCall9b24df42011-08-04 01:03:22 +00002297static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
Chris Lattnerfb300092007-11-28 05:34:05 +00002298 bool constant,
Daniel Dunbardfcf5992008-10-17 21:56:50 +00002299 CodeGenModule &CGM,
John McCall9b24df42011-08-04 01:03:22 +00002300 const char *GlobalName,
2301 unsigned Alignment) {
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002302 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson41a75022009-08-13 21:57:51 +00002303 llvm::Constant *C =
Chris Lattner9c818332012-02-05 02:30:40 +00002304 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
Mike Stump11289f42009-09-09 15:08:12 +00002305
Chris Lattnerfb300092007-11-28 05:34:05 +00002306 // Create a global variable for this string
Rafael Espindolab7f60e32011-01-10 22:34:03 +00002307 llvm::GlobalVariable *GV =
2308 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2309 llvm::GlobalValue::PrivateLinkage,
2310 C, GlobalName);
John McCall9b24df42011-08-04 01:03:22 +00002311 GV->setAlignment(Alignment);
Rafael Espindolab7f60e32011-01-10 22:34:03 +00002312 GV->setUnnamedAddr(true);
2313 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00002314}
2315
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002316/// GetAddrOfConstantString - Returns a pointer to a character array
2317/// containing the literal. This contents are exactly that of the
2318/// given string, i.e. it will not be null terminated automatically;
2319/// see GetAddrOfConstantCString. Note that whether the result is
2320/// actually a pointer to an LLVM constant depends on
2321/// Feature.WriteableStrings.
2322///
2323/// The result has pointer to array type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002324llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
John McCall9b24df42011-08-04 01:03:22 +00002325 const char *GlobalName,
2326 unsigned Alignment) {
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002327 // Get the default prefix if a name wasn't specified.
2328 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00002329 GlobalName = ".str";
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002330
2331 // Don't share any string literals if strings aren't constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002332 if (LangOpts.WritableStrings)
John McCall9b24df42011-08-04 01:03:22 +00002333 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
Mike Stump11289f42009-09-09 15:08:12 +00002334
John McCall9b24df42011-08-04 01:03:22 +00002335 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002336 ConstantStringMap.GetOrCreateValue(Str);
Chris Lattnerfb300092007-11-28 05:34:05 +00002337
John McCall9b24df42011-08-04 01:03:22 +00002338 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2339 if (Alignment > GV->getAlignment()) {
2340 GV->setAlignment(Alignment);
2341 }
2342 return GV;
2343 }
Chris Lattnerfb300092007-11-28 05:34:05 +00002344
2345 // Create a global variable for this.
Chris Lattner00a10ca2012-02-06 22:47:00 +00002346 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2347 Alignment);
John McCall9b24df42011-08-04 01:03:22 +00002348 Entry.setValue(GV);
2349 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00002350}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002351
2352/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002353/// array containing the literal and a terminating '\0'
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002354/// character. The result has pointer to array type.
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002355llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
John McCall9b24df42011-08-04 01:03:22 +00002356 const char *GlobalName,
2357 unsigned Alignment) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002358 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall9b24df42011-08-04 01:03:22 +00002359 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002360}
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002361
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002362/// EmitObjCPropertyImplementations - Emit information for synthesized
2363/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00002364void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002365 ObjCImplementationDecl *D) {
Mike Stump11289f42009-09-09 15:08:12 +00002366 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002367 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002368 ObjCPropertyImplDecl *PID = *i;
Mike Stump11289f42009-09-09 15:08:12 +00002369
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002370 // Dynamic is just for type-checking.
2371 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2372 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2373
2374 // Determine which methods need to be implemented, some may have
2375 // been overridden. Note that ::isSynthesized is not the method
2376 // we want, that just indicates if the decl came from a
2377 // property. What we want to know is if the method is defined in
2378 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002379 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00002380 CodeGenFunction(*this).GenerateObjCGetter(
2381 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002382 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002383 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00002384 CodeGenFunction(*this).GenerateObjCSetter(
2385 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002386 }
2387 }
2388}
2389
John McCall6a4fa522011-03-22 07:05:39 +00002390static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002391 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2392 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00002393 ivar; ivar = ivar->getNextIvar())
2394 if (ivar->getType().isDestructedType())
2395 return true;
2396
2397 return false;
2398}
2399
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002400/// EmitObjCIvarInitializations - Emit information for ivar initialization
2401/// for an implementation.
2402void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00002403 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2404 if (needsDestructMethod(D)) {
2405 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2406 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2407 ObjCMethodDecl *DTORMethod =
2408 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002409 cxxSelector, getContext().VoidTy, 0, D,
2410 /*isInstance=*/true, /*isVariadic=*/false,
2411 /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
2412 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00002413 D->addInstanceMethod(DTORMethod);
2414 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall31168b02011-06-15 23:02:42 +00002415 D->setHasCXXStructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00002416 }
2417
2418 // If the implementation doesn't have any ivar initializers, we don't need
2419 // a .cxx_construct.
David Chisnalla9e54602011-03-17 14:19:08 +00002420 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002421 return;
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002422
John McCall6a4fa522011-03-22 07:05:39 +00002423 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2424 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002425 // The constructor returns 'self'.
2426 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2427 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00002428 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00002429 cxxSelector,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002430 getContext().getObjCIdType(), 0,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002431 D, /*isInstance=*/true,
2432 /*isVariadic=*/false,
2433 /*isSynthesized=*/true,
2434 /*isImplicitlyDeclared=*/true,
2435 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002436 ObjCMethodDecl::Required);
2437 D->addInstanceMethod(CTORMethod);
2438 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall31168b02011-06-15 23:02:42 +00002439 D->setHasCXXStructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002440}
2441
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002442/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson237f3492009-04-01 00:58:25 +00002443void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002444 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson237f3492009-04-01 00:58:25 +00002445 I != E; ++I)
2446 EmitTopLevelDecl(*I);
2447}
2448
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002449// EmitLinkageSpec - Emit all declarations in a linkage spec.
2450void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00002451 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2452 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002453 ErrorUnsupported(LSD, "linkage spec");
2454 return;
2455 }
2456
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002457 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002458 I != E; ++I)
2459 EmitTopLevelDecl(*I);
2460}
2461
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002462/// EmitTopLevelDecl - Emit code for a single top level declaration.
2463void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2464 // If an error has occurred, stop code generation, but continue
2465 // parsing and semantic analysis (to ensure all warnings and errors
2466 // are emitted).
2467 if (Diags.hasErrorOccurred())
2468 return;
2469
Douglas Gregor70d83e22009-06-29 17:30:29 +00002470 // Ignore dependent declarations.
2471 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2472 return;
Mike Stump11289f42009-09-09 15:08:12 +00002473
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002474 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00002475 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00002476 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002477 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00002478 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00002479 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2480 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor70d83e22009-06-29 17:30:29 +00002481 return;
Mike Stump11289f42009-09-09 15:08:12 +00002482
Anders Carlssonecf9bf02009-09-10 23:43:36 +00002483 EmitGlobal(cast<FunctionDecl>(D));
2484 break;
2485
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002486 case Decl::Var:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00002487 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002488 break;
2489
John McCall32f44bd2011-04-12 01:01:22 +00002490 // Indirect fields from global anonymous structs and unions can be
2491 // ignored; only the actual variable requires IR gen support.
2492 case Decl::IndirectField:
2493 break;
2494
Anders Carlssonf7475242009-04-15 15:55:24 +00002495 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002496 case Decl::Namespace:
Anders Carlsson237f3492009-04-01 00:58:25 +00002497 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002498 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00002499 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00002500 case Decl::UsingShadow:
Douglas Gregorfec52632009-06-20 00:51:54 +00002501 case Decl::Using:
Douglas Gregore5feb512009-09-02 23:49:23 +00002502 case Decl::UsingDirective:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002503 case Decl::ClassTemplate:
2504 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00002505 case Decl::TypeAliasTemplate:
Anders Carlsson649a17e2009-09-23 19:19:16 +00002506 case Decl::NamespaceAlias:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002507 case Decl::Block:
Douglas Gregorba345522011-12-02 23:23:56 +00002508 case Decl::Import:
Douglas Gregorfec52632009-06-20 00:51:54 +00002509 break;
Anders Carlssonf7475242009-04-15 15:55:24 +00002510 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00002511 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00002512 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2513 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson0ade9712009-11-24 05:16:24 +00002514 return;
2515
Anders Carlssonf7475242009-04-15 15:55:24 +00002516 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2517 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00002518 case Decl::CXXDestructor:
Francois Pichet1c229c02011-04-22 22:18:13 +00002519 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2520 return;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00002521 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2522 break;
Anders Carlsson87835432009-06-11 21:22:55 +00002523
2524 case Decl::StaticAssert:
2525 // Nothing to do.
2526 break;
2527
Anders Carlssonf7475242009-04-15 15:55:24 +00002528 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00002529
Fariborz Jahanian3654e652009-03-18 22:33:24 +00002530 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00002531 case Decl::ObjCInterface:
Chris Lattnerd18136a2009-04-01 02:36:43 +00002532 break;
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00002533
Chris Lattnere4ec5ab2011-04-09 07:11:53 +00002534 case Decl::ObjCCategory: {
2535 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2536 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2537 Context.ResetObjCLayout(CD->getClassInterface());
2538 break;
2539 }
Chris Lattnerd18136a2009-04-01 02:36:43 +00002540
Douglas Gregorf6102672012-01-01 21:23:57 +00002541 case Decl::ObjCProtocol: {
2542 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2543 if (Proto->isThisDeclarationADefinition())
2544 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002545 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00002546 }
2547
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002548 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002549 // Categories have properties but don't support synthesize so we
2550 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00002551 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002552 break;
2553
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002554 case Decl::ObjCImplementation: {
2555 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002556 if (LangOpts.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00002557 Context.ResetObjCLayout(OMD->getClassInterface());
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002558 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002559 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00002560 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00002561 // Emit global variable debug information.
2562 if (CGDebugInfo *DI = getModuleDebugInfo())
2563 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(OMD->getClassInterface()),
2564 OMD->getLocation());
2565
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002566 break;
Mike Stump11289f42009-09-09 15:08:12 +00002567 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002568 case Decl::ObjCMethod: {
2569 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2570 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002571 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002572 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2573 break;
2574 }
Mike Stump11289f42009-09-09 15:08:12 +00002575 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00002576 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002577 break;
2578
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002579 case Decl::LinkageSpec:
2580 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002581 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002582
2583 case Decl::FileScopeAsm: {
2584 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002585 StringRef AsmString = AD->getAsmString()->getString();
Mike Stump11289f42009-09-09 15:08:12 +00002586
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002587 const std::string &S = getModule().getModuleInlineAsm();
2588 if (S.empty())
2589 getModule().setModuleInlineAsm(AsmString);
Chris Lattner84037d32011-07-23 20:04:25 +00002590 else if (*--S.end() == '\n')
2591 getModule().setModuleInlineAsm(S + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002592 else
Benjamin Kramerb11118b2009-12-11 13:33:18 +00002593 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002594 break;
2595 }
Mike Stump11289f42009-09-09 15:08:12 +00002596
2597 default:
Mike Stump18bb9282009-05-16 07:57:57 +00002598 // Make sure we handled everything we should, every other kind is a
2599 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2600 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002601 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2602 }
2603}
John McCall09ae0322010-07-06 23:57:41 +00002604
2605/// Turns the given pointer into a constant.
2606static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2607 const void *Ptr) {
2608 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00002609 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00002610 return llvm::ConstantInt::get(i64, PtrInt);
2611}
2612
2613static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2614 llvm::NamedMDNode *&GlobalMetadata,
2615 GlobalDecl D,
2616 llvm::GlobalValue *Addr) {
2617 if (!GlobalMetadata)
2618 GlobalMetadata =
2619 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2620
2621 // TODO: should we report variant information for ctors/dtors?
2622 llvm::Value *Ops[] = {
2623 Addr,
2624 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2625 };
Jay Foadea324f12011-04-21 19:59:12 +00002626 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00002627}
2628
2629/// Emits metadata nodes associating all the global values in the
2630/// current module with the Decls they came from. This is useful for
2631/// projects using IR gen as a subroutine.
2632///
2633/// Since there's currently no way to associate an MDNode directly
2634/// with an llvm::GlobalValue, we create a global named metadata
2635/// with the name 'clang.global.decl.ptrs'.
2636void CodeGenModule::EmitDeclMetadata() {
2637 llvm::NamedMDNode *GlobalMetadata = 0;
2638
2639 // StaticLocalDeclMap
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002640 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
John McCall09ae0322010-07-06 23:57:41 +00002641 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2642 I != E; ++I) {
2643 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2644 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2645 }
2646}
2647
2648/// Emits metadata nodes for all the local variables in the current
2649/// function.
2650void CodeGenFunction::EmitDeclMetadata() {
2651 if (LocalDeclMap.empty()) return;
2652
2653 llvm::LLVMContext &Context = getLLVMContext();
2654
2655 // Find the unique metadata ID for this name.
2656 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2657
2658 llvm::NamedMDNode *GlobalMetadata = 0;
2659
2660 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2661 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2662 const Decl *D = I->first;
2663 llvm::Value *Addr = I->second;
2664
2665 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2666 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foadea324f12011-04-21 19:59:12 +00002667 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
John McCall09ae0322010-07-06 23:57:41 +00002668 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2669 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2670 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2671 }
2672 }
2673}
Daniel Dunbar900546d2010-07-16 00:00:15 +00002674
Nick Lewycky85c011d2011-05-05 00:08:20 +00002675void CodeGenModule::EmitCoverageFile() {
2676 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky480cb992011-05-04 20:46:58 +00002677 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2678 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2679 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky85c011d2011-05-05 00:08:20 +00002680 llvm::MDString *CoverageFile =
2681 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky480cb992011-05-04 20:46:58 +00002682 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2683 llvm::MDNode *CU = CUNode->getOperand(i);
Nick Lewycky85c011d2011-05-05 00:08:20 +00002684 llvm::Value *node[] = { CoverageFile, CU };
Nick Lewycky480cb992011-05-04 20:46:58 +00002685 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2686 GCov->addOperand(N);
2687 }
2688 }
2689 }
2690}