blob: 7432b01e255cca67d2565ab809b441b4ec34805b [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
Daniel Dunbara8f02052008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor3556bc72009-02-13 00:10:09 +000019#include "Mangle.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Chris Lattner825f6ea2008-11-04 16:51:42 +000022#include "clang/AST/DeclCXX.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000023#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000026#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000027#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000029#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattnerdb6be562007-11-28 05:34:05 +000034CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000035 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar1be1df32008-08-11 21:35:06 +000036 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000037 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000038 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Mike Stump95e54802009-02-13 15:16:56 +000039 CFConstantStringClassRef(0), NSConcreteGlobalBlock(0),
Mike Stump0dffa462009-02-13 15:25:34 +000040 BlockDescriptorType(0), GenericBlockLiteralType(0) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000041
42 if (Features.ObjC1) {
Daniel Dunbar1be1df32008-08-11 21:35:06 +000043 if (Features.NeXTRuntime) {
Fariborz Jahaniand0374812009-01-22 23:02:58 +000044 Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this)
Fariborz Jahanian48543f52009-01-21 22:04:16 +000045 : CreateMacObjCRuntime(*this);
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000046 } else {
47 Runtime = CreateGNUObjCRuntime(*this);
48 }
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000049 }
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000050
51 // If debug info generation is enabled, create the CGDebugInfo object.
Mike Stumpef2c82f2009-02-13 18:36:05 +000052 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
53
54 Block.GlobalUniqueCount = 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000055}
56
57CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000058 delete Runtime;
59 delete DebugInfo;
60}
61
62void CodeGenModule::Release() {
Daniel Dunbar21f3cf72009-02-13 20:29:50 +000063 EmitDeferred();
Daniel Dunbar566a6502008-09-08 23:44:31 +000064 EmitAliases();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000065 if (Runtime)
66 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
67 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000068 EmitCtorList(GlobalCtors, "llvm.global_ctors");
69 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000070 EmitAnnotations();
Daniel Dunbar21f3cf72009-02-13 20:29:50 +000071 EmitLLVMUsed();
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000072 BindRuntimeFunctions();
Chris Lattnercbfb5512008-03-01 08:45:05 +000073}
Chris Lattner4b009652007-07-25 00:24:17 +000074
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000075void CodeGenModule::BindRuntimeFunctions() {
76 // Deal with protecting runtime function names.
77 for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
78 llvm::Function *Fn = RuntimeFunctions[i].first;
79 const std::string &Name = RuntimeFunctions[i].second;
80
Daniel Dunbarfc1543e2008-11-19 06:15:35 +000081 // Discard unused runtime functions.
82 if (Fn->use_empty()) {
83 Fn->eraseFromParent();
84 continue;
85 }
86
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000087 // See if there is a conflict against a function.
88 llvm::Function *Conflict = TheModule.getFunction(Name);
89 if (Conflict) {
90 // Decide which version to take. If the conflict is a definition
91 // we are forced to take that, otherwise assume the runtime
92 // knows best.
93 if (!Conflict->isDeclaration()) {
94 llvm::Value *Casted =
95 llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
96 Fn->replaceAllUsesWith(Casted);
97 Fn->eraseFromParent();
98 } else {
99 Fn->takeName(Conflict);
100 llvm::Value *Casted =
101 llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
102 Conflict->replaceAllUsesWith(Casted);
103 Conflict->eraseFromParent();
104 }
105 } else {
106 // FIXME: There still may be conflicts with aliases and
107 // variables.
108 Fn->setName(Name);
109 }
110 }
111}
112
Daniel Dunbar9503b782008-08-16 00:56:44 +0000113/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000114/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000115void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
116 bool OmitOnError) {
117 if (OmitOnError && getDiags().hasErrorOccurred())
118 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000119 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +0000120 "cannot compile this %0 yet");
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000121 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +0000122 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
123 << Msg << S->getSourceRange();
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000124}
Chris Lattner0e4755d2007-12-02 06:27:33 +0000125
Daniel Dunbar9503b782008-08-16 00:56:44 +0000126/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +0000127/// specified decl yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000128void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
129 bool OmitOnError) {
130 if (OmitOnError && getDiags().hasErrorOccurred())
131 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000132 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +0000133 "cannot compile this %0 yet");
Chris Lattner806a5f52008-01-12 07:05:38 +0000134 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +0000135 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner806a5f52008-01-12 07:05:38 +0000136}
137
Daniel Dunbar27250d32008-08-15 23:26:23 +0000138/// setGlobalVisibility - Set the visibility for the given LLVM
139/// GlobalValue according to the given clang AST visibility value.
140static void setGlobalVisibility(llvm::GlobalValue *GV,
141 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4751a3a2008-05-22 00:50:06 +0000142 switch (Vis) {
143 default: assert(0 && "Unknown visibility!");
144 case VisibilityAttr::DefaultVisibility:
145 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
146 break;
147 case VisibilityAttr::HiddenVisibility:
148 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
149 break;
150 case VisibilityAttr::ProtectedVisibility:
151 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
152 break;
153 }
154}
155
Douglas Gregor3556bc72009-02-13 00:10:09 +0000156/// \brief Retrieves the mangled name for the given declaration.
157///
158/// If the given declaration requires a mangled name, returns an
159/// IdentifierInfo* containing the mangled name. Otherwise, returns
160/// the name of the declaration as an identifier.
161///
162/// FIXME: Returning an IdentifierInfo* here is a total hack. We
163/// really need some kind of string abstraction that either stores a
164/// mangled name or stores an IdentifierInfo*. This will require
Daniel Dunbar7b7f4f42009-02-18 22:52:09 +0000165/// changes to the GlobalDeclMap, too. (I disagree, I think what we
166/// actually need is for Sema to provide some notion of which Decls
167/// refer to the same semantic decl. We shouldn't need to mangle the
168/// names and see what comes out the same to figure this out. - DWD)
Douglas Gregor3556bc72009-02-13 00:10:09 +0000169///
170/// FIXME: Performance here is going to be terribly until we start
171/// caching mangled names. However, we should fix the problem above
172/// first.
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000173const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
174 llvm::SmallString<256> Name;
175 llvm::raw_svector_ostream Out(Name);
Douglas Gregor3556bc72009-02-13 00:10:09 +0000176 if (!mangleName(ND, Context, Out))
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000177 return ND->getIdentifier()->getName();
Douglas Gregor3556bc72009-02-13 00:10:09 +0000178
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000179 Name += '\0';
180 return MangledNames.GetOrCreateValue(Name.begin(), Name.end())
181 .getKeyData();
Douglas Gregor3556bc72009-02-13 00:10:09 +0000182}
183
Chris Lattner753d2592008-03-14 17:18:18 +0000184/// AddGlobalCtor - Add a function to the list that will be called before
185/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000186void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000187 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000188 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000189}
190
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000191/// AddGlobalDtor - Add a function to the list that will be called
192/// when the module is unloaded.
193void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000194 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000195 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
196}
197
198void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
199 // Ctor function type is void()*.
200 llvm::FunctionType* CtorFTy =
201 llvm::FunctionType::get(llvm::Type::VoidTy,
202 std::vector<const llvm::Type*>(),
203 false);
204 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
205
206 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000207 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000208 llvm::StructType::get(llvm::Type::Int32Ty,
209 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000210
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000211 // Construct the constructor and destructor arrays.
212 std::vector<llvm::Constant*> Ctors;
213 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
214 std::vector<llvm::Constant*> S;
215 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
216 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
217 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000218 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000219
220 if (!Ctors.empty()) {
221 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
222 new llvm::GlobalVariable(AT, false,
223 llvm::GlobalValue::AppendingLinkage,
224 llvm::ConstantArray::get(AT, Ctors),
225 GlobalName,
226 &TheModule);
227 }
Chris Lattner753d2592008-03-14 17:18:18 +0000228}
229
Nate Begeman52da5c72008-04-18 23:43:57 +0000230void CodeGenModule::EmitAnnotations() {
231 if (Annotations.empty())
232 return;
233
234 // Create a new global variable for the ConstantStruct in the Module.
235 llvm::Constant *Array =
236 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
237 Annotations.size()),
238 Annotations);
239 llvm::GlobalValue *gv =
240 new llvm::GlobalVariable(Array->getType(), false,
241 llvm::GlobalValue::AppendingLinkage, Array,
242 "llvm.global.annotations", &TheModule);
243 gv->setSection("llvm.metadata");
244}
245
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000246void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
247 bool IsInternal,
248 bool IsInline,
249 llvm::GlobalValue *GV,
250 bool ForDefinition) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000251 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopes78534382008-06-08 15:45:52 +0000252 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000253 if (!ForDefinition) {
254 // Only a few attributes are set on declarations.
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000255 if (D->getAttr<DLLImportAttr>()) {
256 // The dllimport attribute is overridden by a subsequent declaration as
257 // dllexport.
Sebastian Redle299eb42009-01-05 20:53:53 +0000258 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000259 // dllimport attribute can be applied only to function decls, not to
260 // definitions.
261 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
262 if (!FD->getBody())
263 GV->setLinkage(llvm::Function::DLLImportLinkage);
264 } else
265 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redle299eb42009-01-05 20:53:53 +0000266 }
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000267 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000268 } else {
269 if (IsInternal) {
270 GV->setLinkage(llvm::Function::InternalLinkage);
271 } else {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000272 if (D->getAttr<DLLExportAttr>()) {
273 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
274 // The dllexport attribute is ignored for undefined symbols.
275 if (FD->getBody())
276 GV->setLinkage(llvm::Function::DLLExportLinkage);
277 } else
278 GV->setLinkage(llvm::Function::DLLExportLinkage);
279 } else if (D->getAttr<WeakAttr>() || IsInline)
Daniel Dunbar566a6502008-09-08 23:44:31 +0000280 GV->setLinkage(llvm::Function::WeakLinkage);
281 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000282 }
Nuno Lopes78534382008-06-08 15:45:52 +0000283
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000284 // FIXME: Figure out the relative priority of the attribute,
285 // -fvisibility, and private_extern.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000286 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000287 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000288 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000289
Daniel Dunbara8f02052008-09-08 21:33:45 +0000290 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbarced89142008-08-06 00:03:29 +0000291 // Prefaced with special LLVM marker to indicate that the name
292 // should not be munged.
293 GV->setName("\01" + ALA->getLabel());
294 }
Daniel Dunbar97509722009-02-12 17:28:23 +0000295
296 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
297 GV->setSection(SA->getName());
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000298
299 // Only add to llvm.used when we see a definition, otherwise we
300 // might add multiple times or risk the value being replaced by a
301 // subsequent RAUW.
302 if (ForDefinition) {
303 if (D->getAttr<UsedAttr>())
304 AddUsedGlobal(GV);
305 }
Nuno Lopes78534382008-06-08 15:45:52 +0000306}
307
Devang Patela85a9ef2008-09-25 21:02:23 +0000308void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000309 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000310 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000311 AttributeListType AttributeList;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000312 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000313
Devang Patela85a9ef2008-09-25 21:02:23 +0000314 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
315 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000316
317 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000318 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000319 F->setCallingConv(llvm::CallingConv::X86_FastCall);
320
321 if (D->getAttr<StdCallAttr>())
322 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000323}
324
325/// SetFunctionAttributesForDefinition - Set function attributes
326/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000327void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
328 llvm::Function *F) {
329 if (isa<ObjCMethodDecl>(D)) {
330 SetGlobalValueAttributes(D, true, false, F, true);
331 } else {
332 const FunctionDecl *FD = cast<FunctionDecl>(D);
333 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
334 FD->isInline(), F, true);
335 }
336
Daniel Dunbarf2787002008-09-04 23:41:35 +0000337 if (!Features.Exceptions)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000338 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000339
340 if (D->getAttr<AlwaysInlineAttr>())
341 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson2157eec2009-02-19 19:22:11 +0000342
343 if (D->getAttr<NoinlineAttr>())
344 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000345}
346
347void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
348 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000349 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000350
Daniel Dunbar566a6502008-09-08 23:44:31 +0000351 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000352}
353
354void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
355 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000356 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000357
Daniel Dunbar566a6502008-09-08 23:44:31 +0000358 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
359 FD->isInline(), F, false);
360}
361
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000362
Daniel Dunbar566a6502008-09-08 23:44:31 +0000363void CodeGenModule::EmitAliases() {
364 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
365 const FunctionDecl *D = Aliases[i];
366 const AliasAttr *AA = D->getAttr<AliasAttr>();
367
368 // This is something of a hack, if the FunctionDecl got overridden
369 // then its attributes will be moved to the new declaration. In
370 // this case the current decl has no alias attribute, but we will
371 // eventually see it.
372 if (!AA)
373 continue;
374
375 const std::string& aliaseeName = AA->getAliasee();
376 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
377 if (!aliasee) {
378 // FIXME: This isn't unsupported, this is just an error, which
379 // sema should catch, but...
380 ErrorUnsupported(D, "alias referencing a missing function");
381 continue;
382 }
383
384 llvm::GlobalValue *GA =
385 new llvm::GlobalAlias(aliasee->getType(),
386 llvm::Function::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000387 getMangledName(D), aliasee,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000388 &getModule());
Daniel Dunbar566a6502008-09-08 23:44:31 +0000389
Douglas Gregor3556bc72009-02-13 00:10:09 +0000390 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar566a6502008-09-08 23:44:31 +0000391 if (Entry) {
392 // If we created a dummy function for this then replace it.
393 GA->takeName(Entry);
394
395 llvm::Value *Casted =
396 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
397 Entry->replaceAllUsesWith(Casted);
398 Entry->eraseFromParent();
399
400 Entry = GA;
401 }
402
403 // Alias should never be internal or inline.
404 SetGlobalValueAttributes(D, false, false, GA, true);
405 }
Eli Friedman9be42212008-06-01 15:54:49 +0000406}
407
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000408void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
409 assert(!GV->isDeclaration() &&
410 "Only globals with definition can force usage.");
411 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
412 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
413}
414
415void CodeGenModule::EmitLLVMUsed() {
416 // Don't create llvm.used if there is no need.
417 if (LLVMUsed.empty())
418 return;
419
420 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
421 LLVMUsed.size());
422 llvm::GlobalVariable *GV =
423 new llvm::GlobalVariable(ATy, false,
424 llvm::GlobalValue::AppendingLinkage,
425 llvm::ConstantArray::get(ATy, LLVMUsed),
426 "llvm.used", &getModule());
427
428 GV->setSection("llvm.metadata");
429}
430
431void CodeGenModule::EmitDeferred() {
432 // Emit code for any deferred decl which was used. Since a
433 // previously unused static decl may become used during the
434 // generation of code for a static function, iterate until no
435 // changes are made.
Nate Begemanad320b62008-04-20 06:29:50 +0000436 bool Changed;
437 do {
438 Changed = false;
Anders Carlsson2e427d52009-01-04 02:08:04 +0000439
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000440 for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(),
441 e = DeferredDecls.end(); i != e; ) {
Anders Carlsson2e427d52009-01-04 02:08:04 +0000442 const ValueDecl *D = *i;
443
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000444 // Check if we have used a decl with the same name
445 // FIXME: The AST should have some sort of aggregate decls or
446 // global symbol map.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000447 // FIXME: This is missing some important cases. For example, we
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000448 // need to check for uses in an alias.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000449 if (!GlobalDeclMap.count(getMangledName(D))) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000450 ++i;
Daniel Dunbarced89142008-08-06 00:03:29 +0000451 continue;
Anders Carlsson2e427d52009-01-04 02:08:04 +0000452 }
453
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000454 // Emit the definition.
455 EmitGlobalDefinition(D);
456
Nate Begemanad320b62008-04-20 06:29:50 +0000457 // Erase the used decl from the list.
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000458 i = DeferredDecls.erase(i);
Anders Carlsson2e427d52009-01-04 02:08:04 +0000459
Nate Begemanad320b62008-04-20 06:29:50 +0000460 // Remember that we made a change.
461 Changed = true;
462 }
463 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000464}
465
Nate Begeman8a704172008-04-19 04:17:09 +0000466/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
467/// annotation information for a given GlobalValue. The annotation struct is
468/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000469/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000470/// created from the AnnotateAttr's annotation. The third field is a constant
471/// string containing the name of the translation unit. The fourth field is
472/// the line number in the file of the annotated value declaration.
473///
474/// FIXME: this does not unique the annotation string constants, as llvm-gcc
475/// appears to.
476///
477llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
478 const AnnotateAttr *AA,
479 unsigned LineNo) {
480 llvm::Module *M = &getModule();
481
482 // get [N x i8] constants for the annotation string, and the filename string
483 // which are the 2nd and 3rd elements of the global annotation structure.
484 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
485 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
486 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
487 true);
488
489 // Get the two global values corresponding to the ConstantArrays we just
490 // created to hold the bytes of the strings.
491 llvm::GlobalValue *annoGV =
492 new llvm::GlobalVariable(anno->getType(), false,
493 llvm::GlobalValue::InternalLinkage, anno,
494 GV->getName() + ".str", M);
495 // translation unit name string, emitted into the llvm.metadata section.
496 llvm::GlobalValue *unitGV =
497 new llvm::GlobalVariable(unit->getType(), false,
498 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
499
500 // Create the ConstantStruct that is the global annotion.
501 llvm::Constant *Fields[4] = {
502 llvm::ConstantExpr::getBitCast(GV, SBP),
503 llvm::ConstantExpr::getBitCast(annoGV, SBP),
504 llvm::ConstantExpr::getBitCast(unitGV, SBP),
505 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
506 };
507 return llvm::ConstantStruct::get(Fields, 4, false);
508}
509
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000510bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000511 // Never defer when EmitAllDecls is specified or the decl has
512 // attribute used.
513 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000514 return false;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000515
516 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000517 // Constructors and destructors should never be deferred.
518 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
519 return false;
520
521 if (FD->getStorageClass() != FunctionDecl::Static)
522 return false;
523 } else {
524 const VarDecl *VD = cast<VarDecl>(Global);
525 assert(VD->isFileVarDecl() && "Invalid decl.");
526
527 if (VD->getStorageClass() != VarDecl::Static)
528 return false;
529 }
530
531 return true;
532}
533
534void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
535 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000536 // Aliases are deferred until code for everything else has been
537 // emitted.
538 if (FD->getAttr<AliasAttr>()) {
539 assert(!FD->isThisDeclarationADefinition() &&
540 "Function alias cannot have a definition!");
541 Aliases.push_back(FD);
542 return;
543 }
544
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000545 // Forward declarations are emitted lazily on first use.
546 if (!FD->isThisDeclarationADefinition())
547 return;
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000548 } else {
549 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000550 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
551
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000552 // Forward declarations are emitted lazily on first use.
Daniel Dunbar0c79d782009-02-13 22:49:13 +0000553 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000554 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000555 }
556
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000557 // Defer code generation when possible.
558 if (MayDeferGeneration(Global)) {
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000559 DeferredDecls.push_back(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000560 return;
561 }
562
563 // Otherwise emit the definition.
564 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000565}
566
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000567void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
568 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
569 EmitGlobalFunctionDefinition(FD);
570 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
571 EmitGlobalVarDefinition(VD);
572 } else {
573 assert(0 && "Invalid argument to EmitGlobalDefinition()");
574 }
575}
576
Daniel Dunbar2188c532008-07-30 16:32:24 +0000577 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000578 assert(D->hasGlobalStorage() && "Not a global variable");
579
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000580 QualType ASTTy = D->getType();
581 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000582 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000583
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000584 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000585 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000586 if (!Entry) {
587 llvm::GlobalVariable *GV =
588 new llvm::GlobalVariable(Ty, false,
589 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000590 0, getMangledName(D), &getModule(),
Douglas Gregor3556bc72009-02-13 00:10:09 +0000591 0, ASTTy.getAddressSpace());
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000592 Entry = GV;
593
594 // Handle things which are present even on external declarations.
595
596 // FIXME: This code is overly simple and should be merged with
597 // other global handling.
598
599 GV->setConstant(D->getType().isConstant(Context));
600
601 if (D->getStorageClass() == VarDecl::PrivateExtern)
602 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
603 }
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000604
Daniel Dunbar2188c532008-07-30 16:32:24 +0000605 // Make sure the result is of the correct type.
606 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000607}
608
609void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000610 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000611 QualType ASTTy = D->getType();
612 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000613
Chris Lattner4b009652007-07-25 00:24:17 +0000614 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000615 // This is a tentative definition; tentative definitions are
616 // implicitly initialized with { 0 }
617 const llvm::Type* InitTy;
618 if (ASTTy->isIncompleteArrayType()) {
619 // An incomplete array is normally [ TYPE x 0 ], but we need
620 // to fix it to [ TYPE x 1 ].
621 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
622 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
623 } else {
624 InitTy = VarTy;
625 }
626 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000627 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000628 Init = EmitConstantExpr(D->getInit());
Eli Friedman442959a2009-02-20 01:18:21 +0000629 if (!Init) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000630 ErrorUnsupported(D, "static initializer");
Eli Friedman442959a2009-02-20 01:18:21 +0000631 QualType T = D->getInit()->getType();
632 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
633 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000634 }
635 const llvm::Type* InitType = Init->getType();
636
Douglas Gregor3556bc72009-02-13 00:10:09 +0000637 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000638 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
639
Eli Friedman43a0ce82008-05-30 19:50:47 +0000640 if (!GV) {
641 GV = new llvm::GlobalVariable(InitType, false,
642 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000643 0, getMangledName(D),
Douglas Gregor3556bc72009-02-13 00:10:09 +0000644 &getModule(), 0, ASTTy.getAddressSpace());
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000645
646 } else if (GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
647 // If we already have this global and it has an initializer, then
648 // we are in the rare situation where we emitted the defining
649 // declaration of the global and are now being asked to emit a
650 // definition which would be common. This occurs, for example, in
651 // the following situation because statics can be emitted out of
652 // order:
653 //
654 // static int x;
655 // static int *y = &x;
656 // static int x = 10;
657 // int **z = &y;
658 //
659 // Bail here so we don't blow away the definition. Note that if we
660 // can't distinguish here if we emitted a definition with a null
661 // initializer, but this case is safe.
662 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
663 return;
664
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000665 } else if (GV->getType() !=
666 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000667 // We have a definition after a prototype with the wrong type.
668 // We must make a new GlobalVariable* and update everything that used OldGV
669 // (a declaration or tentative definition) with the new GlobalVariable*
670 // (which will be a definition).
671 //
672 // This happens if there is a prototype for a global (e.g. "extern int x[];")
673 // and then a definition of a different type (e.g. "int x[10];"). This also
674 // happens when an initializer has a different type from the type of the
675 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000676 //
677 // FIXME: This also ends up happening if there's a definition followed by
678 // a tentative definition! (Although Sema rejects that construct
679 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000680
681 // Save the old global
682 llvm::GlobalVariable *OldGV = GV;
683
684 // Make a new global with the correct type
685 GV = new llvm::GlobalVariable(InitType, false,
686 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000687 0, getMangledName(D),
Douglas Gregor3556bc72009-02-13 00:10:09 +0000688 &getModule(), 0, ASTTy.getAddressSpace());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000689 // Steal the name of the old global
690 GV->takeName(OldGV);
691
692 // Replace all uses of the old global with the new global
693 llvm::Constant *NewPtrForOldDecl =
694 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
695 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000696
697 // Erase the old global, since it is no longer used.
698 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000699 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000700
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000701 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000702
Nate Begeman8a704172008-04-19 04:17:09 +0000703 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
704 SourceManager &SM = Context.getSourceManager();
705 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner18c8dc02009-01-16 07:36:28 +0000706 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8a704172008-04-19 04:17:09 +0000707 }
708
Chris Lattner4b009652007-07-25 00:24:17 +0000709 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000710 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner402b3372008-03-03 03:28:21 +0000711
Eli Friedman7008e9a2008-05-30 20:39:54 +0000712 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
713 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000714 if (const IncompleteArrayType* IAT =
715 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000716 Align = Context.getTypeAlign(IAT->getElementType());
717 else
718 Align = Context.getTypeAlign(D->getType());
Daniel Dunbarf8eb23b2009-02-18 19:45:21 +0000719 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmanb232e992008-05-29 11:10:27 +0000720 Align = std::max(Align, AA->getAlignment());
Eli Friedmanb232e992008-05-29 11:10:27 +0000721 GV->setAlignment(Align / 8);
722
Chris Lattner402b3372008-03-03 03:28:21 +0000723 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000724 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000725 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000726
727 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
728 // Prefaced with special LLVM marker to indicate that the name
729 // should not be munged.
730 GV->setName("\01" + ALA->getLabel());
731 }
Chris Lattner4b009652007-07-25 00:24:17 +0000732
733 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000734 if (D->getStorageClass() == VarDecl::Static)
735 GV->setLinkage(llvm::Function::InternalLinkage);
736 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000737 GV->setLinkage(llvm::Function::DLLImportLinkage);
738 else if (D->getAttr<DLLExportAttr>())
739 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000740 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000741 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000742 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000743 // FIXME: This isn't right. This should handle common linkage and other
744 // stuff.
745 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000746 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000747 case VarDecl::Auto:
748 case VarDecl::Register:
749 assert(0 && "Can't have auto or register globals");
750 case VarDecl::None:
751 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000752 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson689bba82008-12-03 05:51:23 +0000753 else
754 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000755 break;
756 case VarDecl::Extern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000757 // FIXME: common
758 break;
759
Chris Lattner402b3372008-03-03 03:28:21 +0000760 case VarDecl::PrivateExtern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000761 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
762 // FIXME: common
Chris Lattner402b3372008-03-03 03:28:21 +0000763 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000764 }
Chris Lattner4b009652007-07-25 00:24:17 +0000765 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000766
Daniel Dunbar97509722009-02-12 17:28:23 +0000767 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
768 GV->setSection(SA->getName());
769
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000770 if (D->getAttr<UsedAttr>())
771 AddUsedGlobal(GV);
772
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000773 // Emit global variable debug information.
774 CGDebugInfo *DI = getDebugInfo();
775 if(DI) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000776 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000777 DI->EmitGlobalVariable(GV, D);
778 }
Chris Lattner4b009652007-07-25 00:24:17 +0000779}
780
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000781llvm::GlobalValue *
Daniel Dunbar3f197842009-02-19 07:15:39 +0000782CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D,
783 const llvm::Type *Ty) {
784 if (!Ty)
785 Ty = getTypes().ConvertType(D->getType());
Daniel Dunbar566a6502008-09-08 23:44:31 +0000786 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
787 llvm::Function::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000788 getMangledName(D),
Douglas Gregor3556bc72009-02-13 00:10:09 +0000789 &getModule());
Daniel Dunbar566a6502008-09-08 23:44:31 +0000790 SetFunctionAttributes(D, F);
791 return F;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000792}
793
794llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000795 QualType ASTTy = D->getType();
796 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
797 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000798
799 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000800 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000801 if (!Entry)
Daniel Dunbar3f197842009-02-19 07:15:39 +0000802 Entry = EmitForwardFunctionDefinition(D, 0);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000803
Daniel Dunbar2188c532008-07-30 16:32:24 +0000804 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000805}
806
807void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000808 const llvm::FunctionType *Ty =
809 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
810
811 // As a special case, make sure that definitions of K&R function
812 // "type foo()" aren't declared as varargs (which forces the backend
813 // to do unnecessary work).
814 if (Ty->isVarArg() && Ty->getNumParams() == 0 && Ty->isVarArg())
815 Ty = llvm::FunctionType::get(Ty->getReturnType(),
816 std::vector<const llvm::Type*>(),
817 false);
818
Douglas Gregor3556bc72009-02-13 00:10:09 +0000819 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000820 if (!Entry) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000821 Entry = EmitForwardFunctionDefinition(D, Ty);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000822 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000823 // If the types mismatch then we have to rewrite the definition.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000824 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000825 // Otherwise, we have a definition after a prototype with the
826 // wrong type. F is the Function* for the one with the wrong
827 // type, we must make a new Function* and update everything that
828 // used F (a declaration) with the new Function* (which will be
829 // a definition).
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000830 //
Daniel Dunbar3f197842009-02-19 07:15:39 +0000831 // This happens if there is a prototype for a function
832 // (e.g. "int f()") and then a definition of a different type
833 // (e.g. "int f(int x)"). Start by making a new function of the
834 // correct type, RAUW, then steal the name.
835 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D, Ty);
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000836 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000837
838 // Replace uses of F with the Function we will endow with a body.
839 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000840 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
841 Entry->replaceAllUsesWith(NewPtrForOldDecl);
842
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000843 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000844 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar566a6502008-09-08 23:44:31 +0000845 Entry->eraseFromParent();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000846
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000847 Entry = NewFn;
848 }
849 }
850
Daniel Dunbar566a6502008-09-08 23:44:31 +0000851 llvm::Function *Fn = cast<llvm::Function>(Entry);
852 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000853
Daniel Dunbar566a6502008-09-08 23:44:31 +0000854 SetFunctionAttributesForDefinition(D, Fn);
855
856 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
857 AddGlobalCtor(Fn, CA->getPriority());
858 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
859 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000860 }
861}
862
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000863llvm::Function *
864CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
865 const std::string &Name) {
866 llvm::Function *Fn = llvm::Function::Create(FTy,
867 llvm::Function::ExternalLinkage,
868 "", &TheModule);
869 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
870 return Fn;
871}
872
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000873void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
874 // Make sure that this type is translated.
875 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000876}
877
878
Chris Lattnerab862cc2007-08-31 04:31:45 +0000879/// getBuiltinLibFunction
880llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000881 if (BuiltinID > BuiltinFunctions.size())
882 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000883
Chris Lattner9f2d6892007-12-13 00:38:03 +0000884 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
885 // a slot for it.
886 assert(BuiltinID && "Invalid Builtin ID");
887 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000888 if (FunctionSlot)
889 return FunctionSlot;
890
Douglas Gregor411889e2009-02-13 23:20:09 +0000891 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
892 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
893 "isn't a lib fn");
Chris Lattnerab862cc2007-08-31 04:31:45 +0000894
Douglas Gregor411889e2009-02-13 23:20:09 +0000895 // Get the name, skip over the __builtin_ prefix (if necessary).
896 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
897 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
898 Name += 10;
Chris Lattnerab862cc2007-08-31 04:31:45 +0000899
900 // Get the type for the builtin.
Douglas Gregor1fa246d2009-02-14 01:52:53 +0000901 Builtin::Context::GetBuiltinTypeError Error;
902 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
903 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
904
Chris Lattnerab862cc2007-08-31 04:31:45 +0000905 const llvm::FunctionType *Ty =
906 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
907
908 // FIXME: This has a serious problem with code like this:
909 // void abs() {}
910 // ... __builtin_abs(x);
911 // The two versions of abs will collide. The fix is for the builtin to win,
912 // and for the existing one to be turned into a constantexpr cast of the
913 // builtin. In the case where the existing one is a static function, it
914 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000915 if (llvm::Function *Existing = getModule().getFunction(Name)) {
916 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
917 return FunctionSlot = Existing;
918 assert(Existing == 0 && "FIXME: Name collision");
919 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000920
921 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000922 return FunctionSlot =
923 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
924 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000925}
926
Chris Lattner4b23f942007-12-18 00:25:38 +0000927llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
928 unsigned NumTys) {
929 return llvm::Intrinsic::getDeclaration(&getModule(),
930 (llvm::Intrinsic::ID)IID, Tys, NumTys);
931}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000932
Chris Lattner4b009652007-07-25 00:24:17 +0000933llvm::Function *CodeGenModule::getMemCpyFn() {
934 if (MemCpyFn) return MemCpyFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000935 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
936 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000937}
Anders Carlsson36a04872007-08-21 00:21:21 +0000938
Eli Friedman8f08a252008-05-26 12:59:39 +0000939llvm::Function *CodeGenModule::getMemMoveFn() {
940 if (MemMoveFn) return MemMoveFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000941 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
942 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman8f08a252008-05-26 12:59:39 +0000943}
944
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000945llvm::Function *CodeGenModule::getMemSetFn() {
946 if (MemSetFn) return MemSetFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000947 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
948 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000949}
Chris Lattner4b23f942007-12-18 00:25:38 +0000950
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000951static void appendFieldAndPadding(CodeGenModule &CGM,
952 std::vector<llvm::Constant*>& Fields,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000953 FieldDecl *FieldD, FieldDecl *NextFieldD,
954 llvm::Constant* Field,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000955 RecordDecl* RD, const llvm::StructType *STy)
956{
957 // Append the field.
958 Fields.push_back(Field);
959
Douglas Gregor8acb7272008-12-11 16:49:14 +0000960 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000961
962 int NextStructFieldNo;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000963 if (!NextFieldD) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000964 NextStructFieldNo = STy->getNumElements();
965 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000966 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000967 }
968
969 // Append padding
970 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
971 llvm::Constant *C =
972 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
973
974 Fields.push_back(C);
975 }
976}
977
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000978// We still need to work out the details of handling UTF-16.
979// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +0000980llvm::Constant *CodeGenModule::
981GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000982 llvm::StringMapEntry<llvm::Constant *> &Entry =
983 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
984
985 if (Entry.getValue())
986 return Entry.getValue();
987
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000988 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
989 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +0000990
991 if (!CFConstantStringClassRef) {
992 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
993 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000994
995 // FIXME: This is fairly broken if
996 // __CFConstantStringClassReference is already defined, in that it
997 // will get renamed and the user will most likely see an opaque
998 // error message. This is a general issue with relying on
999 // particular names.
1000 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +00001001 new llvm::GlobalVariable(Ty, false,
1002 llvm::GlobalVariable::ExternalLinkage, 0,
1003 "__CFConstantStringClassReference",
1004 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001005
1006 // Decay array -> ptr
1007 CFConstantStringClassRef =
1008 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +00001009 }
1010
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001011 QualType CFTy = getContext().getCFConstantStringType();
1012 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001013
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001014 const llvm::StructType *STy =
1015 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1016
1017 std::vector<llvm::Constant*> Fields;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001018 RecordDecl::field_iterator Field = CFRD->field_begin();
1019
Anders Carlsson36a04872007-08-21 00:21:21 +00001020 // Class pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001021 FieldDecl *CurField = *Field++;
1022 FieldDecl *NextField = *Field++;
1023 appendFieldAndPadding(*this, Fields, CurField, NextField,
1024 CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001025
1026 // Flags.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001027 CurField = NextField;
1028 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001029 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001030 appendFieldAndPadding(*this, Fields, CurField, NextField,
1031 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001032
1033 // String pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001034 CurField = NextField;
1035 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001036 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +00001037 C = new llvm::GlobalVariable(C->getType(), true,
1038 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001039 C, ".str", &getModule());
Douglas Gregor8acb7272008-12-11 16:49:14 +00001040 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001041 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1042 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001043
1044 // String length.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001045 CurField = NextField;
1046 NextField = 0;
Anders Carlsson36a04872007-08-21 00:21:21 +00001047 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001048 appendFieldAndPadding(*this, Fields, CurField, NextField,
1049 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001050
1051 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001052 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +00001053 llvm::GlobalVariable *GV =
1054 new llvm::GlobalVariable(C->getType(), true,
1055 llvm::GlobalVariable::InternalLinkage,
1056 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001057
Anders Carlsson9be009e2007-11-01 00:41:52 +00001058 GV->setSection("__DATA,__cfstring");
1059 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001060
Anders Carlsson9be009e2007-11-01 00:41:52 +00001061 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +00001062}
Chris Lattnerdb6be562007-11-28 05:34:05 +00001063
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001064/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001065/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001066std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar952f4732008-08-29 17:28:43 +00001067 if (E->isWide()) {
1068 ErrorUnsupported(E, "wide string");
1069 return "FIXME";
1070 }
1071
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001072 const char *StrData = E->getStrData();
1073 unsigned Len = E->getByteLength();
1074
1075 const ConstantArrayType *CAT =
1076 getContext().getAsConstantArrayType(E->getType());
1077 assert(CAT && "String isn't pointer or array!");
1078
1079 // Resize the string to the right size
1080 // FIXME: What about wchar_t strings?
1081 std::string Str(StrData, StrData+Len);
1082 uint64_t RealLen = CAT->getSize().getZExtValue();
1083 Str.resize(RealLen, '\0');
1084
1085 return Str;
1086}
1087
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001088/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1089/// constant array for the given string literal.
1090llvm::Constant *
1091CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1092 // FIXME: This can be more efficient.
1093 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1094}
1095
Chris Lattnera6dcce32008-02-11 00:02:17 +00001096/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +00001097static llvm::Constant *GenerateStringLiteral(const std::string &str,
1098 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001099 CodeGenModule &CGM,
1100 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001101 // Create Constant for this string literal. Don't add a '\0'.
1102 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001103
1104 // Create a global variable for this string
1105 C = new llvm::GlobalVariable(C->getType(), constant,
1106 llvm::GlobalValue::InternalLinkage,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001107 C,
1108 GlobalName ? GlobalName : ".str",
1109 &CGM.getModule());
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001110
Chris Lattnerdb6be562007-11-28 05:34:05 +00001111 return C;
1112}
1113
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001114/// GetAddrOfConstantString - Returns a pointer to a character array
1115/// containing the literal. This contents are exactly that of the
1116/// given string, i.e. it will not be null terminated automatically;
1117/// see GetAddrOfConstantCString. Note that whether the result is
1118/// actually a pointer to an LLVM constant depends on
1119/// Feature.WriteableStrings.
1120///
1121/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001122llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1123 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +00001124 // Don't share any string literals if writable-strings is turned on.
1125 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001126 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001127
1128 llvm::StringMapEntry<llvm::Constant *> &Entry =
1129 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1130
1131 if (Entry.getValue())
1132 return Entry.getValue();
1133
1134 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001135 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001136 Entry.setValue(C);
1137 return C;
1138}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001139
1140/// GetAddrOfConstantCString - Returns a pointer to a character
1141/// array containing the literal and a terminating '\-'
1142/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001143llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1144 const char *GlobalName){
Chris Lattnerb2176012008-12-09 19:10:54 +00001145 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001146}
Daniel Dunbar27250d32008-08-15 23:26:23 +00001147
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001148/// EmitObjCPropertyImplementations - Emit information for synthesized
1149/// properties for an implementation.
1150void CodeGenModule::EmitObjCPropertyImplementations(const
1151 ObjCImplementationDecl *D) {
1152 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1153 e = D->propimpl_end(); i != e; ++i) {
1154 ObjCPropertyImplDecl *PID = *i;
1155
1156 // Dynamic is just for type-checking.
1157 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1158 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1159
1160 // Determine which methods need to be implemented, some may have
1161 // been overridden. Note that ::isSynthesized is not the method
1162 // we want, that just indicates if the decl came from a
1163 // property. What we want to know is if the method is defined in
1164 // this implementation.
1165 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001166 CodeGenFunction(*this).GenerateObjCGetter(
1167 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001168 if (!PD->isReadOnly() &&
1169 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001170 CodeGenFunction(*this).GenerateObjCSetter(
1171 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001172 }
1173 }
1174}
1175
Daniel Dunbar27250d32008-08-15 23:26:23 +00001176/// EmitTopLevelDecl - Emit code for a single top level declaration.
1177void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1178 // If an error has occurred, stop code generation, but continue
1179 // parsing and semantic analysis (to ensure all warnings and errors
1180 // are emitted).
1181 if (Diags.hasErrorOccurred())
1182 return;
1183
1184 switch (D->getKind()) {
1185 case Decl::Function:
1186 case Decl::Var:
1187 EmitGlobal(cast<ValueDecl>(D));
1188 break;
1189
1190 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001191 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001192 break;
1193
1194 // Objective-C Decls
1195
1196 // Forward declarations, no (immediate) code generation.
1197 case Decl::ObjCClass:
1198 case Decl::ObjCCategory:
1199 case Decl::ObjCForwardProtocol:
1200 case Decl::ObjCInterface:
1201 break;
1202
1203 case Decl::ObjCProtocol:
1204 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1205 break;
1206
1207 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001208 // Categories have properties but don't support synthesize so we
1209 // can ignore them here.
1210
Daniel Dunbar27250d32008-08-15 23:26:23 +00001211 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1212 break;
1213
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001214 case Decl::ObjCImplementation: {
1215 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1216 EmitObjCPropertyImplementations(OMD);
1217 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001218 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001219 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001220 case Decl::ObjCMethod: {
1221 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1222 // If this is not a prototype, emit the body.
1223 if (OMD->getBody())
1224 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1225 break;
1226 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001227 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian2ac4cd32009-01-08 01:10:55 +00001228 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001229 break;
1230
1231 case Decl::LinkageSpec: {
1232 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1233 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001234 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001235 // FIXME: implement C++ linkage, C linkage works mostly by C
1236 // language reuse already.
1237 break;
1238 }
1239
1240 case Decl::FileScopeAsm: {
1241 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1242 std::string AsmString(AD->getAsmString()->getStrData(),
1243 AD->getAsmString()->getByteLength());
1244
1245 const std::string &S = getModule().getModuleInlineAsm();
1246 if (S.empty())
1247 getModule().setModuleInlineAsm(AsmString);
1248 else
1249 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1250 break;
1251 }
1252
1253 default:
1254 // Make sure we handled everything we should, every other kind is
1255 // a non-top-level decl. FIXME: Would be nice to have an
1256 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1257 // that easily.
1258 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1259 }
1260}