blob: ecfd8c98c32c544340814648c3b812cc2f851f88 [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
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 Lattner753d2592008-03-14 17:18:18 +0000179/// AddGlobalCtor - Add a function to the list that will be called before
180/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000181void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000182 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000183 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000184}
185
Daniel Dunbardd2e9ca2008-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 Dunbar3a80fc02009-01-13 02:25:00 +0000189 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-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 Lattnera18c12e2008-03-19 05:24:56 +0000202 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000203 llvm::StructType::get(llvm::Type::Int32Ty,
204 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000205
Daniel Dunbardd2e9ca2008-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 Lattner753d2592008-03-14 17:18:18 +0000213 }
Daniel Dunbardd2e9ca2008-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 Lattner753d2592008-03-14 17:18:18 +0000223}
224
Nate Begeman52da5c72008-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 Dunbara8f02052008-09-08 21:33:45 +0000241static void SetGlobalValueAttributes(const Decl *D,
242 bool IsInternal,
243 bool IsInline,
Daniel Dunbar566a6502008-09-08 23:44:31 +0000244 llvm::GlobalValue *GV,
245 bool ForDefinition) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000246 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopes78534382008-06-08 15:45:52 +0000247 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000248 if (!ForDefinition) {
249 // Only a few attributes are set on declarations.
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000250 if (D->getAttr<DLLImportAttr>()) {
251 // The dllimport attribute is overridden by a subsequent declaration as
252 // dllexport.
Sebastian Redle299eb42009-01-05 20:53:53 +0000253 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikovb27a8702008-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 Redle299eb42009-01-05 20:53:53 +0000261 }
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000262 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000263 } else {
264 if (IsInternal) {
265 GV->setLinkage(llvm::Function::InternalLinkage);
266 } else {
Anton Korobeynikovb27a8702008-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 Dunbar566a6502008-09-08 23:44:31 +0000275 GV->setLinkage(llvm::Function::WeakLinkage);
276 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000277 }
Nuno Lopes78534382008-06-08 15:45:52 +0000278
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000279 // FIXME: Figure out the relative priority of the attribute,
280 // -fvisibility, and private_extern.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000281 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000282 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000283 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000284
Daniel Dunbara8f02052008-09-08 21:33:45 +0000285 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbarced89142008-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 Dunbar97509722009-02-12 17:28:23 +0000290
291 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
292 GV->setSection(SA->getName());
Nuno Lopes78534382008-06-08 15:45:52 +0000293}
294
Devang Patela85a9ef2008-09-25 21:02:23 +0000295void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000296 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000297 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000298 AttributeListType AttributeList;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000299 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000300
Devang Patela85a9ef2008-09-25 21:02:23 +0000301 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
302 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000303
304 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000305 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000306 F->setCallingConv(llvm::CallingConv::X86_FastCall);
307
308 if (D->getAttr<StdCallAttr>())
309 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000310}
311
312/// SetFunctionAttributesForDefinition - Set function attributes
313/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000314void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
315 llvm::Function *F) {
316 if (isa<ObjCMethodDecl>(D)) {
317 SetGlobalValueAttributes(D, true, false, F, true);
318 } else {
319 const FunctionDecl *FD = cast<FunctionDecl>(D);
320 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
321 FD->isInline(), F, true);
322 }
323
Daniel Dunbarf2787002008-09-04 23:41:35 +0000324 if (!Features.Exceptions)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000325 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000326
327 if (D->getAttr<AlwaysInlineAttr>())
328 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000329}
330
331void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
332 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000333 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000334
Daniel Dunbar566a6502008-09-08 23:44:31 +0000335 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000336}
337
338void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
339 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000340 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000341
Daniel Dunbar566a6502008-09-08 23:44:31 +0000342 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
343 FD->isInline(), F, false);
344}
345
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000346
Daniel Dunbar566a6502008-09-08 23:44:31 +0000347void CodeGenModule::EmitAliases() {
348 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
349 const FunctionDecl *D = Aliases[i];
350 const AliasAttr *AA = D->getAttr<AliasAttr>();
351
352 // This is something of a hack, if the FunctionDecl got overridden
353 // then its attributes will be moved to the new declaration. In
354 // this case the current decl has no alias attribute, but we will
355 // eventually see it.
356 if (!AA)
357 continue;
358
359 const std::string& aliaseeName = AA->getAliasee();
360 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
361 if (!aliasee) {
362 // FIXME: This isn't unsupported, this is just an error, which
363 // sema should catch, but...
364 ErrorUnsupported(D, "alias referencing a missing function");
365 continue;
366 }
367
368 llvm::GlobalValue *GA =
369 new llvm::GlobalAlias(aliasee->getType(),
370 llvm::Function::ExternalLinkage,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000371 getMangledName(D)->getName(), aliasee,
372 &getModule());
Daniel Dunbar566a6502008-09-08 23:44:31 +0000373
Douglas Gregor3556bc72009-02-13 00:10:09 +0000374 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar566a6502008-09-08 23:44:31 +0000375 if (Entry) {
376 // If we created a dummy function for this then replace it.
377 GA->takeName(Entry);
378
379 llvm::Value *Casted =
380 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
381 Entry->replaceAllUsesWith(Casted);
382 Entry->eraseFromParent();
383
384 Entry = GA;
385 }
386
387 // Alias should never be internal or inline.
388 SetGlobalValueAttributes(D, false, false, GA, true);
389 }
Eli Friedman9be42212008-06-01 15:54:49 +0000390}
391
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000392void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
393 assert(!GV->isDeclaration() &&
394 "Only globals with definition can force usage.");
395 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
396 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
397}
398
399void CodeGenModule::EmitLLVMUsed() {
400 // Don't create llvm.used if there is no need.
401 if (LLVMUsed.empty())
402 return;
403
404 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
405 LLVMUsed.size());
406 llvm::GlobalVariable *GV =
407 new llvm::GlobalVariable(ATy, false,
408 llvm::GlobalValue::AppendingLinkage,
409 llvm::ConstantArray::get(ATy, LLVMUsed),
410 "llvm.used", &getModule());
411
412 GV->setSection("llvm.metadata");
413}
414
415void CodeGenModule::EmitDeferred() {
416 // Emit code for any deferred decl which was used. Since a
417 // previously unused static decl may become used during the
418 // generation of code for a static function, iterate until no
419 // changes are made.
Nate Begemanad320b62008-04-20 06:29:50 +0000420 bool Changed;
421 do {
422 Changed = false;
Anders Carlsson2e427d52009-01-04 02:08:04 +0000423
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000424 for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(),
425 e = DeferredDecls.end(); i != e; ) {
Anders Carlsson2e427d52009-01-04 02:08:04 +0000426 const ValueDecl *D = *i;
427
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000428 // Check if we have used a decl with the same name
429 // FIXME: The AST should have some sort of aggregate decls or
430 // global symbol map.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000431 // FIXME: This is missing some important cases. For example, we
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000432 // need to check for uses in an alias.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000433 if (!GlobalDeclMap.count(getMangledName(D))) {
Anders Carlsson2e427d52009-01-04 02:08:04 +0000434 i++;
Daniel Dunbarced89142008-08-06 00:03:29 +0000435 continue;
Anders Carlsson2e427d52009-01-04 02:08:04 +0000436 }
437
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000438 // Emit the definition.
439 EmitGlobalDefinition(D);
440
Nate Begemanad320b62008-04-20 06:29:50 +0000441 // Erase the used decl from the list.
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000442 i = DeferredDecls.erase(i);
Anders Carlsson2e427d52009-01-04 02:08:04 +0000443
Nate Begemanad320b62008-04-20 06:29:50 +0000444 // Remember that we made a change.
445 Changed = true;
446 }
447 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000448}
449
Nate Begeman8a704172008-04-19 04:17:09 +0000450/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
451/// annotation information for a given GlobalValue. The annotation struct is
452/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000453/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000454/// created from the AnnotateAttr's annotation. The third field is a constant
455/// string containing the name of the translation unit. The fourth field is
456/// the line number in the file of the annotated value declaration.
457///
458/// FIXME: this does not unique the annotation string constants, as llvm-gcc
459/// appears to.
460///
461llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
462 const AnnotateAttr *AA,
463 unsigned LineNo) {
464 llvm::Module *M = &getModule();
465
466 // get [N x i8] constants for the annotation string, and the filename string
467 // which are the 2nd and 3rd elements of the global annotation structure.
468 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
469 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
470 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
471 true);
472
473 // Get the two global values corresponding to the ConstantArrays we just
474 // created to hold the bytes of the strings.
475 llvm::GlobalValue *annoGV =
476 new llvm::GlobalVariable(anno->getType(), false,
477 llvm::GlobalValue::InternalLinkage, anno,
478 GV->getName() + ".str", M);
479 // translation unit name string, emitted into the llvm.metadata section.
480 llvm::GlobalValue *unitGV =
481 new llvm::GlobalVariable(unit->getType(), false,
482 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
483
484 // Create the ConstantStruct that is the global annotion.
485 llvm::Constant *Fields[4] = {
486 llvm::ConstantExpr::getBitCast(GV, SBP),
487 llvm::ConstantExpr::getBitCast(annoGV, SBP),
488 llvm::ConstantExpr::getBitCast(unitGV, SBP),
489 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
490 };
491 return llvm::ConstantStruct::get(Fields, 4, false);
492}
493
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000494bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
495 // Never defer when EmitAllDecls is specified.
496 if (Features.EmitAllDecls)
497 return false;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000498
499 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000500 // Constructors and destructors should never be deferred.
501 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
502 return false;
503
504 if (FD->getStorageClass() != FunctionDecl::Static)
505 return false;
506 } else {
507 const VarDecl *VD = cast<VarDecl>(Global);
508 assert(VD->isFileVarDecl() && "Invalid decl.");
509
510 if (VD->getStorageClass() != VarDecl::Static)
511 return false;
512 }
513
514 return true;
515}
516
517void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
518 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000519 // Aliases are deferred until code for everything else has been
520 // emitted.
521 if (FD->getAttr<AliasAttr>()) {
522 assert(!FD->isThisDeclarationADefinition() &&
523 "Function alias cannot have a definition!");
524 Aliases.push_back(FD);
525 return;
526 }
527
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000528 // Forward declarations are emitted lazily on first use.
529 if (!FD->isThisDeclarationADefinition())
530 return;
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000531 } else {
532 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000533 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
534
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000535 // Forward declarations are emitted lazily on first use.
536 if ((VD->getStorageClass() == VarDecl::Extern ||
537 VD->getStorageClass() == VarDecl::PrivateExtern) &&
538 VD->getInit() == 0)
539 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000540 }
541
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000542 // Defer code generation when possible.
543 if (MayDeferGeneration(Global)) {
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000544 DeferredDecls.push_back(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000545 return;
546 }
547
548 // Otherwise emit the definition.
549 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000550}
551
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000552void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
553 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
554 EmitGlobalFunctionDefinition(FD);
555 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
556 EmitGlobalVarDefinition(VD);
557 } else {
558 assert(0 && "Invalid argument to EmitGlobalDefinition()");
559 }
560}
561
Daniel Dunbar2188c532008-07-30 16:32:24 +0000562 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000563 assert(D->hasGlobalStorage() && "Not a global variable");
564
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000565 QualType ASTTy = D->getType();
566 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000567 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000568
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000569 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000570 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000571 if (!Entry) {
572 llvm::GlobalVariable *GV =
573 new llvm::GlobalVariable(Ty, false,
574 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000575 0, getMangledName(D)->getName(), &getModule(),
576 0, ASTTy.getAddressSpace());
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000577 Entry = GV;
578
579 // Handle things which are present even on external declarations.
580
581 // FIXME: This code is overly simple and should be merged with
582 // other global handling.
583
584 GV->setConstant(D->getType().isConstant(Context));
585
586 if (D->getStorageClass() == VarDecl::PrivateExtern)
587 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
588 }
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000589
Daniel Dunbar2188c532008-07-30 16:32:24 +0000590 // Make sure the result is of the correct type.
591 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000592}
593
594void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000595 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000596 QualType ASTTy = D->getType();
597 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000598
Chris Lattner4b009652007-07-25 00:24:17 +0000599 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000600 // This is a tentative definition; tentative definitions are
601 // implicitly initialized with { 0 }
602 const llvm::Type* InitTy;
603 if (ASTTy->isIncompleteArrayType()) {
604 // An incomplete array is normally [ TYPE x 0 ], but we need
605 // to fix it to [ TYPE x 1 ].
606 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
607 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
608 } else {
609 InitTy = VarTy;
610 }
611 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000612 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000613 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000614 }
615 const llvm::Type* InitType = Init->getType();
616
Douglas Gregor3556bc72009-02-13 00:10:09 +0000617 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000618 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
619
Eli Friedman43a0ce82008-05-30 19:50:47 +0000620 if (!GV) {
621 GV = new llvm::GlobalVariable(InitType, false,
622 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000623 0, getMangledName(D)->getName(),
624 &getModule(), 0, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000625 } else if (GV->getType() !=
626 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000627 // We have a definition after a prototype with the wrong type.
628 // We must make a new GlobalVariable* and update everything that used OldGV
629 // (a declaration or tentative definition) with the new GlobalVariable*
630 // (which will be a definition).
631 //
632 // This happens if there is a prototype for a global (e.g. "extern int x[];")
633 // and then a definition of a different type (e.g. "int x[10];"). This also
634 // happens when an initializer has a different type from the type of the
635 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000636 //
637 // FIXME: This also ends up happening if there's a definition followed by
638 // a tentative definition! (Although Sema rejects that construct
639 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000640
641 // Save the old global
642 llvm::GlobalVariable *OldGV = GV;
643
644 // Make a new global with the correct type
645 GV = new llvm::GlobalVariable(InitType, false,
646 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000647 0, getMangledName(D)->getName(),
648 &getModule(), 0, ASTTy.getAddressSpace());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000649 // Steal the name of the old global
650 GV->takeName(OldGV);
651
652 // Replace all uses of the old global with the new global
653 llvm::Constant *NewPtrForOldDecl =
654 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
655 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000656
657 // Erase the old global, since it is no longer used.
658 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000659 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000660
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000661 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000662
Nate Begeman8a704172008-04-19 04:17:09 +0000663 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
664 SourceManager &SM = Context.getSourceManager();
665 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner18c8dc02009-01-16 07:36:28 +0000666 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8a704172008-04-19 04:17:09 +0000667 }
668
Chris Lattner4b009652007-07-25 00:24:17 +0000669 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000670 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner402b3372008-03-03 03:28:21 +0000671
Eli Friedman7008e9a2008-05-30 20:39:54 +0000672 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
673 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000674 if (const IncompleteArrayType* IAT =
675 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000676 Align = Context.getTypeAlign(IAT->getElementType());
677 else
678 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000679 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
680 Align = std::max(Align, AA->getAlignment());
681 }
682 GV->setAlignment(Align / 8);
683
Chris Lattner402b3372008-03-03 03:28:21 +0000684 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000685 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000686 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000687
688 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
689 // Prefaced with special LLVM marker to indicate that the name
690 // should not be munged.
691 GV->setName("\01" + ALA->getLabel());
692 }
Chris Lattner4b009652007-07-25 00:24:17 +0000693
694 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000695 if (D->getStorageClass() == VarDecl::Static)
696 GV->setLinkage(llvm::Function::InternalLinkage);
697 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000698 GV->setLinkage(llvm::Function::DLLImportLinkage);
699 else if (D->getAttr<DLLExportAttr>())
700 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000701 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000702 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000703 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000704 // FIXME: This isn't right. This should handle common linkage and other
705 // stuff.
706 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000707 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000708 case VarDecl::Auto:
709 case VarDecl::Register:
710 assert(0 && "Can't have auto or register globals");
711 case VarDecl::None:
712 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000713 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson689bba82008-12-03 05:51:23 +0000714 else
715 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000716 break;
717 case VarDecl::Extern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000718 // FIXME: common
719 break;
720
Chris Lattner402b3372008-03-03 03:28:21 +0000721 case VarDecl::PrivateExtern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000722 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
723 // FIXME: common
Chris Lattner402b3372008-03-03 03:28:21 +0000724 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000725 }
Chris Lattner4b009652007-07-25 00:24:17 +0000726 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000727
Daniel Dunbar97509722009-02-12 17:28:23 +0000728 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
729 GV->setSection(SA->getName());
730
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000731 // Emit global variable debug information.
732 CGDebugInfo *DI = getDebugInfo();
733 if(DI) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000734 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000735 DI->EmitGlobalVariable(GV, D);
736 }
Chris Lattner4b009652007-07-25 00:24:17 +0000737}
738
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000739llvm::GlobalValue *
740CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000741 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
742 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
743 llvm::Function::ExternalLinkage,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000744 getMangledName(D)->getName(),
745 &getModule());
Daniel Dunbar566a6502008-09-08 23:44:31 +0000746 SetFunctionAttributes(D, F);
747 return F;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000748}
749
750llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000751 QualType ASTTy = D->getType();
752 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
753 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000754
755 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000756 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000757 if (!Entry)
758 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000759
Daniel Dunbar2188c532008-07-30 16:32:24 +0000760 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000761}
762
763void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Douglas Gregor3556bc72009-02-13 00:10:09 +0000764 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000765 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000766 Entry = EmitForwardFunctionDefinition(D);
767 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000768 // If the types mismatch then we have to rewrite the definition.
769 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
770 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000771 // Otherwise, we have a definition after a prototype with the wrong type.
772 // F is the Function* for the one with the wrong type, we must make a new
773 // Function* and update everything that used F (a declaration) with the new
774 // Function* (which will be a definition).
775 //
776 // This happens if there is a prototype for a function (e.g. "int f()") and
777 // then a definition of a different type (e.g. "int f(int x)"). Start by
778 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000779 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
780 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000781
782 // Replace uses of F with the Function we will endow with a body.
783 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000784 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
785 Entry->replaceAllUsesWith(NewPtrForOldDecl);
786
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000787 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000788 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar566a6502008-09-08 23:44:31 +0000789 Entry->eraseFromParent();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000790
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000791 Entry = NewFn;
792 }
793 }
794
Daniel Dunbar566a6502008-09-08 23:44:31 +0000795 llvm::Function *Fn = cast<llvm::Function>(Entry);
796 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000797
Daniel Dunbar566a6502008-09-08 23:44:31 +0000798 SetFunctionAttributesForDefinition(D, Fn);
799
800 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
801 AddGlobalCtor(Fn, CA->getPriority());
802 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
803 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000804 }
805}
806
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000807llvm::Function *
808CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
809 const std::string &Name) {
810 llvm::Function *Fn = llvm::Function::Create(FTy,
811 llvm::Function::ExternalLinkage,
812 "", &TheModule);
813 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
814 return Fn;
815}
816
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000817void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
818 // Make sure that this type is translated.
819 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000820}
821
822
Chris Lattnerab862cc2007-08-31 04:31:45 +0000823/// getBuiltinLibFunction
824llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000825 if (BuiltinID > BuiltinFunctions.size())
826 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000827
Chris Lattner9f2d6892007-12-13 00:38:03 +0000828 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
829 // a slot for it.
830 assert(BuiltinID && "Invalid Builtin ID");
831 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000832 if (FunctionSlot)
833 return FunctionSlot;
834
835 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
836
837 // Get the name, skip over the __builtin_ prefix.
838 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
839
840 // Get the type for the builtin.
841 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
842 const llvm::FunctionType *Ty =
843 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
844
845 // FIXME: This has a serious problem with code like this:
846 // void abs() {}
847 // ... __builtin_abs(x);
848 // The two versions of abs will collide. The fix is for the builtin to win,
849 // and for the existing one to be turned into a constantexpr cast of the
850 // builtin. In the case where the existing one is a static function, it
851 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000852 if (llvm::Function *Existing = getModule().getFunction(Name)) {
853 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
854 return FunctionSlot = Existing;
855 assert(Existing == 0 && "FIXME: Name collision");
856 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000857
858 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000859 return FunctionSlot =
860 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
861 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000862}
863
Chris Lattner4b23f942007-12-18 00:25:38 +0000864llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
865 unsigned NumTys) {
866 return llvm::Intrinsic::getDeclaration(&getModule(),
867 (llvm::Intrinsic::ID)IID, Tys, NumTys);
868}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000869
Chris Lattner4b009652007-07-25 00:24:17 +0000870llvm::Function *CodeGenModule::getMemCpyFn() {
871 if (MemCpyFn) return MemCpyFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000872 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
873 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000874}
Anders Carlsson36a04872007-08-21 00:21:21 +0000875
Eli Friedman8f08a252008-05-26 12:59:39 +0000876llvm::Function *CodeGenModule::getMemMoveFn() {
877 if (MemMoveFn) return MemMoveFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000878 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
879 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman8f08a252008-05-26 12:59:39 +0000880}
881
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000882llvm::Function *CodeGenModule::getMemSetFn() {
883 if (MemSetFn) return MemSetFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000884 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
885 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000886}
Chris Lattner4b23f942007-12-18 00:25:38 +0000887
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000888static void appendFieldAndPadding(CodeGenModule &CGM,
889 std::vector<llvm::Constant*>& Fields,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000890 FieldDecl *FieldD, FieldDecl *NextFieldD,
891 llvm::Constant* Field,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000892 RecordDecl* RD, const llvm::StructType *STy)
893{
894 // Append the field.
895 Fields.push_back(Field);
896
Douglas Gregor8acb7272008-12-11 16:49:14 +0000897 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000898
899 int NextStructFieldNo;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000900 if (!NextFieldD) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000901 NextStructFieldNo = STy->getNumElements();
902 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000903 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000904 }
905
906 // Append padding
907 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
908 llvm::Constant *C =
909 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
910
911 Fields.push_back(C);
912 }
913}
914
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000915// We still need to work out the details of handling UTF-16.
916// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +0000917llvm::Constant *CodeGenModule::
918GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000919 llvm::StringMapEntry<llvm::Constant *> &Entry =
920 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
921
922 if (Entry.getValue())
923 return Entry.getValue();
924
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000925 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
926 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +0000927
928 if (!CFConstantStringClassRef) {
929 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
930 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000931
932 // FIXME: This is fairly broken if
933 // __CFConstantStringClassReference is already defined, in that it
934 // will get renamed and the user will most likely see an opaque
935 // error message. This is a general issue with relying on
936 // particular names.
937 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +0000938 new llvm::GlobalVariable(Ty, false,
939 llvm::GlobalVariable::ExternalLinkage, 0,
940 "__CFConstantStringClassReference",
941 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000942
943 // Decay array -> ptr
944 CFConstantStringClassRef =
945 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +0000946 }
947
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000948 QualType CFTy = getContext().getCFConstantStringType();
949 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000950
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000951 const llvm::StructType *STy =
952 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
953
954 std::vector<llvm::Constant*> Fields;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000955 RecordDecl::field_iterator Field = CFRD->field_begin();
956
Anders Carlsson36a04872007-08-21 00:21:21 +0000957 // Class pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000958 FieldDecl *CurField = *Field++;
959 FieldDecl *NextField = *Field++;
960 appendFieldAndPadding(*this, Fields, CurField, NextField,
961 CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000962
963 // Flags.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000964 CurField = NextField;
965 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000966 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000967 appendFieldAndPadding(*this, Fields, CurField, NextField,
968 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000969
970 // String pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000971 CurField = NextField;
972 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000973 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +0000974 C = new llvm::GlobalVariable(C->getType(), true,
975 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000976 C, ".str", &getModule());
Douglas Gregor8acb7272008-12-11 16:49:14 +0000977 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000978 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
979 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000980
981 // String length.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000982 CurField = NextField;
983 NextField = 0;
Anders Carlsson36a04872007-08-21 00:21:21 +0000984 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000985 appendFieldAndPadding(*this, Fields, CurField, NextField,
986 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000987
988 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000989 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000990 llvm::GlobalVariable *GV =
991 new llvm::GlobalVariable(C->getType(), true,
992 llvm::GlobalVariable::InternalLinkage,
993 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000994
Anders Carlsson9be009e2007-11-01 00:41:52 +0000995 GV->setSection("__DATA,__cfstring");
996 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000997
Anders Carlsson9be009e2007-11-01 00:41:52 +0000998 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000999}
Chris Lattnerdb6be562007-11-28 05:34:05 +00001000
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001001/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001002/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001003std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar952f4732008-08-29 17:28:43 +00001004 if (E->isWide()) {
1005 ErrorUnsupported(E, "wide string");
1006 return "FIXME";
1007 }
1008
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001009 const char *StrData = E->getStrData();
1010 unsigned Len = E->getByteLength();
1011
1012 const ConstantArrayType *CAT =
1013 getContext().getAsConstantArrayType(E->getType());
1014 assert(CAT && "String isn't pointer or array!");
1015
1016 // Resize the string to the right size
1017 // FIXME: What about wchar_t strings?
1018 std::string Str(StrData, StrData+Len);
1019 uint64_t RealLen = CAT->getSize().getZExtValue();
1020 Str.resize(RealLen, '\0');
1021
1022 return Str;
1023}
1024
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001025/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1026/// constant array for the given string literal.
1027llvm::Constant *
1028CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1029 // FIXME: This can be more efficient.
1030 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1031}
1032
Chris Lattnera6dcce32008-02-11 00:02:17 +00001033/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +00001034static llvm::Constant *GenerateStringLiteral(const std::string &str,
1035 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001036 CodeGenModule &CGM,
1037 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001038 // Create Constant for this string literal. Don't add a '\0'.
1039 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001040
1041 // Create a global variable for this string
1042 C = new llvm::GlobalVariable(C->getType(), constant,
1043 llvm::GlobalValue::InternalLinkage,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001044 C,
1045 GlobalName ? GlobalName : ".str",
1046 &CGM.getModule());
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001047
Chris Lattnerdb6be562007-11-28 05:34:05 +00001048 return C;
1049}
1050
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001051/// GetAddrOfConstantString - Returns a pointer to a character array
1052/// containing the literal. This contents are exactly that of the
1053/// given string, i.e. it will not be null terminated automatically;
1054/// see GetAddrOfConstantCString. Note that whether the result is
1055/// actually a pointer to an LLVM constant depends on
1056/// Feature.WriteableStrings.
1057///
1058/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001059llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1060 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +00001061 // Don't share any string literals if writable-strings is turned on.
1062 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001063 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001064
1065 llvm::StringMapEntry<llvm::Constant *> &Entry =
1066 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1067
1068 if (Entry.getValue())
1069 return Entry.getValue();
1070
1071 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001072 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001073 Entry.setValue(C);
1074 return C;
1075}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001076
1077/// GetAddrOfConstantCString - Returns a pointer to a character
1078/// array containing the literal and a terminating '\-'
1079/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001080llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1081 const char *GlobalName){
Chris Lattnerb2176012008-12-09 19:10:54 +00001082 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001083}
Daniel Dunbar27250d32008-08-15 23:26:23 +00001084
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001085/// EmitObjCPropertyImplementations - Emit information for synthesized
1086/// properties for an implementation.
1087void CodeGenModule::EmitObjCPropertyImplementations(const
1088 ObjCImplementationDecl *D) {
1089 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1090 e = D->propimpl_end(); i != e; ++i) {
1091 ObjCPropertyImplDecl *PID = *i;
1092
1093 // Dynamic is just for type-checking.
1094 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1095 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1096
1097 // Determine which methods need to be implemented, some may have
1098 // been overridden. Note that ::isSynthesized is not the method
1099 // we want, that just indicates if the decl came from a
1100 // property. What we want to know is if the method is defined in
1101 // this implementation.
1102 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001103 CodeGenFunction(*this).GenerateObjCGetter(
1104 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001105 if (!PD->isReadOnly() &&
1106 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001107 CodeGenFunction(*this).GenerateObjCSetter(
1108 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001109 }
1110 }
1111}
1112
Daniel Dunbar27250d32008-08-15 23:26:23 +00001113/// EmitTopLevelDecl - Emit code for a single top level declaration.
1114void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1115 // If an error has occurred, stop code generation, but continue
1116 // parsing and semantic analysis (to ensure all warnings and errors
1117 // are emitted).
1118 if (Diags.hasErrorOccurred())
1119 return;
1120
1121 switch (D->getKind()) {
1122 case Decl::Function:
1123 case Decl::Var:
1124 EmitGlobal(cast<ValueDecl>(D));
1125 break;
1126
1127 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001128 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001129 break;
1130
1131 // Objective-C Decls
1132
1133 // Forward declarations, no (immediate) code generation.
1134 case Decl::ObjCClass:
1135 case Decl::ObjCCategory:
1136 case Decl::ObjCForwardProtocol:
1137 case Decl::ObjCInterface:
1138 break;
1139
1140 case Decl::ObjCProtocol:
1141 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1142 break;
1143
1144 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001145 // Categories have properties but don't support synthesize so we
1146 // can ignore them here.
1147
Daniel Dunbar27250d32008-08-15 23:26:23 +00001148 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1149 break;
1150
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001151 case Decl::ObjCImplementation: {
1152 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1153 EmitObjCPropertyImplementations(OMD);
1154 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001155 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001156 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001157 case Decl::ObjCMethod: {
1158 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1159 // If this is not a prototype, emit the body.
1160 if (OMD->getBody())
1161 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1162 break;
1163 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001164 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian2ac4cd32009-01-08 01:10:55 +00001165 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001166 break;
1167
1168 case Decl::LinkageSpec: {
1169 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1170 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001171 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001172 // FIXME: implement C++ linkage, C linkage works mostly by C
1173 // language reuse already.
1174 break;
1175 }
1176
1177 case Decl::FileScopeAsm: {
1178 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1179 std::string AsmString(AD->getAsmString()->getStrData(),
1180 AD->getAsmString()->getByteLength());
1181
1182 const std::string &S = getModule().getModuleInlineAsm();
1183 if (S.empty())
1184 getModule().setModuleInlineAsm(AsmString);
1185 else
1186 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1187 break;
1188 }
1189
1190 default:
1191 // Make sure we handled everything we should, every other kind is
1192 // a non-top-level decl. FIXME: Would be nice to have an
1193 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1194 // that easily.
1195 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1196 }
1197}