blob: ba77e44288ca38dad84160d23ce6869f7d756561 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor5f2bfd42009-02-13 00:10:09 +000019#include "Mangle.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000022#include "clang/AST/DeclCXX.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000023#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000024#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/TargetInfo.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000026#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000027#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "llvm/Intrinsics.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000029#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattner45e8cbd2007-11-28 05:34:05 +000034CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-12-02 01:40:18 +000035 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbarf77ac862008-08-11 21:35:06 +000036 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattnerfb97b032007-12-02 01:40:18 +000037 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000038 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Mike Stumpab695142009-02-13 15:16:56 +000039 CFConstantStringClassRef(0), NSConcreteGlobalBlock(0),
Mike Stump9b8a7972009-02-13 15:25:34 +000040 BlockDescriptorType(0), GenericBlockLiteralType(0) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000041
42 if (Features.ObjC1) {
Daniel Dunbarf77ac862008-08-11 21:35:06 +000043 if (Features.NeXTRuntime) {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000044 Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this)
Fariborz Jahanianee0af742009-01-21 22:04:16 +000045 : CreateMacObjCRuntime(*this);
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000046 } else {
47 Runtime = CreateGNUObjCRuntime(*this);
48 }
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000049 }
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000050
51 // If debug info generation is enabled, create the CGDebugInfo object.
Mike Stump26efc332009-02-13 18:36:05 +000052 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
53
54 Block.GlobalUniqueCount = 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000055}
56
57CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000058 delete Runtime;
59 delete DebugInfo;
60}
61
62void CodeGenModule::Release() {
Daniel Dunbar02698712009-02-13 20:29:50 +000063 EmitDeferred();
Daniel Dunbar219df662008-09-08 23:44:31 +000064 EmitAliases();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000065 if (Runtime)
66 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
67 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000068 EmitCtorList(GlobalCtors, "llvm.global_ctors");
69 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000070 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +000071 EmitLLVMUsed();
Daniel Dunbarf1968f22008-10-01 00:49:24 +000072 BindRuntimeFunctions();
Chris Lattner2b94fe32008-03-01 08:45:05 +000073}
Reid Spencer5f016e22007-07-11 17:01:13 +000074
Daniel Dunbarf1968f22008-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 Dunbar0293d542008-11-19 06:15:35 +000081 // Discard unused runtime functions.
82 if (Fn->use_empty()) {
83 Fn->eraseFromParent();
84 continue;
85 }
86
Daniel Dunbarf1968f22008-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 Dunbar488e9932008-08-16 00:56:44 +0000113/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000114/// specified stmt yet.
Daniel Dunbar90df4b62008-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 Dunbar488e9932008-08-16 00:56:44 +0000119 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000120 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000121 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000122 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
123 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000124}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000125
Daniel Dunbar488e9932008-08-16 00:56:44 +0000126/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000127/// specified decl yet.
Daniel Dunbar90df4b62008-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 Dunbar488e9932008-08-16 00:56:44 +0000132 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000133 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000134 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000135 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000136}
137
Daniel Dunbar41071de2008-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 Gohman4f8d1232008-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 Gregor5f2bfd42009-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
165/// changes to the GlobalDeclMap, too.
166///
167/// FIXME: Performance here is going to be terribly until we start
168/// caching mangled names. However, we should fix the problem above
169/// first.
170IdentifierInfo *CodeGenModule::getMangledName(const NamedDecl *ND) const {
171 std::string Name;
172 llvm::raw_string_ostream Out(Name);
173 if (!mangleName(ND, Context, Out))
174 return ND->getIdentifier();
175
176 return &Context.Idents.get(Out.str());
177}
178
Chris Lattner6d397602008-03-14 17:18:18 +0000179/// AddGlobalCtor - Add a function to the list that will be called before
180/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000181void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000182 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000183 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000184}
185
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000186/// AddGlobalDtor - Add a function to the list that will be called
187/// when the module is unloaded.
188void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000189 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000190 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
191}
192
193void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
194 // Ctor function type is void()*.
195 llvm::FunctionType* CtorFTy =
196 llvm::FunctionType::get(llvm::Type::VoidTy,
197 std::vector<const llvm::Type*>(),
198 false);
199 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
200
201 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000202 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000203 llvm::StructType::get(llvm::Type::Int32Ty,
204 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000205
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000206 // Construct the constructor and destructor arrays.
207 std::vector<llvm::Constant*> Ctors;
208 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
209 std::vector<llvm::Constant*> S;
210 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
211 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
212 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000213 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000214
215 if (!Ctors.empty()) {
216 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
217 new llvm::GlobalVariable(AT, false,
218 llvm::GlobalValue::AppendingLinkage,
219 llvm::ConstantArray::get(AT, Ctors),
220 GlobalName,
221 &TheModule);
222 }
Chris Lattner6d397602008-03-14 17:18:18 +0000223}
224
Nate Begeman532485c2008-04-18 23:43:57 +0000225void CodeGenModule::EmitAnnotations() {
226 if (Annotations.empty())
227 return;
228
229 // Create a new global variable for the ConstantStruct in the Module.
230 llvm::Constant *Array =
231 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
232 Annotations.size()),
233 Annotations);
234 llvm::GlobalValue *gv =
235 new llvm::GlobalVariable(Array->getType(), false,
236 llvm::GlobalValue::AppendingLinkage, Array,
237 "llvm.global.annotations", &TheModule);
238 gv->setSection("llvm.metadata");
239}
240
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000241void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
242 bool IsInternal,
243 bool IsInline,
244 llvm::GlobalValue *GV,
245 bool ForDefinition) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000246 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000247 // approximation of what we really want.
Daniel Dunbar219df662008-09-08 23:44:31 +0000248 if (!ForDefinition) {
249 // Only a few attributes are set on declarations.
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000250 if (D->getAttr<DLLImportAttr>()) {
251 // The dllimport attribute is overridden by a subsequent declaration as
252 // dllexport.
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000253 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000254 // dllimport attribute can be applied only to function decls, not to
255 // definitions.
256 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
257 if (!FD->getBody())
258 GV->setLinkage(llvm::Function::DLLImportLinkage);
259 } else
260 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000261 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000262 }
Daniel Dunbar219df662008-09-08 23:44:31 +0000263 } else {
264 if (IsInternal) {
265 GV->setLinkage(llvm::Function::InternalLinkage);
266 } else {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000267 if (D->getAttr<DLLExportAttr>()) {
268 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
269 // The dllexport attribute is ignored for undefined symbols.
270 if (FD->getBody())
271 GV->setLinkage(llvm::Function::DLLExportLinkage);
272 } else
273 GV->setLinkage(llvm::Function::DLLExportLinkage);
274 } else if (D->getAttr<WeakAttr>() || IsInline)
Daniel Dunbar219df662008-09-08 23:44:31 +0000275 GV->setLinkage(llvm::Function::WeakLinkage);
276 }
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000277 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000278
Daniel Dunbar49988882009-01-13 02:25:00 +0000279 // FIXME: Figure out the relative priority of the attribute,
280 // -fvisibility, and private_extern.
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000281 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000282 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000283 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000284
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000285 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbara735ad82008-08-06 00:03:29 +0000286 // Prefaced with special LLVM marker to indicate that the name
287 // should not be munged.
288 GV->setName("\01" + ALA->getLabel());
289 }
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000290
291 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
292 GV->setSection(SA->getName());
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000293
294 // Only add to llvm.used when we see a definition, otherwise we
295 // might add multiple times or risk the value being replaced by a
296 // subsequent RAUW.
297 if (ForDefinition) {
298 if (D->getAttr<UsedAttr>())
299 AddUsedGlobal(GV);
300 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000301}
302
Devang Patel761d7f72008-09-25 21:02:23 +0000303void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000304 const CGFunctionInfo &Info,
Daniel Dunbarb7688072008-09-10 00:41:16 +0000305 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000306 AttributeListType AttributeList;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000307 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000308
Devang Patel761d7f72008-09-25 21:02:23 +0000309 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
310 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000311
312 // Set the appropriate calling convention for the Function.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000313 if (D->getAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000314 F->setCallingConv(llvm::CallingConv::X86_FastCall);
315
316 if (D->getAttr<StdCallAttr>())
317 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000318}
319
320/// SetFunctionAttributesForDefinition - Set function attributes
321/// specific to a function definition.
Daniel Dunbar219df662008-09-08 23:44:31 +0000322void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
323 llvm::Function *F) {
324 if (isa<ObjCMethodDecl>(D)) {
325 SetGlobalValueAttributes(D, true, false, F, true);
326 } else {
327 const FunctionDecl *FD = cast<FunctionDecl>(D);
328 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
329 FD->isInline(), F, true);
330 }
331
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000332 if (!Features.Exceptions)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000333 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000334
335 if (D->getAttr<AlwaysInlineAttr>())
336 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000337}
338
339void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
340 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000341 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000342
Daniel Dunbar219df662008-09-08 23:44:31 +0000343 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000344}
345
346void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
347 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000348 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000349
Daniel Dunbar219df662008-09-08 23:44:31 +0000350 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
351 FD->isInline(), F, false);
352}
353
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000354
Daniel Dunbar219df662008-09-08 23:44:31 +0000355void CodeGenModule::EmitAliases() {
356 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
357 const FunctionDecl *D = Aliases[i];
358 const AliasAttr *AA = D->getAttr<AliasAttr>();
359
360 // This is something of a hack, if the FunctionDecl got overridden
361 // then its attributes will be moved to the new declaration. In
362 // this case the current decl has no alias attribute, but we will
363 // eventually see it.
364 if (!AA)
365 continue;
366
367 const std::string& aliaseeName = AA->getAliasee();
368 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
369 if (!aliasee) {
370 // FIXME: This isn't unsupported, this is just an error, which
371 // sema should catch, but...
372 ErrorUnsupported(D, "alias referencing a missing function");
373 continue;
374 }
375
376 llvm::GlobalValue *GA =
377 new llvm::GlobalAlias(aliasee->getType(),
378 llvm::Function::ExternalLinkage,
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000379 getMangledName(D)->getName(), aliasee,
380 &getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000381
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000382 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar219df662008-09-08 23:44:31 +0000383 if (Entry) {
384 // If we created a dummy function for this then replace it.
385 GA->takeName(Entry);
386
387 llvm::Value *Casted =
388 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
389 Entry->replaceAllUsesWith(Casted);
390 Entry->eraseFromParent();
391
392 Entry = GA;
393 }
394
395 // Alias should never be internal or inline.
396 SetGlobalValueAttributes(D, false, false, GA, true);
397 }
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000398}
399
Daniel Dunbar02698712009-02-13 20:29:50 +0000400void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
401 assert(!GV->isDeclaration() &&
402 "Only globals with definition can force usage.");
403 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
404 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
405}
406
407void CodeGenModule::EmitLLVMUsed() {
408 // Don't create llvm.used if there is no need.
409 if (LLVMUsed.empty())
410 return;
411
412 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
413 LLVMUsed.size());
414 llvm::GlobalVariable *GV =
415 new llvm::GlobalVariable(ATy, false,
416 llvm::GlobalValue::AppendingLinkage,
417 llvm::ConstantArray::get(ATy, LLVMUsed),
418 "llvm.used", &getModule());
419
420 GV->setSection("llvm.metadata");
421}
422
423void CodeGenModule::EmitDeferred() {
424 // Emit code for any deferred decl which was used. Since a
425 // previously unused static decl may become used during the
426 // generation of code for a static function, iterate until no
427 // changes are made.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000428 bool Changed;
429 do {
430 Changed = false;
Anders Carlssonb723f752009-01-04 02:08:04 +0000431
Daniel Dunbar02698712009-02-13 20:29:50 +0000432 for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(),
433 e = DeferredDecls.end(); i != e; ) {
Anders Carlssonb723f752009-01-04 02:08:04 +0000434 const ValueDecl *D = *i;
435
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000436 // Check if we have used a decl with the same name
437 // FIXME: The AST should have some sort of aggregate decls or
438 // global symbol map.
Daniel Dunbar219df662008-09-08 23:44:31 +0000439 // FIXME: This is missing some important cases. For example, we
Daniel Dunbar73241df2009-02-13 21:18:01 +0000440 // need to check for uses in an alias.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000441 if (!GlobalDeclMap.count(getMangledName(D))) {
Anders Carlssonb723f752009-01-04 02:08:04 +0000442 i++;
Daniel Dunbara735ad82008-08-06 00:03:29 +0000443 continue;
Anders Carlssonb723f752009-01-04 02:08:04 +0000444 }
445
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000446 // Emit the definition.
447 EmitGlobalDefinition(D);
448
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000449 // Erase the used decl from the list.
Daniel Dunbar02698712009-02-13 20:29:50 +0000450 i = DeferredDecls.erase(i);
Anders Carlssonb723f752009-01-04 02:08:04 +0000451
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000452 // Remember that we made a change.
453 Changed = true;
454 }
455 } while (Changed);
Reid Spencer5f016e22007-07-11 17:01:13 +0000456}
457
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000458/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
459/// annotation information for a given GlobalValue. The annotation struct is
460/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000461/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000462/// created from the AnnotateAttr's annotation. The third field is a constant
463/// string containing the name of the translation unit. The fourth field is
464/// the line number in the file of the annotated value declaration.
465///
466/// FIXME: this does not unique the annotation string constants, as llvm-gcc
467/// appears to.
468///
469llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
470 const AnnotateAttr *AA,
471 unsigned LineNo) {
472 llvm::Module *M = &getModule();
473
474 // get [N x i8] constants for the annotation string, and the filename string
475 // which are the 2nd and 3rd elements of the global annotation structure.
476 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
477 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
478 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
479 true);
480
481 // Get the two global values corresponding to the ConstantArrays we just
482 // created to hold the bytes of the strings.
483 llvm::GlobalValue *annoGV =
484 new llvm::GlobalVariable(anno->getType(), false,
485 llvm::GlobalValue::InternalLinkage, anno,
486 GV->getName() + ".str", M);
487 // translation unit name string, emitted into the llvm.metadata section.
488 llvm::GlobalValue *unitGV =
489 new llvm::GlobalVariable(unit->getType(), false,
490 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
491
492 // Create the ConstantStruct that is the global annotion.
493 llvm::Constant *Fields[4] = {
494 llvm::ConstantExpr::getBitCast(GV, SBP),
495 llvm::ConstantExpr::getBitCast(annoGV, SBP),
496 llvm::ConstantExpr::getBitCast(unitGV, SBP),
497 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
498 };
499 return llvm::ConstantStruct::get(Fields, 4, false);
500}
501
Daniel Dunbar73241df2009-02-13 21:18:01 +0000502bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000503 // Never defer when EmitAllDecls is specified or the decl has
504 // attribute used.
505 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000506 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000507
508 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000509 // Constructors and destructors should never be deferred.
510 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
511 return false;
512
513 if (FD->getStorageClass() != FunctionDecl::Static)
514 return false;
515 } else {
516 const VarDecl *VD = cast<VarDecl>(Global);
517 assert(VD->isFileVarDecl() && "Invalid decl.");
518
519 if (VD->getStorageClass() != VarDecl::Static)
520 return false;
521 }
522
523 return true;
524}
525
526void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
527 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000528 // Aliases are deferred until code for everything else has been
529 // emitted.
530 if (FD->getAttr<AliasAttr>()) {
531 assert(!FD->isThisDeclarationADefinition() &&
532 "Function alias cannot have a definition!");
533 Aliases.push_back(FD);
534 return;
535 }
536
Daniel Dunbar73241df2009-02-13 21:18:01 +0000537 // Forward declarations are emitted lazily on first use.
538 if (!FD->isThisDeclarationADefinition())
539 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000540 } else {
541 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000542 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
543
Daniel Dunbar73241df2009-02-13 21:18:01 +0000544 // Forward declarations are emitted lazily on first use.
Daniel Dunbar7542bca2009-02-13 22:49:13 +0000545 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000546 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000547 }
548
Daniel Dunbar73241df2009-02-13 21:18:01 +0000549 // Defer code generation when possible.
550 if (MayDeferGeneration(Global)) {
Daniel Dunbar02698712009-02-13 20:29:50 +0000551 DeferredDecls.push_back(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000552 return;
553 }
554
555 // Otherwise emit the definition.
556 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000557}
558
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000559void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
560 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
561 EmitGlobalFunctionDefinition(FD);
562 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
563 EmitGlobalVarDefinition(VD);
564 } else {
565 assert(0 && "Invalid argument to EmitGlobalDefinition()");
566 }
567}
568
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000569 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000570 assert(D->hasGlobalStorage() && "Not a global variable");
571
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000572 QualType ASTTy = D->getType();
573 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000574 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000575
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000576 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000577 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar49988882009-01-13 02:25:00 +0000578 if (!Entry) {
579 llvm::GlobalVariable *GV =
580 new llvm::GlobalVariable(Ty, false,
581 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000582 0, getMangledName(D)->getName(), &getModule(),
583 0, ASTTy.getAddressSpace());
Daniel Dunbar49988882009-01-13 02:25:00 +0000584 Entry = GV;
585
586 // Handle things which are present even on external declarations.
587
588 // FIXME: This code is overly simple and should be merged with
589 // other global handling.
590
591 GV->setConstant(D->getType().isConstant(Context));
592
593 if (D->getStorageClass() == VarDecl::PrivateExtern)
594 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
595 }
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000596
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000597 // Make sure the result is of the correct type.
598 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000599}
600
601void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000602 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000603 QualType ASTTy = D->getType();
604 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000605
Chris Lattner8f32f712007-07-14 00:23:28 +0000606 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000607 // This is a tentative definition; tentative definitions are
608 // implicitly initialized with { 0 }
609 const llvm::Type* InitTy;
610 if (ASTTy->isIncompleteArrayType()) {
611 // An incomplete array is normally [ TYPE x 0 ], but we need
612 // to fix it to [ TYPE x 1 ].
613 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
614 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
615 } else {
616 InitTy = VarTy;
617 }
618 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000619 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000620 Init = EmitConstantExpr(D->getInit());
Eli Friedman77ba7082008-05-30 19:50:47 +0000621 }
622 const llvm::Type* InitType = Init->getType();
623
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000624 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000625 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
626
Eli Friedman77ba7082008-05-30 19:50:47 +0000627 if (!GV) {
628 GV = new llvm::GlobalVariable(InitType, false,
629 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000630 0, getMangledName(D)->getName(),
631 &getModule(), 0, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000632 } else if (GV->getType() !=
633 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000634 // We have a definition after a prototype with the wrong type.
635 // We must make a new GlobalVariable* and update everything that used OldGV
636 // (a declaration or tentative definition) with the new GlobalVariable*
637 // (which will be a definition).
638 //
639 // This happens if there is a prototype for a global (e.g. "extern int x[];")
640 // and then a definition of a different type (e.g. "int x[10];"). This also
641 // happens when an initializer has a different type from the type of the
642 // global (this happens with unions).
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000643 //
644 // FIXME: This also ends up happening if there's a definition followed by
645 // a tentative definition! (Although Sema rejects that construct
646 // at the moment.)
Eli Friedman77ba7082008-05-30 19:50:47 +0000647
648 // Save the old global
649 llvm::GlobalVariable *OldGV = GV;
650
651 // Make a new global with the correct type
652 GV = new llvm::GlobalVariable(InitType, false,
653 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000654 0, getMangledName(D)->getName(),
655 &getModule(), 0, ASTTy.getAddressSpace());
Eli Friedman77ba7082008-05-30 19:50:47 +0000656 // Steal the name of the old global
657 GV->takeName(OldGV);
658
659 // Replace all uses of the old global with the new global
660 llvm::Constant *NewPtrForOldDecl =
661 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
662 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000663
664 // Erase the old global, since it is no longer used.
665 OldGV->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000666 }
Devang Patel8e53e722007-10-26 16:31:40 +0000667
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000668 Entry = GV;
Devang Patel8e53e722007-10-26 16:31:40 +0000669
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000670 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
671 SourceManager &SM = Context.getSourceManager();
672 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000673 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000674 }
675
Chris Lattner88a69ad2007-07-13 05:13:43 +0000676 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000677 GV->setConstant(D->getType().isConstant(Context));
Chris Lattnerddee4232008-03-03 03:28:21 +0000678
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000679 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
680 unsigned Align;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000681 if (const IncompleteArrayType* IAT =
682 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000683 Align = Context.getTypeAlign(IAT->getElementType());
684 else
685 Align = Context.getTypeAlign(D->getType());
Eli Friedman08d78022008-05-29 11:10:27 +0000686 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
687 Align = std::max(Align, AA->getAlignment());
688 }
689 GV->setAlignment(Align / 8);
690
Chris Lattnerddee4232008-03-03 03:28:21 +0000691 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000692 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000693 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000694
695 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
696 // Prefaced with special LLVM marker to indicate that the name
697 // should not be munged.
698 GV->setName("\01" + ALA->getLabel());
699 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000700
701 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000702 if (D->getStorageClass() == VarDecl::Static)
703 GV->setLinkage(llvm::Function::InternalLinkage);
704 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000705 GV->setLinkage(llvm::Function::DLLImportLinkage);
706 else if (D->getAttr<DLLExportAttr>())
707 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000708 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000709 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000710 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000711 // FIXME: This isn't right. This should handle common linkage and other
712 // stuff.
713 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000714 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000715 case VarDecl::Auto:
716 case VarDecl::Register:
717 assert(0 && "Can't have auto or register globals");
718 case VarDecl::None:
719 if (!D->getInit())
Eli Friedmana07b7642008-05-29 11:03:17 +0000720 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson98883e12008-12-03 05:51:23 +0000721 else
722 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000723 break;
724 case VarDecl::Extern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000725 // FIXME: common
726 break;
727
Chris Lattnerddee4232008-03-03 03:28:21 +0000728 case VarDecl::PrivateExtern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000729 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
730 // FIXME: common
Chris Lattnerddee4232008-03-03 03:28:21 +0000731 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000732 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000733 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000734
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000735 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
736 GV->setSection(SA->getName());
737
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000738 if (D->getAttr<UsedAttr>())
739 AddUsedGlobal(GV);
740
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000741 // Emit global variable debug information.
742 CGDebugInfo *DI = getDebugInfo();
743 if(DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000744 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000745 DI->EmitGlobalVariable(GV, D);
746 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000747}
Reid Spencer5f016e22007-07-11 17:01:13 +0000748
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000749llvm::GlobalValue *
750CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000751 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
752 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
753 llvm::Function::ExternalLinkage,
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000754 getMangledName(D)->getName(),
755 &getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000756 SetFunctionAttributes(D, F);
757 return F;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000758}
759
760llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000761 QualType ASTTy = D->getType();
762 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
763 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000764
765 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000766 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000767 if (!Entry)
768 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000769
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000770 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000771}
772
773void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000774 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000775 if (!Entry) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000776 Entry = EmitForwardFunctionDefinition(D);
777 } else {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000778 // If the types mismatch then we have to rewrite the definition.
779 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
780 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000781 // Otherwise, we have a definition after a prototype with the wrong type.
782 // F is the Function* for the one with the wrong type, we must make a new
783 // Function* and update everything that used F (a declaration) with the new
784 // Function* (which will be a definition).
785 //
786 // This happens if there is a prototype for a function (e.g. "int f()") and
787 // then a definition of a different type (e.g. "int f(int x)"). Start by
788 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000789 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
790 NewFn->takeName(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000791
792 // Replace uses of F with the Function we will endow with a body.
793 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000794 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
795 Entry->replaceAllUsesWith(NewPtrForOldDecl);
796
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000797 // Ok, delete the old function now, which is dead.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000798 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar219df662008-09-08 23:44:31 +0000799 Entry->eraseFromParent();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000800
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000801 Entry = NewFn;
802 }
803 }
804
Daniel Dunbar219df662008-09-08 23:44:31 +0000805 llvm::Function *Fn = cast<llvm::Function>(Entry);
806 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000807
Daniel Dunbar219df662008-09-08 23:44:31 +0000808 SetFunctionAttributesForDefinition(D, Fn);
809
810 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
811 AddGlobalCtor(Fn, CA->getPriority());
812 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
813 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000814 }
815}
816
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000817llvm::Function *
818CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
819 const std::string &Name) {
820 llvm::Function *Fn = llvm::Function::Create(FTy,
821 llvm::Function::ExternalLinkage,
822 "", &TheModule);
823 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
824 return Fn;
825}
826
Chris Lattnerc5b88062008-02-06 05:08:19 +0000827void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
828 // Make sure that this type is translated.
829 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000830}
831
832
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000833/// getBuiltinLibFunction
834llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000835 if (BuiltinID > BuiltinFunctions.size())
836 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000837
Chris Lattner1426fec2007-12-13 00:38:03 +0000838 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
839 // a slot for it.
840 assert(BuiltinID && "Invalid Builtin ID");
841 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000842 if (FunctionSlot)
843 return FunctionSlot;
844
Douglas Gregor3e41d602009-02-13 23:20:09 +0000845 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
846 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
847 "isn't a lib fn");
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000848
Douglas Gregor3e41d602009-02-13 23:20:09 +0000849 // Get the name, skip over the __builtin_ prefix (if necessary).
850 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
851 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
852 Name += 10;
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000853
854 // Get the type for the builtin.
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000855 Builtin::Context::GetBuiltinTypeError Error;
856 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
857 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
858
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000859 const llvm::FunctionType *Ty =
860 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
861
862 // FIXME: This has a serious problem with code like this:
863 // void abs() {}
864 // ... __builtin_abs(x);
865 // The two versions of abs will collide. The fix is for the builtin to win,
866 // and for the existing one to be turned into a constantexpr cast of the
867 // builtin. In the case where the existing one is a static function, it
868 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000869 if (llvm::Function *Existing = getModule().getFunction(Name)) {
870 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
871 return FunctionSlot = Existing;
872 assert(Existing == 0 && "FIXME: Name collision");
873 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000874
875 // FIXME: param attributes for sext/zext etc.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000876 return FunctionSlot =
877 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
878 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000879}
880
Chris Lattner7acda7c2007-12-18 00:25:38 +0000881llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
882 unsigned NumTys) {
883 return llvm::Intrinsic::getDeclaration(&getModule(),
884 (llvm::Intrinsic::ID)IID, Tys, NumTys);
885}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000886
Reid Spencer5f016e22007-07-11 17:01:13 +0000887llvm::Function *CodeGenModule::getMemCpyFn() {
888 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000889 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
890 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000891}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000892
Eli Friedman0c995092008-05-26 12:59:39 +0000893llvm::Function *CodeGenModule::getMemMoveFn() {
894 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000895 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
896 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +0000897}
898
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000899llvm::Function *CodeGenModule::getMemSetFn() {
900 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000901 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
902 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000903}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000904
Anders Carlssone3daa762008-11-15 18:54:24 +0000905static void appendFieldAndPadding(CodeGenModule &CGM,
906 std::vector<llvm::Constant*>& Fields,
Douglas Gregor44b43212008-12-11 16:49:14 +0000907 FieldDecl *FieldD, FieldDecl *NextFieldD,
908 llvm::Constant* Field,
Anders Carlssone3daa762008-11-15 18:54:24 +0000909 RecordDecl* RD, const llvm::StructType *STy)
910{
911 // Append the field.
912 Fields.push_back(Field);
913
Douglas Gregor44b43212008-12-11 16:49:14 +0000914 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000915
916 int NextStructFieldNo;
Douglas Gregor44b43212008-12-11 16:49:14 +0000917 if (!NextFieldD) {
Anders Carlssone3daa762008-11-15 18:54:24 +0000918 NextStructFieldNo = STy->getNumElements();
919 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000920 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000921 }
922
923 // Append padding
924 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
925 llvm::Constant *C =
926 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
927
928 Fields.push_back(C);
929 }
930}
931
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000932// We still need to work out the details of handling UTF-16.
933// See: <rdr://2996215>
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000934llvm::Constant *CodeGenModule::
935GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000936 llvm::StringMapEntry<llvm::Constant *> &Entry =
937 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
938
939 if (Entry.getValue())
940 return Entry.getValue();
941
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000942 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
943 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +0000944
945 if (!CFConstantStringClassRef) {
946 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
947 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000948
949 // FIXME: This is fairly broken if
950 // __CFConstantStringClassReference is already defined, in that it
951 // will get renamed and the user will most likely see an opaque
952 // error message. This is a general issue with relying on
953 // particular names.
954 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +0000955 new llvm::GlobalVariable(Ty, false,
956 llvm::GlobalVariable::ExternalLinkage, 0,
957 "__CFConstantStringClassReference",
958 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000959
960 // Decay array -> ptr
961 CFConstantStringClassRef =
962 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000963 }
964
Anders Carlssone3daa762008-11-15 18:54:24 +0000965 QualType CFTy = getContext().getCFConstantStringType();
966 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000967
Anders Carlssone3daa762008-11-15 18:54:24 +0000968 const llvm::StructType *STy =
969 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
970
971 std::vector<llvm::Constant*> Fields;
Douglas Gregor44b43212008-12-11 16:49:14 +0000972 RecordDecl::field_iterator Field = CFRD->field_begin();
973
Anders Carlssonc9e20912007-08-21 00:21:21 +0000974 // Class pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +0000975 FieldDecl *CurField = *Field++;
976 FieldDecl *NextField = *Field++;
977 appendFieldAndPadding(*this, Fields, CurField, NextField,
978 CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000979
980 // Flags.
Douglas Gregor44b43212008-12-11 16:49:14 +0000981 CurField = NextField;
982 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000983 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor44b43212008-12-11 16:49:14 +0000984 appendFieldAndPadding(*this, Fields, CurField, NextField,
985 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000986
987 // String pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +0000988 CurField = NextField;
989 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000990 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000991 C = new llvm::GlobalVariable(C->getType(), true,
992 llvm::GlobalValue::InternalLinkage,
Anders Carlssone3daa762008-11-15 18:54:24 +0000993 C, ".str", &getModule());
Douglas Gregor44b43212008-12-11 16:49:14 +0000994 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlssone3daa762008-11-15 18:54:24 +0000995 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
996 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000997
998 // String length.
Douglas Gregor44b43212008-12-11 16:49:14 +0000999 CurField = NextField;
1000 NextField = 0;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001001 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001002 appendFieldAndPadding(*this, Fields, CurField, NextField,
1003 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001004
1005 // The struct.
Anders Carlssone3daa762008-11-15 18:54:24 +00001006 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +00001007 llvm::GlobalVariable *GV =
1008 new llvm::GlobalVariable(C->getType(), true,
1009 llvm::GlobalVariable::InternalLinkage,
1010 C, "", &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001011
Anders Carlsson0c678292007-11-01 00:41:52 +00001012 GV->setSection("__DATA,__cfstring");
1013 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001014
Anders Carlsson0c678292007-11-01 00:41:52 +00001015 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001016}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001017
Daniel Dunbar61432932008-08-13 23:20:05 +00001018/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001019/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001020std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar662174c82008-08-29 17:28:43 +00001021 if (E->isWide()) {
1022 ErrorUnsupported(E, "wide string");
1023 return "FIXME";
1024 }
1025
Daniel Dunbar1e049762008-08-10 20:25:57 +00001026 const char *StrData = E->getStrData();
1027 unsigned Len = E->getByteLength();
1028
1029 const ConstantArrayType *CAT =
1030 getContext().getAsConstantArrayType(E->getType());
1031 assert(CAT && "String isn't pointer or array!");
1032
1033 // Resize the string to the right size
1034 // FIXME: What about wchar_t strings?
1035 std::string Str(StrData, StrData+Len);
1036 uint64_t RealLen = CAT->getSize().getZExtValue();
1037 Str.resize(RealLen, '\0');
1038
1039 return Str;
1040}
1041
Daniel Dunbar61432932008-08-13 23:20:05 +00001042/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1043/// constant array for the given string literal.
1044llvm::Constant *
1045CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1046 // FIXME: This can be more efficient.
1047 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1048}
1049
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001050/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001051static llvm::Constant *GenerateStringLiteral(const std::string &str,
1052 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001053 CodeGenModule &CGM,
1054 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001055 // Create Constant for this string literal. Don't add a '\0'.
1056 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001057
1058 // Create a global variable for this string
1059 C = new llvm::GlobalVariable(C->getType(), constant,
1060 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001061 C,
1062 GlobalName ? GlobalName : ".str",
1063 &CGM.getModule());
Daniel Dunbar61432932008-08-13 23:20:05 +00001064
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001065 return C;
1066}
1067
Daniel Dunbar61432932008-08-13 23:20:05 +00001068/// GetAddrOfConstantString - Returns a pointer to a character array
1069/// containing the literal. This contents are exactly that of the
1070/// given string, i.e. it will not be null terminated automatically;
1071/// see GetAddrOfConstantCString. Note that whether the result is
1072/// actually a pointer to an LLVM constant depends on
1073/// Feature.WriteableStrings.
1074///
1075/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001076llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1077 const char *GlobalName) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001078 // Don't share any string literals if writable-strings is turned on.
1079 if (Features.WritableStrings)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001080 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001081
1082 llvm::StringMapEntry<llvm::Constant *> &Entry =
1083 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1084
1085 if (Entry.getValue())
1086 return Entry.getValue();
1087
1088 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001089 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001090 Entry.setValue(C);
1091 return C;
1092}
Daniel Dunbar61432932008-08-13 23:20:05 +00001093
1094/// GetAddrOfConstantCString - Returns a pointer to a character
1095/// array containing the literal and a terminating '\-'
1096/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001097llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1098 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001099 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001100}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001101
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001102/// EmitObjCPropertyImplementations - Emit information for synthesized
1103/// properties for an implementation.
1104void CodeGenModule::EmitObjCPropertyImplementations(const
1105 ObjCImplementationDecl *D) {
1106 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1107 e = D->propimpl_end(); i != e; ++i) {
1108 ObjCPropertyImplDecl *PID = *i;
1109
1110 // Dynamic is just for type-checking.
1111 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1112 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1113
1114 // Determine which methods need to be implemented, some may have
1115 // been overridden. Note that ::isSynthesized is not the method
1116 // we want, that just indicates if the decl came from a
1117 // property. What we want to know is if the method is defined in
1118 // this implementation.
1119 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001120 CodeGenFunction(*this).GenerateObjCGetter(
1121 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001122 if (!PD->isReadOnly() &&
1123 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001124 CodeGenFunction(*this).GenerateObjCSetter(
1125 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001126 }
1127 }
1128}
1129
Daniel Dunbar41071de2008-08-15 23:26:23 +00001130/// EmitTopLevelDecl - Emit code for a single top level declaration.
1131void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1132 // If an error has occurred, stop code generation, but continue
1133 // parsing and semantic analysis (to ensure all warnings and errors
1134 // are emitted).
1135 if (Diags.hasErrorOccurred())
1136 return;
1137
1138 switch (D->getKind()) {
1139 case Decl::Function:
1140 case Decl::Var:
1141 EmitGlobal(cast<ValueDecl>(D));
1142 break;
1143
1144 case Decl::Namespace:
Daniel Dunbar662174c82008-08-29 17:28:43 +00001145 ErrorUnsupported(D, "namespace");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001146 break;
1147
1148 // Objective-C Decls
1149
1150 // Forward declarations, no (immediate) code generation.
1151 case Decl::ObjCClass:
1152 case Decl::ObjCCategory:
1153 case Decl::ObjCForwardProtocol:
1154 case Decl::ObjCInterface:
1155 break;
1156
1157 case Decl::ObjCProtocol:
1158 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1159 break;
1160
1161 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001162 // Categories have properties but don't support synthesize so we
1163 // can ignore them here.
1164
Daniel Dunbar41071de2008-08-15 23:26:23 +00001165 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1166 break;
1167
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001168 case Decl::ObjCImplementation: {
1169 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1170 EmitObjCPropertyImplementations(OMD);
1171 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001172 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001173 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001174 case Decl::ObjCMethod: {
1175 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1176 // If this is not a prototype, emit the body.
1177 if (OMD->getBody())
1178 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1179 break;
1180 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001181 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001182 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001183 break;
1184
1185 case Decl::LinkageSpec: {
1186 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1187 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar488e9932008-08-16 00:56:44 +00001188 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001189 // FIXME: implement C++ linkage, C linkage works mostly by C
1190 // language reuse already.
1191 break;
1192 }
1193
1194 case Decl::FileScopeAsm: {
1195 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1196 std::string AsmString(AD->getAsmString()->getStrData(),
1197 AD->getAsmString()->getByteLength());
1198
1199 const std::string &S = getModule().getModuleInlineAsm();
1200 if (S.empty())
1201 getModule().setModuleInlineAsm(AsmString);
1202 else
1203 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1204 break;
1205 }
1206
1207 default:
1208 // Make sure we handled everything we should, every other kind is
1209 // a non-top-level decl. FIXME: Would be nice to have an
1210 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1211 // that easily.
1212 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1213 }
1214}