blob: 89aeeb6fc79ffeffb37571bab0235254b8224a6e [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"
John McCall5d865c322010-08-31 07:33:07 +000019#include "CGCXXABI.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000020#include "CGObjCRuntime.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000021#include "TargetInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000022#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000023#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000024#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000026#include "clang/AST/DeclCXX.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000027#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000029#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000031#include "clang/Basic/Diagnostic.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000032#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000033#include "clang/Basic/TargetInfo.h"
Steve Naroff29cae662009-04-01 15:50:34 +000034#include "clang/Basic/ConvertUTF.h"
Nate Begemanaca747a2008-03-09 03:09:36 +000035#include "llvm/CallingConv.h"
Chris Lattner1eec6602007-08-31 04:31:45 +000036#include "llvm/Module.h"
Chris Lattner09153c02007-06-22 18:48:09 +000037#include "llvm/Intrinsics.h"
Chris Lattner5e124bf2009-12-28 21:44:41 +000038#include "llvm/LLVMContext.h"
John McCallbeec5a02010-03-06 00:35:14 +000039#include "llvm/ADT/Triple.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000040#include "llvm/Target/TargetData.h"
Gabor Greifd0ef1342010-04-10 02:56:12 +000041#include "llvm/Support/CallSite.h"
Chris Lattner15275e52009-11-07 09:22:46 +000042#include "llvm/Support/ErrorHandling.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000043using namespace clang;
44using namespace CodeGen;
45
John McCall614dbdc2010-08-22 21:01:12 +000046static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
47 switch (CGM.getContext().Target.getCXXABI()) {
48 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
49 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
50 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
51 }
52
53 llvm_unreachable("invalid C++ ABI kind");
54 return *CreateItaniumCXXABI(CGM);
55}
56
Chris Lattnerbed31442007-05-28 01:07:47 +000057
Chandler Carruthbc55fe22009-11-12 17:24:48 +000058CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall731be662010-03-04 04:29:44 +000059 llvm::Module &M, const llvm::TargetData &TD,
60 Diagnostic &diags)
John McCallad7c5c12011-02-08 08:22:06 +000061 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
John McCall731be662010-03-04 04:29:44 +000062 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
John McCall614dbdc2010-08-22 21:01:12 +000063 ABI(createCXXABI(*this)),
64 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
Dan Gohman947c9af2010-10-14 23:06:10 +000065 TBAA(0),
John McCall614dbdc2010-08-22 21:01:12 +000066 VTables(*this), Runtime(0),
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000067 CFConstantStringClassRef(0), ConstantStringClassRef(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000068 VMContext(M.getContext()),
Daniel Dunbar3348e2d2010-07-16 00:00:19 +000069 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000070 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
Daniel Dunbar3348e2d2010-07-16 00:00:19 +000071 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
John McCallad7c5c12011-02-08 08:22:06 +000072 BlockObjectAssign(0), BlockObjectDispose(0),
73 BlockDescriptorType(0), GenericBlockLiteralType(0) {
Chris Lattner36376522009-03-21 07:12:05 +000074 if (!Features.ObjC1)
75 Runtime = 0;
76 else if (!Features.NeXTRuntime)
77 Runtime = CreateGNUObjCRuntime(*this);
78 else if (Features.ObjCNonFragileABI)
79 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
80 else
81 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Gupta15cb6692008-05-08 08:54:20 +000082
Dan Gohman947c9af2010-10-14 23:06:10 +000083 // Enable TBAA unless it's suppressed.
84 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
Dan Gohman2e29eb52010-10-15 20:23:12 +000085 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
86 ABI.getMangleContext());
Dan Gohman947c9af2010-10-14 23:06:10 +000087
Sanjiv Gupta15cb6692008-05-08 08:54:20 +000088 // If debug info generation is enabled, create the CGDebugInfo object.
Anders Carlsson3efc6e62009-12-06 18:00:51 +000089 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
John McCallad7c5c12011-02-08 08:22:06 +000090
91 Block.GlobalUniqueCount = 0;
92 Int8PtrTy = llvm::Type::getInt8PtrTy(M.getContext());
Chris Lattnera087ff92008-03-01 08:45:05 +000093}
94
95CodeGenModule::~CodeGenModule() {
Ted Kremenek2c674f62008-08-05 18:50:11 +000096 delete Runtime;
John McCall614dbdc2010-08-22 21:01:12 +000097 delete &ABI;
Dan Gohmand19ee8a2010-10-15 18:04:46 +000098 delete TBAA;
Ted Kremenek2c674f62008-08-05 18:50:11 +000099 delete DebugInfo;
100}
101
David Chisnall481e3a82010-01-23 02:40:42 +0000102void CodeGenModule::createObjCRuntime() {
103 if (!Features.NeXTRuntime)
104 Runtime = CreateGNUObjCRuntime(*this);
105 else if (Features.ObjCNonFragileABI)
106 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
107 else
108 Runtime = CreateMacObjCRuntime(*this);
109}
110
Ted Kremenek2c674f62008-08-05 18:50:11 +0000111void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000112 EmitDeferred();
Eli Friedman5866fe32010-01-08 00:50:11 +0000113 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000114 EmitCXXGlobalDtorFunc();
Daniel Dunbar8d480592008-08-11 18:12:00 +0000115 if (Runtime)
116 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
117 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000118 EmitCtorList(GlobalCtors, "llvm.global_ctors");
119 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman7fab5782008-04-18 23:43:57 +0000120 EmitAnnotations();
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000121 EmitLLVMUsed();
John McCall09ae0322010-07-06 23:57:41 +0000122
John McCall0bdb1fd2010-09-16 06:16:50 +0000123 SimplifyPersonality();
124
John McCall09ae0322010-07-06 23:57:41 +0000125 if (getCodeGenOpts().EmitDeclMetadata)
126 EmitDeclMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000127}
128
Dan Gohman947c9af2010-10-14 23:06:10 +0000129llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
130 if (!TBAA)
131 return 0;
132 return TBAA->getTBAAInfo(QTy);
133}
134
135void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
136 llvm::MDNode *TBAAInfo) {
137 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
138}
139
John McCallbeec5a02010-03-06 00:35:14 +0000140bool CodeGenModule::isTargetDarwin() const {
141 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
142}
143
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000144/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000145/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000146void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
147 bool OmitOnError) {
148 if (OmitOnError && getDiags().hasErrorOccurred())
149 return;
Mike Stump11289f42009-09-09 15:08:12 +0000150 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000151 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000152 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000153 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
154 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000155}
Chris Lattner41af8182007-12-02 06:27:33 +0000156
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000157/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000158/// specified decl yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000159void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
160 bool OmitOnError) {
161 if (OmitOnError && getDiags().hasErrorOccurred())
162 return;
Mike Stump11289f42009-09-09 15:08:12 +0000163 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000164 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000165 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000166 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000167}
168
Mike Stump11289f42009-09-09 15:08:12 +0000169void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlssonc6a47892011-01-29 19:39:23 +0000170 const NamedDecl *D) const {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000171 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000172 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000173 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000174 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000175 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000176
John McCallc273f242010-10-30 11:50:40 +0000177 // Set visibility for definitions.
178 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola88ea6ab2011-02-01 05:45:26 +0000179 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
180 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000181}
182
John McCalle16adc22010-08-04 08:34:44 +0000183/// Set the symbol visibility of type information (vtable and RTTI)
184/// associated with the given type.
185void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
186 const CXXRecordDecl *RD,
Anders Carlsson265aa7c2011-01-29 20:24:48 +0000187 TypeVisibilityKind TVK) const {
Anders Carlssonc6a47892011-01-29 19:39:23 +0000188 setGlobalVisibility(GV, RD);
John McCalle16adc22010-08-04 08:34:44 +0000189
John McCallb3732bb2010-08-12 23:36:15 +0000190 if (!CodeGenOpts.HiddenWeakVTables)
191 return;
192
Anders Carlsson678632f2011-01-29 20:36:11 +0000193 // We never want to drop the visibility for RTTI names.
194 if (TVK == TVK_ForRTTIName)
195 return;
196
John McCalle16adc22010-08-04 08:34:44 +0000197 // We want to drop the visibility to hidden for weak type symbols.
198 // This isn't possible if there might be unresolved references
199 // elsewhere that rely on this symbol being visible.
200
John McCall5513fce92010-08-05 20:39:18 +0000201 // This should be kept roughly in sync with setThunkVisibility
202 // in CGVTables.cpp.
203
John McCalle16adc22010-08-04 08:34:44 +0000204 // Preconditions.
Anders Carlsson571e2ad2011-01-24 00:46:19 +0000205 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
John McCalle16adc22010-08-04 08:34:44 +0000206 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
207 return;
208
209 // Don't override an explicit visibility attribute.
210 if (RD->hasAttr<VisibilityAttr>())
211 return;
212
213 switch (RD->getTemplateSpecializationKind()) {
214 // We have to disable the optimization if this is an EI definition
215 // because there might be EI declarations in other shared objects.
216 case TSK_ExplicitInstantiationDefinition:
217 case TSK_ExplicitInstantiationDeclaration:
218 return;
219
John McCall5513fce92010-08-05 20:39:18 +0000220 // Every use of a non-template class's type information has to emit it.
John McCalle16adc22010-08-04 08:34:44 +0000221 case TSK_Undeclared:
222 break;
223
John McCall5513fce92010-08-05 20:39:18 +0000224 // In theory, implicit instantiations can ignore the possibility of
225 // an explicit instantiation declaration because there necessarily
226 // must be an EI definition somewhere with default visibility. In
227 // practice, it's possible to have an explicit instantiation for
228 // an arbitrary template class, and linkers aren't necessarily able
229 // to deal with mixed-visibility symbols.
230 case TSK_ExplicitSpecialization:
John McCalle16adc22010-08-04 08:34:44 +0000231 case TSK_ImplicitInstantiation:
John McCallb3732bb2010-08-12 23:36:15 +0000232 if (!CodeGenOpts.HiddenWeakTemplateVTables)
John McCall5513fce92010-08-05 20:39:18 +0000233 return;
John McCalle16adc22010-08-04 08:34:44 +0000234 break;
235 }
236
237 // If there's a key function, there may be translation units
238 // that don't have the key function's definition. But ignore
239 // this if we're emitting RTTI under -fno-rtti.
Anders Carlsson265aa7c2011-01-29 20:24:48 +0000240 if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
John McCalle16adc22010-08-04 08:34:44 +0000241 if (Context.getKeyFunction(RD))
242 return;
Anders Carlsson265aa7c2011-01-29 20:24:48 +0000243 }
John McCalle16adc22010-08-04 08:34:44 +0000244
245 // Otherwise, drop the visibility to hidden.
246 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1e879c2011-01-11 21:44:37 +0000247 GV->setUnnamedAddr(true);
John McCalle16adc22010-08-04 08:34:44 +0000248}
249
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000250llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
251 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
252
253 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
254 if (!Str.empty())
255 return Str;
256
John McCall5d865c322010-08-31 07:33:07 +0000257 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000258 IdentifierInfo *II = ND->getIdentifier();
259 assert(II && "Attempt to mangle unnamed decl.");
260
261 Str = II->getName();
262 return Str;
263 }
264
265 llvm::SmallString<256> Buffer;
266 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
John McCall5d865c322010-08-31 07:33:07 +0000267 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000268 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
John McCall5d865c322010-08-31 07:33:07 +0000269 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000270 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000271 getCXXABI().getMangleContext().mangleBlock(BD, Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000272 else
John McCall5d865c322010-08-31 07:33:07 +0000273 getCXXABI().getMangleContext().mangleName(ND, Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000274
275 // Allocate space for the mangled name.
276 size_t Length = Buffer.size();
277 char *Name = MangledNamesAllocator.Allocate<char>(Length);
278 std::copy(Buffer.begin(), Buffer.end(), Name);
279
280 Str = llvm::StringRef(Name, Length);
281
282 return Str;
283}
284
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000285void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
286 const BlockDecl *BD) {
287 MangleContext &MangleCtx = getCXXABI().getMangleContext();
288 const Decl *D = GD.getDecl();
289 if (D == 0)
290 MangleCtx.mangleGlobalBlock(BD, Buffer.getBuffer());
291 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
292 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Buffer.getBuffer());
293 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
294 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Buffer.getBuffer());
295 else
296 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Buffer.getBuffer());
Anders Carlsson635186a2010-06-09 02:36:32 +0000297}
298
John McCall7ec50432010-03-19 23:29:14 +0000299llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
300 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000301}
302
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000303/// AddGlobalCtor - Add a function to the list that will be called before
304/// main() runs.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000305void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000306 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000307 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000308}
309
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000310/// AddGlobalDtor - Add a function to the list that will be called
311/// when the module is unloaded.
312void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000313 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000314 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
315}
316
317void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
318 // Ctor function type is void()*.
319 llvm::FunctionType* CtorFTy =
Benjamin Kramer1e188892011-01-22 12:15:57 +0000320 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000321 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000322
323 // Get the type of a ctor entry, { i32, void ()* }.
Mike Stump11289f42009-09-09 15:08:12 +0000324 llvm::StructType* CtorStructTy =
325 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
Owen Anderson9793f0e2009-07-29 22:16:19 +0000326 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000327
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000328 // Construct the constructor and destructor arrays.
329 std::vector<llvm::Constant*> Ctors;
330 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
331 std::vector<llvm::Constant*> S;
Mike Stump11289f42009-09-09 15:08:12 +0000332 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson41a75022009-08-13 21:57:51 +0000333 I->second, false));
Owen Andersonade90fd2009-07-29 18:54:39 +0000334 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
Owen Anderson0e0189d2009-07-27 22:29:56 +0000335 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000336 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000337
338 if (!Ctors.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000339 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Andersonc10c8d32009-07-08 19:05:04 +0000340 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000341 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000342 llvm::ConstantArray::get(AT, Ctors),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000343 GlobalName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000344 }
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000345}
346
Nate Begeman7fab5782008-04-18 23:43:57 +0000347void CodeGenModule::EmitAnnotations() {
348 if (Annotations.empty())
349 return;
350
351 // Create a new global variable for the ConstantStruct in the Module.
352 llvm::Constant *Array =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000353 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
Nate Begeman7fab5782008-04-18 23:43:57 +0000354 Annotations.size()),
355 Annotations);
Mike Stump11289f42009-09-09 15:08:12 +0000356 llvm::GlobalValue *gv =
357 new llvm::GlobalVariable(TheModule, Array->getType(), false,
358 llvm::GlobalValue::AppendingLinkage, Array,
Owen Andersonc10c8d32009-07-08 19:05:04 +0000359 "llvm.global.annotations");
Nate Begeman7fab5782008-04-18 23:43:57 +0000360 gv->setSection("llvm.metadata");
361}
362
John McCalld4324142010-02-19 01:32:20 +0000363llvm::GlobalValue::LinkageTypes
364CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000365 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +0000366
Chris Lattner749b8ed2010-06-30 16:58:07 +0000367 if (Linkage == GVA_Internal)
John McCalld4324142010-02-19 01:32:20 +0000368 return llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000369
370 if (D->hasAttr<DLLExportAttr>())
John McCalld4324142010-02-19 01:32:20 +0000371 return llvm::Function::DLLExportLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000372
373 if (D->hasAttr<WeakAttr>())
John McCalld4324142010-02-19 01:32:20 +0000374 return llvm::Function::WeakAnyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000375
376 // In C99 mode, 'inline' functions are guaranteed to have a strong
377 // definition somewhere else, so we can use available_externally linkage.
378 if (Linkage == GVA_C99Inline)
Fariborz Jahanian7cadb2f2011-02-04 00:08:13 +0000379 return llvm::Function::AvailableExternallyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000380
381 // In C++, the compiler has to emit a definition in every translation unit
382 // that references the function. We should use linkonce_odr because
383 // a) if all references in this translation unit are optimized away, we
384 // don't need to codegen it. b) if the function persists, it needs to be
385 // merged with other definitions. c) C++ has the ODR, so we know the
386 // definition is dependable.
387 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Fariborz Jahanianf7f04452011-02-04 00:01:24 +0000388 return !Context.getLangOptions().AppleKext
389 ? llvm::Function::LinkOnceODRLinkage
390 : llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000391
392 // An explicit instantiation of a template has weak linkage, since
393 // explicit instantiations can occur in multiple translation units
394 // and must all be equivalent. However, we are not allowed to
395 // throw away these explicit instantiations.
396 if (Linkage == GVA_ExplicitTemplateInstantiation)
Fariborz Jahanianf7f04452011-02-04 00:01:24 +0000397 return !Context.getLangOptions().AppleKext
398 ? llvm::Function::WeakODRLinkage
399 : llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000400
401 // Otherwise, we have strong external linkage.
402 assert(Linkage == GVA_StrongExternal);
403 return llvm::Function::ExternalLinkage;
John McCalld4324142010-02-19 01:32:20 +0000404}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000405
John McCalld4324142010-02-19 01:32:20 +0000406
407/// SetFunctionDefinitionAttributes - Set attributes for a global.
408///
409/// FIXME: This is currently only done for aliases and functions, but not for
410/// variables (these details are set in EmitGlobalVarDefinition for variables).
411void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
412 llvm::GlobalValue *GV) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000413 SetCommonAttributes(D, GV);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000414}
415
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000416void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000417 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000418 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000419 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +0000420 AttributeListType AttributeList;
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000421 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Devang Patel322300d2008-09-25 21:02:23 +0000422 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000423 AttributeList.size()));
424 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000425}
426
Daniel Dunbar38932572009-04-14 08:05:55 +0000427void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
428 llvm::Function *F) {
Daniel Dunbar0f3403c2009-03-02 04:58:03 +0000429 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Mike Stump11289f42009-09-09 15:08:12 +0000430 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000431
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000432 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbar03a38442008-10-28 00:17:57 +0000433 F->addFnAttr(llvm::Attribute::AlwaysInline);
Mike Stump11289f42009-09-09 15:08:12 +0000434
Daniel Dunbar8caf6412010-09-29 18:20:25 +0000435 if (D->hasAttr<NakedAttr>())
436 F->addFnAttr(llvm::Attribute::Naked);
437
Mike Stump3722f582009-08-26 22:31:08 +0000438 if (D->hasAttr<NoInlineAttr>())
Anders Carlssonf96954c2009-02-19 19:22:11 +0000439 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpc5e153c2009-10-05 21:58:44 +0000440
Rafael Espindola0ee986c1f2011-01-11 00:26:26 +0000441 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
442 F->setUnnamedAddr(true);
443
Anders Carlsson0d82fa62009-11-16 16:56:03 +0000444 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
445 F->addFnAttr(llvm::Attribute::StackProtect);
446 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
447 F->addFnAttr(llvm::Attribute::StackProtectReq);
448
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000449 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
450 if (alignment)
451 F->setAlignment(alignment);
452
Mike Stump3472ae52009-10-05 22:49:20 +0000453 // C++ ABI requires 2-byte alignment for member functions.
Mike Stump916c0062009-10-05 23:08:21 +0000454 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
455 F->setAlignment(2);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000456}
457
Mike Stump11289f42009-09-09 15:08:12 +0000458void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +0000459 llvm::GlobalValue *GV) {
Anders Carlsson072ef742011-01-29 19:41:00 +0000460 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
461 setGlobalVisibility(GV, ND);
John McCall457a04e2010-10-22 21:05:15 +0000462 else
463 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +0000464
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000465 if (D->hasAttr<UsedAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000466 AddUsedGlobal(GV);
467
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000468 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000469 GV->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000470
471 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +0000472}
473
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000474void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
475 llvm::Function *F,
476 const CGFunctionInfo &FI) {
477 SetLLVMFunctionAttributes(D, FI, F);
478 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +0000479
480 F->setLinkage(llvm::Function::InternalLinkage);
481
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000482 SetCommonAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000483}
484
Anders Carlsson6710c532010-02-06 02:44:09 +0000485void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedman895771a2009-05-26 01:22:57 +0000486 llvm::Function *F,
487 bool IsIncompleteFunction) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000488 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
489
Eli Friedman895771a2009-05-26 01:22:57 +0000490 if (!IsIncompleteFunction)
Anders Carlsson6710c532010-02-06 02:44:09 +0000491 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +0000492
Daniel Dunbar38932572009-04-14 08:05:55 +0000493 // Only a few attributes are set on declarations; these may later be
494 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +0000495
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000496 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000497 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump11289f42009-09-09 15:08:12 +0000498 } else if (FD->hasAttr<WeakAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000499 FD->hasAttr<WeakImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000500 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump11289f42009-09-09 15:08:12 +0000501 // separate linkage types for this.
Daniel Dunbar38932572009-04-14 08:05:55 +0000502 F->setLinkage(llvm::Function::ExternalWeakLinkage);
503 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000504 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallc273f242010-10-30 11:50:40 +0000505
506 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
507 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
508 F->setVisibility(GetLLVMVisibility(LV.visibility()));
509 }
Daniel Dunbar38932572009-04-14 08:05:55 +0000510 }
511
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000512 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000513 F->setSection(SA->getName());
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000514}
515
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000516void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +0000517 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000518 "Only globals with definition can force usage.");
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000519 LLVMUsed.push_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000520}
521
522void CodeGenModule::EmitLLVMUsed() {
523 // Don't create llvm.used if there is no need.
Chris Lattnerf56501c2009-07-17 23:57:13 +0000524 if (LLVMUsed.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000525 return;
526
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000527 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump11289f42009-09-09 15:08:12 +0000528
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000529 // Convert LLVMUsed to what ConstantArray needs.
530 std::vector<llvm::Constant*> UsedArray;
531 UsedArray.resize(LLVMUsed.size());
532 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000533 UsedArray[i] =
534 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Owen Anderson170229f2009-07-14 23:10:40 +0000535 i8PTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000536 }
Mike Stump11289f42009-09-09 15:08:12 +0000537
Fariborz Jahanian248c7192009-06-23 21:47:46 +0000538 if (UsedArray.empty())
539 return;
Owen Anderson9793f0e2009-07-29 22:16:19 +0000540 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +0000541
542 llvm::GlobalVariable *GV =
543 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000544 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000545 llvm::ConstantArray::get(ATy, UsedArray),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000546 "llvm.used");
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000547
548 GV->setSection("llvm.metadata");
549}
550
551void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +0000552 // Emit code for any potentially referenced deferred decls. Since a
553 // previously unused static decl may become used during the generation of code
554 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000555
Anders Carlsson11e51402010-04-17 20:15:18 +0000556 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
557 if (!DeferredVTables.empty()) {
558 const CXXRecordDecl *RD = DeferredVTables.back();
559 DeferredVTables.pop_back();
560 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000561 continue;
562 }
563
Anders Carlssondae1abc2009-05-05 04:44:02 +0000564 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner45470942009-03-21 09:44:56 +0000565 DeferredDeclsToEmit.pop_back();
566
John McCallc2af9392010-05-27 01:45:30 +0000567 // Check to see if we've already emitted this. This is necessary
568 // for a couple of reasons: first, decls can end up in the
569 // deferred-decls queue multiple times, and second, decls can end
570 // up with definitions in unusual ways (e.g. by an extern inline
571 // function acquiring a strong function redefinition). Just
572 // ignore these cases.
573 //
574 // TODO: That said, looking this up multiple times is very wasteful.
Anders Carlssonea836bc2010-06-22 16:16:50 +0000575 llvm::StringRef Name = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +0000576 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner45470942009-03-21 09:44:56 +0000577 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump11289f42009-09-09 15:08:12 +0000578
Chris Lattner45470942009-03-21 09:44:56 +0000579 if (!CGRef->isDeclaration())
580 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000581
John McCallc2af9392010-05-27 01:45:30 +0000582 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
583 // purposes an alias counts as a definition.
584 if (isa<llvm::GlobalAlias>(CGRef))
585 continue;
586
Chris Lattner45470942009-03-21 09:44:56 +0000587 // Otherwise, emit the definition and move on to the next one.
588 EmitGlobalDefinition(D);
589 }
Chris Lattnerbed31442007-05-28 01:07:47 +0000590}
Chris Lattner09153c02007-06-22 18:48:09 +0000591
Mike Stump11289f42009-09-09 15:08:12 +0000592/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
Nate Begemanfaae0812008-04-19 04:17:09 +0000593/// annotation information for a given GlobalValue. The annotation struct is
Mike Stump11289f42009-09-09 15:08:12 +0000594/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
595/// GlobalValue being annotated. The second field is the constant string
596/// created from the AnnotateAttr's annotation. The third field is a constant
Nate Begemanfaae0812008-04-19 04:17:09 +0000597/// string containing the name of the translation unit. The fourth field is
598/// the line number in the file of the annotated value declaration.
599///
600/// FIXME: this does not unique the annotation string constants, as llvm-gcc
601/// appears to.
602///
Mike Stump11289f42009-09-09 15:08:12 +0000603llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +0000604 const AnnotateAttr *AA,
605 unsigned LineNo) {
606 llvm::Module *M = &getModule();
607
608 // get [N x i8] constants for the annotation string, and the filename string
609 // which are the 2nd and 3rd elements of the global annotation structure.
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000610 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump11289f42009-09-09 15:08:12 +0000611 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
Owen Anderson41a75022009-08-13 21:57:51 +0000612 AA->getAnnotation(), true);
613 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
614 M->getModuleIdentifier(),
Nate Begemanfaae0812008-04-19 04:17:09 +0000615 true);
616
617 // Get the two global values corresponding to the ConstantArrays we just
618 // created to hold the bytes of the strings.
Mike Stump11289f42009-09-09 15:08:12 +0000619 llvm::GlobalValue *annoGV =
Chris Lattner3afa3e12009-07-16 05:03:48 +0000620 new llvm::GlobalVariable(*M, anno->getType(), false,
621 llvm::GlobalValue::PrivateLinkage, anno,
622 GV->getName());
Nate Begemanfaae0812008-04-19 04:17:09 +0000623 // translation unit name string, emitted into the llvm.metadata section.
624 llvm::GlobalValue *unitGV =
Chris Lattner3afa3e12009-07-16 05:03:48 +0000625 new llvm::GlobalVariable(*M, unit->getType(), false,
Mike Stump11289f42009-09-09 15:08:12 +0000626 llvm::GlobalValue::PrivateLinkage, unit,
Chris Lattner3afa3e12009-07-16 05:03:48 +0000627 ".str");
Rafael Espindola2e217d62011-01-17 22:22:52 +0000628 unitGV->setUnnamedAddr(true);
Nate Begemanfaae0812008-04-19 04:17:09 +0000629
Daniel Dunbar346892a2009-04-14 22:41:13 +0000630 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +0000631 llvm::Constant *Fields[4] = {
Owen Andersonade90fd2009-07-29 18:54:39 +0000632 llvm::ConstantExpr::getBitCast(GV, SBP),
633 llvm::ConstantExpr::getBitCast(annoGV, SBP),
634 llvm::ConstantExpr::getBitCast(unitGV, SBP),
Owen Anderson41a75022009-08-13 21:57:51 +0000635 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
Nate Begemanfaae0812008-04-19 04:17:09 +0000636 };
Owen Anderson758428f2009-08-05 23:18:46 +0000637 return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
Nate Begemanfaae0812008-04-19 04:17:09 +0000638}
639
Argyrios Kyrtzidisc0279a92010-07-27 22:37:14 +0000640bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000641 // Never defer when EmitAllDecls is specified.
642 if (Features.EmitAllDecls)
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000643 return false;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000644
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +0000645 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000646}
647
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000648llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
649 const AliasAttr *AA = VD->getAttr<AliasAttr>();
650 assert(AA && "No alias?");
651
652 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
653
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000654 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +0000655 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000656
657 llvm::Constant *Aliasee;
658 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson3c239482011-02-05 04:35:53 +0000659 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
660 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000661 else
John McCall7ec50432010-03-19 23:29:14 +0000662 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000663 llvm::PointerType::getUnqual(DeclTy), 0);
664 if (!Entry) {
665 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
666 F->setLinkage(llvm::Function::ExternalWeakLinkage);
667 WeakRefReferences.insert(F);
668 }
669
670 return Aliasee;
671}
672
Chris Lattnere0be0df2009-05-12 21:21:08 +0000673void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000674 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000675
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000676 // Weak references don't produce any output by themselves.
677 if (Global->hasAttr<WeakRefAttr>())
678 return;
679
Chris Lattner54041692009-03-22 21:47:11 +0000680 // If this is an alias definition (which otherwise looks like a declaration)
681 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000682 if (Global->hasAttr<AliasAttr>())
John McCall7ec50432010-03-19 23:29:14 +0000683 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000684
Chris Lattner45470942009-03-21 09:44:56 +0000685 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar4e004ed2009-03-19 08:27:24 +0000686 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar3348e2d2010-07-16 00:00:19 +0000687 if (FD->getIdentifier()) {
688 llvm::StringRef Name = FD->getName();
689 if (Name == "_Block_object_assign") {
690 BlockObjectAssignDecl = FD;
691 } else if (Name == "_Block_object_dispose") {
692 BlockObjectDisposeDecl = FD;
693 }
694 }
695
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000696 // Forward declarations are emitted lazily on first use.
697 if (!FD->isThisDeclarationADefinition())
698 return;
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000699 } else {
700 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000701 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
702
Daniel Dunbar3348e2d2010-07-16 00:00:19 +0000703 if (VD->getIdentifier()) {
704 llvm::StringRef Name = VD->getName();
705 if (Name == "_NSConcreteGlobalBlock") {
706 NSConcreteGlobalBlockDecl = VD;
707 } else if (Name == "_NSConcreteStackBlock") {
708 NSConcreteStackBlockDecl = VD;
709 }
710 }
711
712
Douglas Gregor61f6db52010-02-06 05:15:45 +0000713 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorbeecd582009-04-21 17:11:58 +0000714 return;
Nate Begeman8e8d4982008-04-20 06:29:50 +0000715 }
716
Chris Lattner45470942009-03-21 09:44:56 +0000717 // Defer code generation when possible if this is a static definition, inline
718 // function etc. These we only want to emit if they are used.
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000719 if (!MayDeferGeneration(Global)) {
720 // Emit the definition if it can't be deferred.
721 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000722 return;
723 }
John McCall70013b62010-07-15 23:40:35 +0000724
725 // If we're deferring emission of a C++ variable with an
726 // initializer, remember the order in which it appeared in the file.
727 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
728 cast<VarDecl>(Global)->hasInit()) {
729 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
730 CXXGlobalInits.push_back(0);
731 }
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000732
733 // If the value has already been used, add it directly to the
734 // DeferredDeclsToEmit list.
Anders Carlssonea836bc2010-06-22 16:16:50 +0000735 llvm::StringRef MangledName = getMangledName(GD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000736 if (GetGlobalValue(MangledName))
737 DeferredDeclsToEmit.push_back(GD);
738 else {
739 // Otherwise, remember that we saw a deferred decl with this name. The
740 // first use of the mangled name will cause it to move into
741 // DeferredDeclsToEmit.
742 DeferredDecls[MangledName] = GD;
743 }
Nate Begeman8e8d4982008-04-20 06:29:50 +0000744}
745
Chris Lattnere0be0df2009-05-12 21:21:08 +0000746void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000747 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000748
Dan Gohman145f3f12010-04-19 16:39:44 +0000749 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +0000750 Context.getSourceManager(),
751 "Generating code for declaration");
752
Douglas Gregora700f682010-07-13 06:02:28 +0000753 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
754 // At -O0, don't generate IR for functions with available_externally
755 // linkage.
Douglas Gregor89976902010-07-15 22:58:18 +0000756 if (CodeGenOpts.OptimizationLevel == 0 &&
757 !Function->hasAttr<AlwaysInlineAttr>() &&
Douglas Gregora700f682010-07-13 06:02:28 +0000758 getFunctionLinkage(Function)
759 == llvm::Function::AvailableExternallyLinkage)
760 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +0000761
Douglas Gregora700f682010-07-13 06:02:28 +0000762 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
763 if (Method->isVirtual())
764 getVTables().EmitThunks(GD);
765
766 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
767 return EmitCXXConstructor(CD, GD.getCtorType());
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000768
Douglas Gregora700f682010-07-13 06:02:28 +0000769 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
770 return EmitCXXDestructor(DD, GD.getDtorType());
771 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000772
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000773 return EmitGlobalFunctionDefinition(GD);
Douglas Gregora700f682010-07-13 06:02:28 +0000774 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000775
776 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
777 return EmitGlobalVarDefinition(VD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000778
779 assert(0 && "Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +0000780}
781
Chris Lattnerd4808922009-03-22 21:03:39 +0000782/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
783/// module, create and return an llvm Function with the specified type. If there
784/// is something in the module with the specified name, return it potentially
785/// bitcasted to the right type.
786///
787/// If D is non-null, it specifies a decl that correspond to this. This is used
788/// to set the attributes on the function when it is first created.
John McCall7ec50432010-03-19 23:29:14 +0000789llvm::Constant *
790CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
791 const llvm::Type *Ty,
Anders Carlsson3c239482011-02-05 04:35:53 +0000792 GlobalDecl D, bool ForVTable) {
Chris Lattnera85d68e2009-03-21 09:25:43 +0000793 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +0000794 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000795 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000796 if (WeakRefReferences.count(Entry)) {
797 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
798 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +0000799 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000800
801 WeakRefReferences.erase(Entry);
802 }
803
Chris Lattnera85d68e2009-03-21 09:25:43 +0000804 if (Entry->getType()->getElementType() == Ty)
805 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000806
Chris Lattnera85d68e2009-03-21 09:25:43 +0000807 // Make sure the result is of the correct type.
Owen Anderson9793f0e2009-07-29 22:16:19 +0000808 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Owen Andersonade90fd2009-07-29 18:54:39 +0000809 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000810 }
Mike Stump11289f42009-09-09 15:08:12 +0000811
Eli Friedmancc522d92009-11-09 05:07:37 +0000812 // This function doesn't have a complete type (for example, the return
813 // type is an incomplete struct). Use a fake type instead, and make
814 // sure not to try to set attributes.
815 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +0000816
817 const llvm::FunctionType *FTy;
818 if (isa<llvm::FunctionType>(Ty)) {
819 FTy = cast<llvm::FunctionType>(Ty);
820 } else {
Benjamin Kramer1e188892011-01-22 12:15:57 +0000821 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
Eli Friedmancc522d92009-11-09 05:07:37 +0000822 IsIncompleteFunction = true;
823 }
Chris Lattner5c740f12010-06-30 19:14:05 +0000824
John McCalld06fb862010-04-28 00:00:30 +0000825 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedmancc522d92009-11-09 05:07:37 +0000826 llvm::Function::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +0000827 MangledName, &getModule());
828 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedmancc522d92009-11-09 05:07:37 +0000829 if (D.getDecl())
Anders Carlsson6710c532010-02-06 02:44:09 +0000830 SetFunctionAttributes(D, F, IsIncompleteFunction);
Eli Friedmancc522d92009-11-09 05:07:37 +0000831
Chris Lattner45470942009-03-21 09:44:56 +0000832 // This is the first use or definition of a mangled name. If there is a
833 // deferred decl with this name, remember that we need to emit it at the end
834 // of the file.
John McCall7ec50432010-03-19 23:29:14 +0000835 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +0000836 if (DDI != DeferredDecls.end()) {
837 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
838 // list, and remove it from DeferredDecls (since we don't need it anymore).
839 DeferredDeclsToEmit.push_back(DDI->second);
840 DeferredDecls.erase(DDI);
John McCall357d0f32010-12-15 04:00:32 +0000841
842 // Otherwise, there are cases we have to worry about where we're
843 // using a declaration for which we must emit a definition but where
844 // we might not find a top-level definition:
845 // - member functions defined inline in their classes
846 // - friend functions defined inline in some class
847 // - special member functions with implicit definitions
848 // If we ever change our AST traversal to walk into class methods,
849 // this will be unnecessary.
Anders Carlsson3c239482011-02-05 04:35:53 +0000850 //
851 // We also don't emit a definition for a function if it's going to be an entry
852 // in a vtable, unless it's already marked as used.
Rafael Espindolaaf5b92e2011-02-03 06:30:58 +0000853 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
John McCall357d0f32010-12-15 04:00:32 +0000854 // Look for a declaration that's lexically in a record.
855 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
856 do {
857 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Anders Carlsson3c239482011-02-05 04:35:53 +0000858 if (FD->isImplicit() && !ForVTable) {
John McCall357d0f32010-12-15 04:00:32 +0000859 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
860 DeferredDeclsToEmit.push_back(D);
861 break;
862 } else if (FD->isThisDeclarationADefinition()) {
863 DeferredDeclsToEmit.push_back(D);
864 break;
865 }
Rafael Espindola70e040d2010-03-02 21:28:26 +0000866 }
John McCall357d0f32010-12-15 04:00:32 +0000867 FD = FD->getPreviousDeclaration();
868 } while (FD);
Chris Lattner45470942009-03-21 09:44:56 +0000869 }
Mike Stump11289f42009-09-09 15:08:12 +0000870
John McCalld06fb862010-04-28 00:00:30 +0000871 // Make sure the result is of the requested type.
872 if (!IsIncompleteFunction) {
873 assert(F->getType()->getElementType() == Ty);
874 return F;
875 }
876
877 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
878 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000879}
880
Chris Lattnerd4808922009-03-22 21:03:39 +0000881/// GetAddrOfFunction - Return the address of the given function. If Ty is
882/// non-null, then this function will use the specified type if it has to
883/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +0000884llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Anders Carlsson3c239482011-02-05 04:35:53 +0000885 const llvm::Type *Ty,
886 bool ForVTable) {
Chris Lattnerd4808922009-03-22 21:03:39 +0000887 // If there was no specific requested type, just convert it now.
888 if (!Ty)
Anders Carlsson38988d72009-09-10 23:38:47 +0000889 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattner5c740f12010-06-30 19:14:05 +0000890
Anders Carlssonea836bc2010-06-22 16:16:50 +0000891 llvm::StringRef MangledName = getMangledName(GD);
Anders Carlsson3c239482011-02-05 04:35:53 +0000892 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
Chris Lattnerd4808922009-03-22 21:03:39 +0000893}
Eli Friedmanc18d9d52008-05-30 19:50:47 +0000894
Chris Lattnerd4808922009-03-22 21:03:39 +0000895/// CreateRuntimeFunction - Create a new runtime function with the specified
896/// type and name.
897llvm::Constant *
898CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
John McCall7ec50432010-03-19 23:29:14 +0000899 llvm::StringRef Name) {
Anders Carlsson3c239482011-02-05 04:35:53 +0000900 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false);
Chris Lattnerd4808922009-03-22 21:03:39 +0000901}
Daniel Dunbar9c426522008-07-29 23:18:29 +0000902
Eli Friedmanb095e152009-12-11 21:23:03 +0000903static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
John McCall340aafa2010-02-08 21:46:50 +0000904 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +0000905 return false;
906 if (Context.getLangOptions().CPlusPlus &&
907 Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
908 // FIXME: We should do something fancier here!
909 return false;
910 }
911 return true;
912}
913
Chris Lattnerd4808922009-03-22 21:03:39 +0000914/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
915/// create and return an llvm GlobalVariable with the specified type. If there
916/// is something in the module with the specified name, return it potentially
917/// bitcasted to the right type.
918///
919/// If D is non-null, it specifies a decl that correspond to this. This is used
920/// to set the attributes on the global when it is first created.
John McCall7ec50432010-03-19 23:29:14 +0000921llvm::Constant *
922CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
923 const llvm::PointerType *Ty,
Rafael Espindolad661a852011-01-18 21:07:57 +0000924 const VarDecl *D,
925 bool UnnamedAddr) {
Daniel Dunbar829e9882008-08-05 23:31:02 +0000926 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +0000927 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +0000928 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000929 if (WeakRefReferences.count(Entry)) {
930 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +0000931 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000932
933 WeakRefReferences.erase(Entry);
934 }
935
Rafael Espindolad661a852011-01-18 21:07:57 +0000936 if (UnnamedAddr)
937 Entry->setUnnamedAddr(true);
938
Chris Lattnerd4808922009-03-22 21:03:39 +0000939 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +0000940 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattner3bfce182009-03-21 08:03:33 +0000942 // Make sure the result is of the correct type.
Owen Andersonade90fd2009-07-29 18:54:39 +0000943 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +0000944 }
Mike Stump11289f42009-09-09 15:08:12 +0000945
Chris Lattner45470942009-03-21 09:44:56 +0000946 // This is the first use or definition of a mangled name. If there is a
947 // deferred decl with this name, remember that we need to emit it at the end
948 // of the file.
John McCall7ec50432010-03-19 23:29:14 +0000949 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +0000950 if (DDI != DeferredDecls.end()) {
951 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
952 // list, and remove it from DeferredDecls (since we don't need it anymore).
953 DeferredDeclsToEmit.push_back(DDI->second);
954 DeferredDecls.erase(DDI);
955 }
Mike Stump11289f42009-09-09 15:08:12 +0000956
957 llvm::GlobalVariable *GV =
958 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner3bfce182009-03-21 08:03:33 +0000959 llvm::GlobalValue::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +0000960 0, MangledName, 0,
Eli Friedman4f856742009-04-19 21:05:03 +0000961 false, Ty->getAddressSpace());
Chris Lattner3bfce182009-03-21 08:03:33 +0000962
963 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +0000964 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +0000965 // FIXME: This code is overly simple and should be merged with other global
966 // handling.
Eli Friedmanb095e152009-12-11 21:23:03 +0000967 GV->setConstant(DeclIsConstantGlobal(Context, D));
Chris Lattner3bfce182009-03-21 08:03:33 +0000968
John McCall37bb6c92010-10-29 22:22:43 +0000969 // Set linkage and visibility in case we never see a definition.
John McCallc273f242010-10-30 11:50:40 +0000970 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
971 if (LV.linkage() != ExternalLinkage) {
John McCall37bb6c92010-10-29 22:22:43 +0000972 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
973 } else {
974 if (D->hasAttr<DLLImportAttr>())
975 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
976 else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
977 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner3bfce182009-03-21 08:03:33 +0000978
John McCallc273f242010-10-30 11:50:40 +0000979 // Set visibility on a declaration only if it's explicit.
980 if (LV.visibilityExplicit())
981 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall37bb6c92010-10-29 22:22:43 +0000982 }
Eli Friedman4f856742009-04-19 21:05:03 +0000983
984 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattnerd4808922009-03-22 21:03:39 +0000985 }
Mike Stump11289f42009-09-09 15:08:12 +0000986
John McCall7ec50432010-03-19 23:29:14 +0000987 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000988}
989
Chris Lattnerd4808922009-03-22 21:03:39 +0000990
Anders Carlssonda80af32011-01-29 18:20:20 +0000991llvm::GlobalVariable *
992CodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
993 const llvm::Type *Ty,
994 llvm::GlobalValue::LinkageTypes Linkage) {
995 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
996 llvm::GlobalVariable *OldGV = 0;
997
998
999 if (GV) {
1000 // Check if the variable has the right type.
1001 if (GV->getType()->getElementType() == Ty)
1002 return GV;
1003
1004 // Because C++ name mangling, the only way we can end up with an already
1005 // existing global with the same name is if it has been declared extern "C".
Anders Carlsson93be9a92011-01-29 18:25:07 +00001006 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00001007 OldGV = GV;
1008 }
1009
1010 // Create a new variable.
1011 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1012 Linkage, 0, Name);
1013
1014 if (OldGV) {
1015 // Replace occurrences of the old variable if needed.
1016 GV->takeName(OldGV);
1017
1018 if (!OldGV->use_empty()) {
1019 llvm::Constant *NewPtrForOldDecl =
1020 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1021 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1022 }
1023
1024 OldGV->eraseFromParent();
1025 }
1026
1027 return GV;
1028}
1029
Chris Lattnerd4808922009-03-22 21:03:39 +00001030/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1031/// given global variable. If Ty is non-null and if the global doesn't exist,
1032/// then it will be greated with the specified type instead of whatever the
1033/// normal requested type would be.
1034llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1035 const llvm::Type *Ty) {
1036 assert(D->hasGlobalStorage() && "Not a global variable");
1037 QualType ASTTy = D->getType();
1038 if (Ty == 0)
1039 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00001040
1041 const llvm::PointerType *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001042 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
John McCall7ec50432010-03-19 23:29:14 +00001043
Anders Carlssonea836bc2010-06-22 16:16:50 +00001044 llvm::StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001045 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001046}
1047
1048/// CreateRuntimeVariable - Create a new runtime global variable with the
1049/// specified type and name.
1050llvm::Constant *
1051CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
John McCall7ec50432010-03-19 23:29:14 +00001052 llvm::StringRef Name) {
Rafael Espindolad661a852011-01-18 21:07:57 +00001053 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1054 true);
Chris Lattnerd4808922009-03-22 21:03:39 +00001055}
1056
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001057void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1058 assert(!D->getInit() && "Cannot emit definite definitions here!");
1059
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001060 if (MayDeferGeneration(D)) {
1061 // If we have not seen a reference to this variable yet, place it
1062 // into the deferred declarations table to be emitted if needed
1063 // later.
Anders Carlssonea836bc2010-06-22 16:16:50 +00001064 llvm::StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001065 if (!GetGlobalValue(MangledName)) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001066 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001067 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001068 }
1069 }
1070
1071 // The tentative definition is the only definition.
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001072 EmitGlobalVarDefinition(D);
1073}
1074
Douglas Gregor88d292c2010-05-13 16:44:06 +00001075void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1076 if (DefinitionRequired)
1077 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1078}
1079
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001080llvm::GlobalVariable::LinkageTypes
Anders Carlsson11e51402010-04-17 20:15:18 +00001081CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Douglas Gregor2a34df32010-01-06 22:00:56 +00001082 if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1083 return llvm::GlobalVariable::InternalLinkage;
1084
1085 if (const CXXMethodDecl *KeyFunction
1086 = RD->getASTContext().getKeyFunction(RD)) {
1087 // If this class has a key function, use that to determine the linkage of
1088 // the vtable.
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001089 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001090 if (KeyFunction->hasBody(Def))
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001091 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregor2a34df32010-01-06 22:00:56 +00001092
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001093 switch (KeyFunction->getTemplateSpecializationKind()) {
1094 case TSK_Undeclared:
1095 case TSK_ExplicitSpecialization:
Anders Carlssona03f3a82011-01-30 20:45:54 +00001096 // When compiling with optimizations turned on, we emit all vtables,
1097 // even if the key function is not defined in the current translation
1098 // unit. If this is the case, use available_externally linkage.
1099 if (!Def && CodeGenOpts.OptimizationLevel)
1100 return llvm::GlobalVariable::AvailableExternallyLinkage;
1101
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001102 if (KeyFunction->isInlined())
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00001103 return !Context.getLangOptions().AppleKext ?
1104 llvm::GlobalVariable::LinkOnceODRLinkage :
1105 llvm::Function::InternalLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001106
1107 return llvm::GlobalVariable::ExternalLinkage;
1108
1109 case TSK_ImplicitInstantiation:
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00001110 return !Context.getLangOptions().AppleKext ?
1111 llvm::GlobalVariable::LinkOnceODRLinkage :
1112 llvm::Function::InternalLinkage;
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001113
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001114 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00001115 return !Context.getLangOptions().AppleKext ?
1116 llvm::GlobalVariable::WeakODRLinkage :
1117 llvm::Function::InternalLinkage;
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001118
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001119 case TSK_ExplicitInstantiationDeclaration:
1120 // FIXME: Use available_externally linkage. However, this currently
1121 // breaks LLVM's build due to undefined symbols.
1122 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00001123 return !Context.getLangOptions().AppleKext ?
1124 llvm::GlobalVariable::LinkOnceODRLinkage :
1125 llvm::Function::InternalLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001126 }
Douglas Gregor2a34df32010-01-06 22:00:56 +00001127 }
1128
Fariborz Jahaniane28342c2011-02-04 00:32:39 +00001129 if (Context.getLangOptions().AppleKext)
1130 return llvm::Function::InternalLinkage;
1131
Douglas Gregor2a34df32010-01-06 22:00:56 +00001132 switch (RD->getTemplateSpecializationKind()) {
1133 case TSK_Undeclared:
1134 case TSK_ExplicitSpecialization:
1135 case TSK_ImplicitInstantiation:
Douglas Gregor2a34df32010-01-06 22:00:56 +00001136 // FIXME: Use available_externally linkage. However, this currently
1137 // breaks LLVM's build due to undefined symbols.
1138 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00001139 case TSK_ExplicitInstantiationDeclaration:
Fariborz Jahaniane28342c2011-02-04 00:32:39 +00001140 return llvm::GlobalVariable::LinkOnceODRLinkage;
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00001141
1142 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahaniane28342c2011-02-04 00:32:39 +00001143 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001144 }
1145
1146 // Silence GCC warning.
Fariborz Jahaniane28342c2011-02-04 00:32:39 +00001147 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001148}
1149
Ken Dyck98ca7942010-01-26 13:48:07 +00001150CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
Ken Dyck9a648692011-01-18 02:01:14 +00001151 return Context.toCharUnitsFromBits(
1152 TheTargetData.getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00001153}
1154
Daniel Dunbar9c426522008-07-29 23:18:29 +00001155void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001156 llvm::Constant *Init = 0;
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001157 QualType ASTTy = D->getType();
Eli Friedman5866fe32010-01-08 00:50:11 +00001158 bool NonConstInit = false;
Mike Stump11289f42009-09-09 15:08:12 +00001159
Sebastian Redl5ca79842010-02-01 20:16:42 +00001160 const Expr *InitExpr = D->getAnyInitializer();
Anders Carlssonca4a5452010-01-26 17:43:42 +00001161
1162 if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00001163 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001164 // implicitly initialized with { 0 }.
1165 //
1166 // Note that tentative definitions are only emitted at the end of
1167 // a translation unit, so they should never have incomplete
1168 // type. In addition, EmitTentativeDefinition makes sure that we
1169 // never attempt to emit a tentative definition if a real one
1170 // exists. A use may still exists, however, so we still may need
1171 // to do a RAUW.
1172 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00001173 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001174 } else {
Douglas Gregord450f062010-05-05 20:15:55 +00001175 Init = EmitConstantExpr(InitExpr, D->getType());
Eli Friedman719ed1a2009-02-20 01:18:21 +00001176 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00001177 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00001178 if (D->getType()->isReferenceType())
1179 T = D->getType();
1180
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001181 if (getLangOptions().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001182 Init = EmitNullConstant(T);
Eli Friedman5866fe32010-01-08 00:50:11 +00001183 NonConstInit = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001184 } else {
1185 ErrorUnsupported(D, "static initializer");
1186 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1187 }
John McCall70013b62010-07-15 23:40:35 +00001188 } else {
1189 // We don't need an initializer, so remove the entry for the delayed
1190 // initializer position (just in case this entry was delayed).
1191 if (getLangOptions().CPlusPlus)
1192 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00001193 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001194 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001195
Chris Lattner64c55932009-03-21 08:13:05 +00001196 const llvm::Type* InitType = Init->getType();
Chris Lattner149927c2009-03-21 09:16:30 +00001197 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump11289f42009-09-09 15:08:12 +00001198
Chris Lattner149927c2009-03-21 09:16:30 +00001199 // Strip off a bitcast if we got one back.
1200 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00001201 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1202 // all zero index gep.
1203 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00001204 Entry = CE->getOperand(0);
1205 }
Mike Stump11289f42009-09-09 15:08:12 +00001206
Chris Lattner149927c2009-03-21 09:16:30 +00001207 // Entry is now either a Function or GlobalVariable.
1208 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001209
Chris Lattner149927c2009-03-21 09:16:30 +00001210 // We have a definition after a declaration with the wrong type.
1211 // We must make a new GlobalVariable* and update everything that used OldGV
1212 // (a declaration or tentative definition) with the new GlobalVariable*
1213 // (which will be a definition).
1214 //
1215 // This happens if there is a prototype for a global (e.g.
1216 // "extern int x[];") and then a definition of a different type (e.g.
1217 // "int x[10];"). This also happens when an initializer has a different type
1218 // from the type of the global (this happens with unions).
Chris Lattner149927c2009-03-21 09:16:30 +00001219 if (GV == 0 ||
1220 GV->getType()->getElementType() != InitType ||
1221 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
Mike Stump11289f42009-09-09 15:08:12 +00001222
John McCall7ec50432010-03-19 23:29:14 +00001223 // Move the old entry aside so that we'll create a new one.
1224 Entry->setName(llvm::StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00001225
Chris Lattner149927c2009-03-21 09:16:30 +00001226 // Make a new global with the correct type, this is now guaranteed to work.
1227 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattnera85d68e2009-03-21 09:25:43 +00001228
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001229 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00001230 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001231 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00001232 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001233
1234 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00001235 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001236 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00001237
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001238 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begemanfaae0812008-04-19 04:17:09 +00001239 SourceManager &SM = Context.getSourceManager();
1240 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner8a425862009-01-16 07:36:28 +00001241 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begemanfaae0812008-04-19 04:17:09 +00001242 }
1243
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001244 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001245
1246 // If it is safe to mark the global 'constant', do so now.
1247 GV->setConstant(false);
Eli Friedman5866fe32010-01-08 00:50:11 +00001248 if (!NonConstInit && DeclIsConstantGlobal(Context, D))
Chris Lattnerf49573d2009-08-05 05:20:29 +00001249 GV->setConstant(true);
Mike Stump11289f42009-09-09 15:08:12 +00001250
Ken Dyck160146e2010-01-27 17:10:57 +00001251 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001252
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001253 // Set the llvm linkage type as appropriate.
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001254 llvm::GlobalValue::LinkageTypes Linkage =
1255 GetLLVMLinkageVarDefinition(D, GV);
1256 GV->setLinkage(Linkage);
1257 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnerf49573d2009-08-05 05:20:29 +00001258 // common vars aren't constant even if declared const.
1259 GV->setConstant(false);
Daniel Dunbard272cca2009-04-10 20:26:50 +00001260
Daniel Dunbar38932572009-04-14 08:05:55 +00001261 SetCommonAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001262
John McCallcdf7ef52010-11-06 09:44:32 +00001263 // Emit the initializer function if necessary.
1264 if (NonConstInit)
1265 EmitCXXGlobalVarDeclInitFunc(D, GV);
1266
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001267 // Emit global variable debug information.
Chris Lattner64c55932009-03-21 08:13:05 +00001268 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +00001269 DI->setLocation(D->getLocation());
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001270 DI->EmitGlobalVariable(GV, D);
1271 }
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001272}
Chris Lattner09153c02007-06-22 18:48:09 +00001273
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001274llvm::GlobalValue::LinkageTypes
1275CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1276 llvm::GlobalVariable *GV) {
1277 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1278 if (Linkage == GVA_Internal)
1279 return llvm::Function::InternalLinkage;
1280 else if (D->hasAttr<DLLImportAttr>())
1281 return llvm::Function::DLLImportLinkage;
1282 else if (D->hasAttr<DLLExportAttr>())
1283 return llvm::Function::DLLExportLinkage;
1284 else if (D->hasAttr<WeakAttr>()) {
1285 if (GV->isConstant())
1286 return llvm::GlobalVariable::WeakODRLinkage;
1287 else
1288 return llvm::GlobalVariable::WeakAnyLinkage;
1289 } else if (Linkage == GVA_TemplateInstantiation ||
1290 Linkage == GVA_ExplicitTemplateInstantiation)
1291 // FIXME: It seems like we can provide more specific linkage here
1292 // (LinkOnceODR, WeakODR).
1293 return llvm::GlobalVariable::WeakAnyLinkage;
Eric Christopher8a2ee392010-12-02 02:45:55 +00001294 else if (!getLangOptions().CPlusPlus &&
1295 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1296 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001297 !D->hasExternalStorage() && !D->getInit() &&
1298 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
1299 // Thread local vars aren't considered common linkage.
1300 return llvm::GlobalVariable::CommonLinkage;
1301 }
1302 return llvm::GlobalVariable::ExternalLinkage;
1303}
1304
Chris Lattner36797ab2009-05-05 06:16:31 +00001305/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1306/// implement a function with no prototype, e.g. "int foo() {}". If there are
1307/// existing call uses of the old function in the module, this adjusts them to
1308/// call the new function directly.
1309///
1310/// This is not just a cleanup: the always_inline pass requires direct calls to
1311/// functions to be able to inline them. If there is a bitcast in the way, it
1312/// won't inline them. Instcombine normally deletes these calls, but it isn't
1313/// run at -O0.
1314static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1315 llvm::Function *NewFn) {
1316 // If we're redefining a global as a function, don't transform it.
1317 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1318 if (OldFn == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +00001319
Chris Lattner36797ab2009-05-05 06:16:31 +00001320 const llvm::Type *NewRetTy = NewFn->getReturnType();
1321 llvm::SmallVector<llvm::Value*, 4> ArgList;
1322
1323 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001324 UI != E; ) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001325 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001326 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1327 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greif79ac9ed2010-07-28 09:19:33 +00001328 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
Gabor Greifd394aec2010-04-10 03:45:50 +00001329 llvm::CallSite CS(CI);
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001330 if (!CI || !CS.isCallee(I)) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001331
Chris Lattner36797ab2009-05-05 06:16:31 +00001332 // If the return types don't match exactly, and if the call isn't dead, then
1333 // we can't transform this call.
1334 if (CI->getType() != NewRetTy && !CI->use_empty())
1335 continue;
1336
1337 // If the function was passed too few arguments, don't transform. If extra
1338 // arguments were passed, we silently drop them. If any of the types
1339 // mismatch, we don't transform.
1340 unsigned ArgNo = 0;
1341 bool DontTransform = false;
1342 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1343 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greifd394aec2010-04-10 03:45:50 +00001344 if (CS.arg_size() == ArgNo ||
1345 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001346 DontTransform = true;
1347 break;
1348 }
1349 }
1350 if (DontTransform)
1351 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001352
Chris Lattner36797ab2009-05-05 06:16:31 +00001353 // Okay, we can transform this. Create the new call instruction and copy
1354 // over the required information.
Gabor Greifd0ef1342010-04-10 02:56:12 +00001355 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Chris Lattner36797ab2009-05-05 06:16:31 +00001356 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1357 ArgList.end(), "", CI);
1358 ArgList.clear();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00001359 if (!NewCall->getType()->isVoidTy())
Chris Lattner36797ab2009-05-05 06:16:31 +00001360 NewCall->takeName(CI);
Chris Lattner36797ab2009-05-05 06:16:31 +00001361 NewCall->setAttributes(CI->getAttributes());
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001362 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattner36797ab2009-05-05 06:16:31 +00001363
1364 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner734351d2009-10-14 05:49:21 +00001365 if (!CI->use_empty())
1366 CI->replaceAllUsesWith(NewCall);
Devang Patel74684892009-10-13 17:02:04 +00001367
Chris Lattnere675d0f2010-04-01 06:31:43 +00001368 // Copy debug location attached to CI.
1369 if (!CI->getDebugLoc().isUnknown())
1370 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattner36797ab2009-05-05 06:16:31 +00001371 CI->eraseFromParent();
1372 }
1373}
1374
Daniel Dunbar9c426522008-07-29 23:18:29 +00001375
Chris Lattnere0be0df2009-05-12 21:21:08 +00001376void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnere0be0df2009-05-12 21:21:08 +00001377 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCallf8ff7b92010-02-23 00:48:20 +00001378 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
Chris Lattnereb7466d2009-05-12 20:58:15 +00001379 // Get or create the prototype for the function.
Chris Lattnere0be0df2009-05-12 21:21:08 +00001380 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001381
Chris Lattnera85d68e2009-03-21 09:25:43 +00001382 // Strip off a bitcast if we got one back.
1383 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1384 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1385 Entry = CE->getOperand(0);
1386 }
Mike Stump11289f42009-09-09 15:08:12 +00001387
1388
Chris Lattnera85d68e2009-03-21 09:25:43 +00001389 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001390 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001391
Daniel Dunbar99d28352009-03-09 23:53:08 +00001392 // If the types mismatch then we have to rewrite the definition.
Chris Lattner36797ab2009-05-05 06:16:31 +00001393 assert(OldFn->isDeclaration() &&
Chris Lattnera85d68e2009-03-21 09:25:43 +00001394 "Shouldn't replace non-declaration");
Chris Lattner832323e2009-03-21 08:53:37 +00001395
Chris Lattner5eaee562009-03-21 08:38:50 +00001396 // F is the Function* for the one with the wrong type, we must make a new
1397 // Function* and update everything that used F (a declaration) with the new
1398 // Function* (which will be a definition).
1399 //
1400 // This happens if there is a prototype for a function
1401 // (e.g. "int f()") and then a definition of a different type
John McCall7ec50432010-03-19 23:29:14 +00001402 // (e.g. "int f(int x)"). Move the old function aside so that it
1403 // doesn't interfere with GetAddrOfFunction.
1404 OldFn->setName(llvm::StringRef());
Chris Lattnere0be0df2009-05-12 21:21:08 +00001405 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump11289f42009-09-09 15:08:12 +00001406
Chris Lattner36797ab2009-05-05 06:16:31 +00001407 // If this is an implementation of a function without a prototype, try to
1408 // replace any existing uses of the function (which may be calls) with uses
1409 // of the new function
Chris Lattnereb7466d2009-05-12 20:58:15 +00001410 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001411 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattnereb7466d2009-05-12 20:58:15 +00001412 OldFn->removeDeadConstantUsers();
1413 }
Mike Stump11289f42009-09-09 15:08:12 +00001414
Chris Lattner5eaee562009-03-21 08:38:50 +00001415 // Replace uses of F with the Function we will endow with a body.
Chris Lattner36797ab2009-05-05 06:16:31 +00001416 if (!Entry->use_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00001417 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001418 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattner36797ab2009-05-05 06:16:31 +00001419 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1420 }
Mike Stump11289f42009-09-09 15:08:12 +00001421
Chris Lattner5eaee562009-03-21 08:38:50 +00001422 // Ok, delete the old function now, which is dead.
Chris Lattner36797ab2009-05-05 06:16:31 +00001423 OldFn->eraseFromParent();
Mike Stump11289f42009-09-09 15:08:12 +00001424
Chris Lattnera85d68e2009-03-21 09:25:43 +00001425 Entry = NewFn;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001426 }
Mike Stump11289f42009-09-09 15:08:12 +00001427
John McCall8e7cb6d2010-11-02 21:04:24 +00001428 // We need to set linkage and visibility on the function before
1429 // generating code for it because various parts of IR generation
1430 // want to propagate this information down (e.g. to local static
1431 // declarations).
Chris Lattnera85d68e2009-03-21 09:25:43 +00001432 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall7cb02202010-05-25 04:30:21 +00001433 setFunctionLinkage(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001434
John McCall8e7cb6d2010-11-02 21:04:24 +00001435 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlssonc6a47892011-01-29 19:39:23 +00001436 setGlobalVisibility(Fn, D);
John McCall8e7cb6d2010-11-02 21:04:24 +00001437
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001438 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001439
Daniel Dunbar38932572009-04-14 08:05:55 +00001440 SetFunctionDefinitionAttributes(D, Fn);
1441 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00001442
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001443 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001444 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001445 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001446 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar9c426522008-07-29 23:18:29 +00001447}
1448
John McCall7ec50432010-03-19 23:29:14 +00001449void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1450 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001451 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00001452 assert(AA && "Not an alias?");
1453
Anders Carlssonea836bc2010-06-22 16:16:50 +00001454 llvm::StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00001455
John McCall7ec50432010-03-19 23:29:14 +00001456 // If there is a definition in the module, then it wins over the alias.
1457 // This is dubious, but allow it to be safe. Just ignore the alias.
1458 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1459 if (Entry && !Entry->isDeclaration())
1460 return;
1461
1462 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00001463
1464 // Create a reference to the named value. This ensures that it is emitted
1465 // if a deferred decl.
1466 llvm::Constant *Aliasee;
1467 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson3c239482011-02-05 04:35:53 +00001468 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1469 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00001470 else
John McCall7ec50432010-03-19 23:29:14 +00001471 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson9793f0e2009-07-29 22:16:19 +00001472 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattner54041692009-03-22 21:47:11 +00001473
1474 // Create the new alias itself, but don't set a name yet.
Mike Stump11289f42009-09-09 15:08:12 +00001475 llvm::GlobalValue *GA =
Chris Lattner54041692009-03-22 21:47:11 +00001476 new llvm::GlobalAlias(Aliasee->getType(),
1477 llvm::Function::ExternalLinkage,
1478 "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00001479
Chris Lattner54041692009-03-22 21:47:11 +00001480 if (Entry) {
John McCall7ec50432010-03-19 23:29:14 +00001481 assert(Entry->isDeclaration());
1482
Chris Lattner54041692009-03-22 21:47:11 +00001483 // If there is a declaration in the module, then we had an extern followed
1484 // by the alias, as in:
1485 // extern int test6();
1486 // ...
1487 // int test6() __attribute__((alias("test7")));
1488 //
1489 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00001490 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001491
Owen Andersonade90fd2009-07-29 18:54:39 +00001492 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00001493 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00001494 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00001495 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00001496 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00001497 }
Mike Stump11289f42009-09-09 15:08:12 +00001498
Daniel Dunbar38932572009-04-14 08:05:55 +00001499 // Set attributes which are particular to an alias; this is a
1500 // specialization of the attributes which may be set on a global
1501 // variable/function.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001502 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001503 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1504 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001505 if (FD->hasBody())
Daniel Dunbar38932572009-04-14 08:05:55 +00001506 GA->setLinkage(llvm::Function::DLLExportLinkage);
1507 } else {
1508 GA->setLinkage(llvm::Function::DLLExportLinkage);
1509 }
Mike Stump11289f42009-09-09 15:08:12 +00001510 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindolac18086a2010-02-23 22:00:30 +00001511 D->hasAttr<WeakRefAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001512 D->hasAttr<WeakImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001513 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1514 }
1515
1516 SetCommonAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00001517}
1518
Chris Lattnere64911a2009-03-22 21:56:56 +00001519/// getBuiltinLibFunction - Given a builtin id for a function like
1520/// "__builtin_fabsf", return a Function* for "fabsf".
Daniel Dunbarff0553e2009-09-14 04:33:21 +00001521llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1522 unsigned BuiltinID) {
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001523 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
Mike Stump11289f42009-09-09 15:08:12 +00001524 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001525 "isn't a lib fn");
Mike Stump11289f42009-09-09 15:08:12 +00001526
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001527 // Get the name, skip over the __builtin_ prefix (if necessary).
1528 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1529 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1530 Name += 10;
Mike Stump11289f42009-09-09 15:08:12 +00001531
Mike Stump11289f42009-09-09 15:08:12 +00001532 const llvm::FunctionType *Ty =
Eli Friedman4f678f32009-12-09 03:05:59 +00001533 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
Chris Lattner1eec6602007-08-31 04:31:45 +00001534
Anders Carlsson3c239482011-02-05 04:35:53 +00001535 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD), /*ForVTable=*/false);
Chris Lattner1eec6602007-08-31 04:31:45 +00001536}
1537
Chris Lattnerb8be97e2007-12-18 00:25:38 +00001538llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1539 unsigned NumTys) {
1540 return llvm::Intrinsic::getDeclaration(&getModule(),
1541 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1542}
Chris Lattner1eec6602007-08-31 04:31:45 +00001543
Daniel Dunbar64509b22009-07-23 22:52:48 +00001544static llvm::StringMapEntry<llvm::Constant*> &
1545GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1546 const StringLiteral *Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001547 bool TargetIsLSB,
Daniel Dunbar64509b22009-07-23 22:52:48 +00001548 bool &IsUTF16,
1549 unsigned &StringLength) {
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001550 llvm::StringRef String = Literal->getString();
1551 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00001552
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001553 // Check for simple case.
1554 if (!Literal->containsNonAsciiOrNull()) {
1555 StringLength = NumBytes;
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001556 return Map.GetOrCreateValue(String);
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001557 }
1558
Daniel Dunbar64509b22009-07-23 22:52:48 +00001559 // Otherwise, convert the UTF8 literals into a byte string.
1560 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001561 const UTF8 *FromPtr = (UTF8 *)String.data();
Daniel Dunbar64509b22009-07-23 22:52:48 +00001562 UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00001563
Fariborz Jahanian535618b2010-09-07 19:57:04 +00001564 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1565 &ToPtr, ToPtr + NumBytes,
1566 strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00001567
Daniel Dunbar91ade142009-07-23 23:41:22 +00001568 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00001569 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00001570
1571 // Render the UTF-16 string into a byte array and convert to the target byte
1572 // order.
1573 //
1574 // FIXME: This isn't something we should need to do here.
1575 llvm::SmallString<128> AsBytes;
1576 AsBytes.reserve(StringLength * 2);
1577 for (unsigned i = 0; i != StringLength; ++i) {
1578 unsigned short Val = ToBuf[i];
1579 if (TargetIsLSB) {
1580 AsBytes.push_back(Val & 0xFF);
1581 AsBytes.push_back(Val >> 8);
1582 } else {
1583 AsBytes.push_back(Val >> 8);
1584 AsBytes.push_back(Val & 0xFF);
1585 }
1586 }
Daniel Dunbar4d93a4f2009-08-03 21:47:08 +00001587 // Append one extra null character, the second is automatically added by our
1588 // caller.
1589 AsBytes.push_back(0);
Daniel Dunbar91ade142009-07-23 23:41:22 +00001590
Daniel Dunbar64509b22009-07-23 22:52:48 +00001591 IsUTF16 = true;
Daniel Dunbar91ade142009-07-23 23:41:22 +00001592 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
Daniel Dunbar64509b22009-07-23 22:52:48 +00001593}
1594
1595llvm::Constant *
1596CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1597 unsigned StringLength = 0;
1598 bool isUTF16 = false;
1599 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump11289f42009-09-09 15:08:12 +00001600 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001601 getTargetData().isLittleEndian(),
1602 isUTF16, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00001603
Daniel Dunbar64509b22009-07-23 22:52:48 +00001604 if (llvm::Constant *C = Entry.getValue())
1605 return C;
Mike Stump11289f42009-09-09 15:08:12 +00001606
Owen Anderson41a75022009-08-13 21:57:51 +00001607 llvm::Constant *Zero =
1608 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
Daniel Dunbard644ad62008-08-23 18:37:06 +00001609 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump11289f42009-09-09 15:08:12 +00001610
Chris Lattneraa64ca22009-07-16 16:48:25 +00001611 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00001612 if (!CFConstantStringClassRef) {
1613 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001614 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001615 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattneraa64ca22009-07-16 16:48:25 +00001616 "__CFConstantStringClassReference");
Daniel Dunbard644ad62008-08-23 18:37:06 +00001617 // Decay array -> ptr
1618 CFConstantStringClassRef =
Owen Andersonade90fd2009-07-29 18:54:39 +00001619 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonb04ea612007-08-21 00:21:21 +00001620 }
Mike Stump11289f42009-09-09 15:08:12 +00001621
Anders Carlssonc2480a52008-11-15 18:54:24 +00001622 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00001623
Mike Stump11289f42009-09-09 15:08:12 +00001624 const llvm::StructType *STy =
Anders Carlssonc2480a52008-11-15 18:54:24 +00001625 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1626
Anders Carlsson157c3212009-08-16 05:55:31 +00001627 std::vector<llvm::Constant*> Fields(4);
Douglas Gregor91f84212008-12-11 16:49:14 +00001628
Anders Carlssonb04ea612007-08-21 00:21:21 +00001629 // Class pointer.
Anders Carlsson157c3212009-08-16 05:55:31 +00001630 Fields[0] = CFConstantStringClassRef;
Mike Stump11289f42009-09-09 15:08:12 +00001631
Anders Carlssonb04ea612007-08-21 00:21:21 +00001632 // Flags.
Daniel Dunbard644ad62008-08-23 18:37:06 +00001633 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump11289f42009-09-09 15:08:12 +00001634 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson157c3212009-08-16 05:55:31 +00001635 llvm::ConstantInt::get(Ty, 0x07C8);
1636
Anders Carlssonb04ea612007-08-21 00:21:21 +00001637 // String pointer.
Owen Anderson41a75022009-08-13 21:57:51 +00001638 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001639
Chris Lattner3afa3e12009-07-16 05:03:48 +00001640 llvm::GlobalValue::LinkageTypes Linkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001641 bool isConstant;
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001642 if (isUTF16) {
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001643 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner3afa3e12009-07-16 05:03:48 +00001644 Linkage = llvm::GlobalValue::InternalLinkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001645 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1646 // does make plain ascii ones writable.
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001647 isConstant = true;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001648 } else {
1649 Linkage = llvm::GlobalValue::PrivateLinkage;
1650 isConstant = !Features.WritableStrings;
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001651 }
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001652
Mike Stump11289f42009-09-09 15:08:12 +00001653 llvm::GlobalVariable *GV =
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001654 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1655 ".str");
Rafael Espindolae79d43da2011-01-17 16:31:00 +00001656 GV->setUnnamedAddr(true);
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001657 if (isUTF16) {
Ken Dycka0f99ff2010-01-26 18:46:23 +00001658 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1659 GV->setAlignment(Align.getQuantity());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001660 }
Anders Carlsson157c3212009-08-16 05:55:31 +00001661 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1662
Anders Carlssonb04ea612007-08-21 00:21:21 +00001663 // String length.
1664 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson157c3212009-08-16 05:55:31 +00001665 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00001666
Anders Carlssonb04ea612007-08-21 00:21:21 +00001667 // The struct.
Owen Anderson0e0189d2009-07-27 22:29:56 +00001668 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump11289f42009-09-09 15:08:12 +00001669 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1670 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner3afa3e12009-07-16 05:03:48 +00001671 "_unnamed_cfstring_");
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001672 if (const char *Sect = getContext().Target.getCFStringSection())
1673 GV->setSection(Sect);
Daniel Dunbar64509b22009-07-23 22:52:48 +00001674 Entry.setValue(GV);
Mike Stump11289f42009-09-09 15:08:12 +00001675
Anders Carlsson41b7c6b2007-11-01 00:41:52 +00001676 return GV;
Anders Carlssonb04ea612007-08-21 00:21:21 +00001677}
Chris Lattnerfb300092007-11-28 05:34:05 +00001678
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001679llvm::Constant *
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001680CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001681 unsigned StringLength = 0;
1682 bool isUTF16 = false;
1683 llvm::StringMapEntry<llvm::Constant*> &Entry =
1684 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1685 getTargetData().isLittleEndian(),
1686 isUTF16, StringLength);
1687
1688 if (llvm::Constant *C = Entry.getValue())
1689 return C;
1690
1691 llvm::Constant *Zero =
1692 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1693 llvm::Constant *Zeros[] = { Zero, Zero };
1694
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001695 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001696 if (!ConstantStringClassRef) {
1697 std::string StringClass(getLangOptions().ObjCConstantStringClass);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001698 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1699 Ty = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001700 llvm::Constant *GV;
1701 if (StringClass.empty())
1702 GV = CreateRuntimeVariable(Ty,
1703 Features.ObjCNonFragileABI ?
1704 "OBJC_CLASS_$_NSConstantString" :
1705 "_NSConstantStringClassReference");
1706 else {
1707 std::string str;
1708 if (Features.ObjCNonFragileABI)
1709 str = "OBJC_CLASS_$_" + StringClass;
1710 else
1711 str = "_" + StringClass + "ClassReference";
1712 GV = CreateRuntimeVariable(Ty, str);
1713 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001714 // Decay array -> ptr
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001715 ConstantStringClassRef =
1716 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001717 }
1718
1719 QualType NSTy = getContext().getNSConstantStringType();
1720
1721 const llvm::StructType *STy =
1722 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1723
1724 std::vector<llvm::Constant*> Fields(3);
1725
1726 // Class pointer.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001727 Fields[0] = ConstantStringClassRef;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001728
1729 // String pointer.
1730 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1731
1732 llvm::GlobalValue::LinkageTypes Linkage;
1733 bool isConstant;
1734 if (isUTF16) {
1735 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1736 Linkage = llvm::GlobalValue::InternalLinkage;
1737 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1738 // does make plain ascii ones writable.
1739 isConstant = true;
1740 } else {
1741 Linkage = llvm::GlobalValue::PrivateLinkage;
1742 isConstant = !Features.WritableStrings;
1743 }
1744
1745 llvm::GlobalVariable *GV =
1746 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1747 ".str");
Rafael Espindolade089d42011-01-17 22:11:21 +00001748 GV->setUnnamedAddr(true);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001749 if (isUTF16) {
1750 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1751 GV->setAlignment(Align.getQuantity());
1752 }
1753 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1754
1755 // String length.
1756 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1757 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1758
1759 // The struct.
1760 C = llvm::ConstantStruct::get(STy, Fields);
1761 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1762 llvm::GlobalVariable::PrivateLinkage, C,
1763 "_unnamed_nsstring_");
1764 // FIXME. Fix section.
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001765 if (const char *Sect =
1766 Features.ObjCNonFragileABI
1767 ? getContext().Target.getNSStringNonFragileABISection()
1768 : getContext().Target.getNSStringSection())
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001769 GV->setSection(Sect);
1770 Entry.setValue(GV);
1771
1772 return GV;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001773}
1774
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001775/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001776/// string literal, properly padded to match the literal type.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001777std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Ken Dycka45a70c2011-01-29 17:53:12 +00001778 const ASTContext &Context = getContext();
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001779 const ConstantArrayType *CAT =
Ken Dycka45a70c2011-01-29 17:53:12 +00001780 Context.getAsConstantArrayType(E->getType());
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001781 assert(CAT && "String isn't pointer or array!");
Mike Stump11289f42009-09-09 15:08:12 +00001782
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001783 // Resize the string to the right size.
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001784 uint64_t RealLen = CAT->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +00001785
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001786 if (E->isWide())
Ken Dycka45a70c2011-01-29 17:53:12 +00001787 RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00001788
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001789 std::string Str = E->getString().str();
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001790 Str.resize(RealLen, '\0');
Mike Stump11289f42009-09-09 15:08:12 +00001791
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001792 return Str;
1793}
1794
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001795/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1796/// constant array for the given string literal.
1797llvm::Constant *
1798CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1799 // FIXME: This can be more efficient.
Eli Friedman49ddc5f2009-11-16 05:55:46 +00001800 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1801 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1802 if (S->isWide()) {
1803 llvm::Type *DestTy =
1804 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1805 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1806 }
1807 return C;
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001808}
1809
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001810/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1811/// array for the given ObjCEncodeExpr node.
1812llvm::Constant *
1813CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1814 std::string Str;
1815 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00001816
1817 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001818}
1819
1820
Chris Lattner36fc8792008-02-11 00:02:17 +00001821/// GenerateWritableString -- Creates storage for a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001822static llvm::Constant *GenerateStringLiteral(const std::string &str,
Chris Lattnerfb300092007-11-28 05:34:05 +00001823 bool constant,
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001824 CodeGenModule &CGM,
1825 const char *GlobalName) {
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001826 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson41a75022009-08-13 21:57:51 +00001827 llvm::Constant *C =
1828 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
Mike Stump11289f42009-09-09 15:08:12 +00001829
Chris Lattnerfb300092007-11-28 05:34:05 +00001830 // Create a global variable for this string
Rafael Espindolab7f60e32011-01-10 22:34:03 +00001831 llvm::GlobalVariable *GV =
1832 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1833 llvm::GlobalValue::PrivateLinkage,
1834 C, GlobalName);
1835 GV->setUnnamedAddr(true);
1836 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00001837}
1838
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001839/// GetAddrOfConstantString - Returns a pointer to a character array
1840/// containing the literal. This contents are exactly that of the
1841/// given string, i.e. it will not be null terminated automatically;
1842/// see GetAddrOfConstantCString. Note that whether the result is
1843/// actually a pointer to an LLVM constant depends on
1844/// Feature.WriteableStrings.
1845///
1846/// The result has pointer to array type.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001847llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1848 const char *GlobalName) {
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001849 bool IsConstant = !Features.WritableStrings;
1850
1851 // Get the default prefix if a name wasn't specified.
1852 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00001853 GlobalName = ".str";
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001854
1855 // Don't share any string literals if strings aren't constant.
1856 if (!IsConstant)
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001857 return GenerateStringLiteral(str, false, *this, GlobalName);
Mike Stump11289f42009-09-09 15:08:12 +00001858
1859 llvm::StringMapEntry<llvm::Constant *> &Entry =
Chris Lattner3afa3e12009-07-16 05:03:48 +00001860 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
Chris Lattnerfb300092007-11-28 05:34:05 +00001861
1862 if (Entry.getValue())
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001863 return Entry.getValue();
Chris Lattnerfb300092007-11-28 05:34:05 +00001864
1865 // Create a global variable for this.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001866 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerfb300092007-11-28 05:34:05 +00001867 Entry.setValue(C);
1868 return C;
1869}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001870
1871/// GetAddrOfConstantCString - Returns a pointer to a character
1872/// array containing the literal and a terminating '\-'
1873/// character. The result has pointer to array type.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001874llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1875 const char *GlobalName){
Chris Lattner2e41b0e2008-12-09 19:10:54 +00001876 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001877}
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001878
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001879/// EmitObjCPropertyImplementations - Emit information for synthesized
1880/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00001881void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001882 ObjCImplementationDecl *D) {
Mike Stump11289f42009-09-09 15:08:12 +00001883 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001884 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001885 ObjCPropertyImplDecl *PID = *i;
Mike Stump11289f42009-09-09 15:08:12 +00001886
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001887 // Dynamic is just for type-checking.
1888 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1889 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1890
1891 // Determine which methods need to be implemented, some may have
1892 // been overridden. Note that ::isSynthesized is not the method
1893 // we want, that just indicates if the decl came from a
1894 // property. What we want to know is if the method is defined in
1895 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001896 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001897 CodeGenFunction(*this).GenerateObjCGetter(
1898 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001899 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001900 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001901 CodeGenFunction(*this).GenerateObjCSetter(
1902 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001903 }
1904 }
1905}
1906
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001907/// EmitObjCIvarInitializations - Emit information for ivar initialization
1908/// for an implementation.
1909void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1910 if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1911 return;
1912 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1913 assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1914 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1915 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1916 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1917 D->getLocation(),
1918 D->getLocation(), cxxSelector,
1919 getContext().VoidTy, 0,
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001920 DC, true, false, true, false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001921 ObjCMethodDecl::Required);
1922 D->addInstanceMethod(DTORMethod);
1923 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1924
1925 II = &getContext().Idents.get(".cxx_construct");
1926 cxxSelector = getContext().Selectors.getSelector(0, &II);
1927 // The constructor returns 'self'.
1928 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1929 D->getLocation(),
1930 D->getLocation(), cxxSelector,
1931 getContext().getObjCIdType(), 0,
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001932 DC, true, false, true, false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001933 ObjCMethodDecl::Required);
1934 D->addInstanceMethod(CTORMethod);
1935 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1936
1937
1938}
1939
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001940/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson237f3492009-04-01 00:58:25 +00001941void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001942 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson237f3492009-04-01 00:58:25 +00001943 I != E; ++I)
1944 EmitTopLevelDecl(*I);
1945}
1946
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001947// EmitLinkageSpec - Emit all declarations in a linkage spec.
1948void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00001949 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1950 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001951 ErrorUnsupported(LSD, "linkage spec");
1952 return;
1953 }
1954
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001955 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001956 I != E; ++I)
1957 EmitTopLevelDecl(*I);
1958}
1959
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001960/// EmitTopLevelDecl - Emit code for a single top level declaration.
1961void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1962 // If an error has occurred, stop code generation, but continue
1963 // parsing and semantic analysis (to ensure all warnings and errors
1964 // are emitted).
1965 if (Diags.hasErrorOccurred())
1966 return;
1967
Douglas Gregor70d83e22009-06-29 17:30:29 +00001968 // Ignore dependent declarations.
1969 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1970 return;
Mike Stump11289f42009-09-09 15:08:12 +00001971
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001972 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00001973 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00001974 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001975 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00001976 // Skip function templates
1977 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1978 return;
Mike Stump11289f42009-09-09 15:08:12 +00001979
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001980 EmitGlobal(cast<FunctionDecl>(D));
1981 break;
1982
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001983 case Decl::Var:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001984 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001985 break;
1986
Anders Carlssonf7475242009-04-15 15:55:24 +00001987 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001988 case Decl::Namespace:
Anders Carlsson237f3492009-04-01 00:58:25 +00001989 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001990 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00001991 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00001992 case Decl::UsingShadow:
Douglas Gregorfec52632009-06-20 00:51:54 +00001993 case Decl::Using:
Douglas Gregore5feb512009-09-02 23:49:23 +00001994 case Decl::UsingDirective:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001995 case Decl::ClassTemplate:
1996 case Decl::FunctionTemplate:
Anders Carlsson649a17e2009-09-23 19:19:16 +00001997 case Decl::NamespaceAlias:
Douglas Gregorfec52632009-06-20 00:51:54 +00001998 break;
Anders Carlssonf7475242009-04-15 15:55:24 +00001999 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00002000 // Skip function templates
2001 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
2002 return;
2003
Anders Carlssonf7475242009-04-15 15:55:24 +00002004 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2005 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00002006 case Decl::CXXDestructor:
2007 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2008 break;
Anders Carlsson87835432009-06-11 21:22:55 +00002009
2010 case Decl::StaticAssert:
2011 // Nothing to do.
2012 break;
2013
Anders Carlssonf7475242009-04-15 15:55:24 +00002014 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00002015
Fariborz Jahanian3654e652009-03-18 22:33:24 +00002016 // Forward declarations, no (immediate) code generation.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002017 case Decl::ObjCClass:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002018 case Decl::ObjCForwardProtocol:
Chris Lattnerd18136a2009-04-01 02:36:43 +00002019 case Decl::ObjCInterface:
Chris Lattnerd18136a2009-04-01 02:36:43 +00002020 break;
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00002021
2022 case Decl::ObjCCategory: {
2023 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2024 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2025 Context.ResetObjCLayout(CD->getClassInterface());
2026 break;
2027 }
2028
Chris Lattnerd18136a2009-04-01 02:36:43 +00002029
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002030 case Decl::ObjCProtocol:
Fariborz Jahanian629aed92009-03-21 18:06:45 +00002031 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002032 break;
2033
2034 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002035 // Categories have properties but don't support synthesize so we
2036 // can ignore them here.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002037 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2038 break;
2039
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002040 case Decl::ObjCImplementation: {
2041 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00002042 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2043 Context.ResetObjCLayout(OMD->getClassInterface());
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002044 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002045 EmitObjCIvarInitializations(OMD);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002046 Runtime->GenerateClass(OMD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002047 break;
Mike Stump11289f42009-09-09 15:08:12 +00002048 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002049 case Decl::ObjCMethod: {
2050 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2051 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002052 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002053 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2054 break;
2055 }
Mike Stump11289f42009-09-09 15:08:12 +00002056 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian17290c32009-01-08 01:10:55 +00002057 // compatibility-alias is a directive and has no code gen.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002058 break;
2059
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002060 case Decl::LinkageSpec:
2061 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002062 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002063
2064 case Decl::FileScopeAsm: {
2065 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Benjamin Kramerb11118b2009-12-11 13:33:18 +00002066 llvm::StringRef AsmString = AD->getAsmString()->getString();
Mike Stump11289f42009-09-09 15:08:12 +00002067
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002068 const std::string &S = getModule().getModuleInlineAsm();
2069 if (S.empty())
2070 getModule().setModuleInlineAsm(AsmString);
2071 else
Benjamin Kramerb11118b2009-12-11 13:33:18 +00002072 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002073 break;
2074 }
Mike Stump11289f42009-09-09 15:08:12 +00002075
2076 default:
Mike Stump18bb9282009-05-16 07:57:57 +00002077 // Make sure we handled everything we should, every other kind is a
2078 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2079 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002080 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2081 }
2082}
John McCall09ae0322010-07-06 23:57:41 +00002083
2084/// Turns the given pointer into a constant.
2085static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2086 const void *Ptr) {
2087 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2088 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2089 return llvm::ConstantInt::get(i64, PtrInt);
2090}
2091
2092static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2093 llvm::NamedMDNode *&GlobalMetadata,
2094 GlobalDecl D,
2095 llvm::GlobalValue *Addr) {
2096 if (!GlobalMetadata)
2097 GlobalMetadata =
2098 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2099
2100 // TODO: should we report variant information for ctors/dtors?
2101 llvm::Value *Ops[] = {
2102 Addr,
2103 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2104 };
2105 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2106}
2107
2108/// Emits metadata nodes associating all the global values in the
2109/// current module with the Decls they came from. This is useful for
2110/// projects using IR gen as a subroutine.
2111///
2112/// Since there's currently no way to associate an MDNode directly
2113/// with an llvm::GlobalValue, we create a global named metadata
2114/// with the name 'clang.global.decl.ptrs'.
2115void CodeGenModule::EmitDeclMetadata() {
2116 llvm::NamedMDNode *GlobalMetadata = 0;
2117
2118 // StaticLocalDeclMap
2119 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2120 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2121 I != E; ++I) {
2122 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2123 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2124 }
2125}
2126
2127/// Emits metadata nodes for all the local variables in the current
2128/// function.
2129void CodeGenFunction::EmitDeclMetadata() {
2130 if (LocalDeclMap.empty()) return;
2131
2132 llvm::LLVMContext &Context = getLLVMContext();
2133
2134 // Find the unique metadata ID for this name.
2135 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2136
2137 llvm::NamedMDNode *GlobalMetadata = 0;
2138
2139 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2140 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2141 const Decl *D = I->first;
2142 llvm::Value *Addr = I->second;
2143
2144 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2145 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2146 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2147 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2148 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2149 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2150 }
2151 }
2152}
Daniel Dunbar900546d2010-07-16 00:00:15 +00002153
2154///@name Custom Runtime Function Interfaces
2155///@{
2156//
2157// FIXME: These can be eliminated once we can have clients just get the required
2158// AST nodes from the builtin tables.
2159
2160llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2161 if (BlockObjectDispose)
2162 return BlockObjectDispose;
2163
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002164 // If we saw an explicit decl, use that.
2165 if (BlockObjectDisposeDecl) {
2166 return BlockObjectDispose = GetAddrOfFunction(
2167 BlockObjectDisposeDecl,
2168 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2169 }
2170
2171 // Otherwise construct the function by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002172 const llvm::FunctionType *FTy;
2173 std::vector<const llvm::Type*> ArgTys;
2174 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
John McCallad7c5c12011-02-08 08:22:06 +00002175 ArgTys.push_back(Int8PtrTy);
Daniel Dunbar900546d2010-07-16 00:00:15 +00002176 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2177 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2178 return BlockObjectDispose =
2179 CreateRuntimeFunction(FTy, "_Block_object_dispose");
2180}
2181
2182llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2183 if (BlockObjectAssign)
2184 return BlockObjectAssign;
2185
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002186 // If we saw an explicit decl, use that.
2187 if (BlockObjectAssignDecl) {
2188 return BlockObjectAssign = GetAddrOfFunction(
2189 BlockObjectAssignDecl,
2190 getTypes().GetFunctionType(BlockObjectAssignDecl));
2191 }
2192
2193 // Otherwise construct the function by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002194 const llvm::FunctionType *FTy;
2195 std::vector<const llvm::Type*> ArgTys;
2196 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
John McCallad7c5c12011-02-08 08:22:06 +00002197 ArgTys.push_back(Int8PtrTy);
2198 ArgTys.push_back(Int8PtrTy);
Daniel Dunbar900546d2010-07-16 00:00:15 +00002199 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2200 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2201 return BlockObjectAssign =
2202 CreateRuntimeFunction(FTy, "_Block_object_assign");
2203}
2204
2205llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2206 if (NSConcreteGlobalBlock)
2207 return NSConcreteGlobalBlock;
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002208
2209 // If we saw an explicit decl, use that.
2210 if (NSConcreteGlobalBlockDecl) {
2211 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2212 NSConcreteGlobalBlockDecl,
2213 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2214 }
2215
2216 // Otherwise construct the variable by hand.
John McCallad7c5c12011-02-08 08:22:06 +00002217 return NSConcreteGlobalBlock =
2218 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteGlobalBlock");
Daniel Dunbar900546d2010-07-16 00:00:15 +00002219}
2220
2221llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2222 if (NSConcreteStackBlock)
2223 return NSConcreteStackBlock;
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002224
2225 // If we saw an explicit decl, use that.
2226 if (NSConcreteStackBlockDecl) {
2227 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2228 NSConcreteStackBlockDecl,
2229 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2230 }
2231
2232 // Otherwise construct the variable by hand.
John McCallad7c5c12011-02-08 08:22:06 +00002233 return NSConcreteStackBlock =
2234 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteStackBlock");
Daniel Dunbar900546d2010-07-16 00:00:15 +00002235}
2236
2237///@}