blob: d02812ac5d9ce5f8fa80dc6966b25f5cfac46f6d [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000021#include "clang/AST/DeclCXX.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000022#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000023#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/TargetInfo.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000025#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000026#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/Intrinsics.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000028#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30using namespace CodeGen;
31
32
Chris Lattner45e8cbd2007-11-28 05:34:05 +000033CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-12-02 01:40:18 +000034 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbarf77ac862008-08-11 21:35:06 +000035 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattnerfb97b032007-12-02 01:40:18 +000036 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000037 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Eli Friedman0c995092008-05-26 12:59:39 +000038 CFConstantStringClassRef(0) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000039
40 if (Features.ObjC1) {
Daniel Dunbarf77ac862008-08-11 21:35:06 +000041 if (Features.NeXTRuntime) {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000042 Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this)
Fariborz Jahanianee0af742009-01-21 22:04:16 +000043 : CreateMacObjCRuntime(*this);
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000044 } else {
45 Runtime = CreateGNUObjCRuntime(*this);
46 }
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000047 }
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000048
49 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek815c78f2008-08-05 18:50:11 +000050 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000051}
52
53CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000054 delete Runtime;
55 delete DebugInfo;
56}
57
58void CodeGenModule::Release() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000059 EmitStatics();
Daniel Dunbar219df662008-09-08 23:44:31 +000060 EmitAliases();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000061 if (Runtime)
62 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
63 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000064 EmitCtorList(GlobalCtors, "llvm.global_ctors");
65 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000066 EmitAnnotations();
Daniel Dunbarf1968f22008-10-01 00:49:24 +000067 BindRuntimeFunctions();
Chris Lattner2b94fe32008-03-01 08:45:05 +000068}
Reid Spencer5f016e22007-07-11 17:01:13 +000069
Daniel Dunbarf1968f22008-10-01 00:49:24 +000070void CodeGenModule::BindRuntimeFunctions() {
71 // Deal with protecting runtime function names.
72 for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
73 llvm::Function *Fn = RuntimeFunctions[i].first;
74 const std::string &Name = RuntimeFunctions[i].second;
75
Daniel Dunbar0293d542008-11-19 06:15:35 +000076 // Discard unused runtime functions.
77 if (Fn->use_empty()) {
78 Fn->eraseFromParent();
79 continue;
80 }
81
Daniel Dunbarf1968f22008-10-01 00:49:24 +000082 // See if there is a conflict against a function.
83 llvm::Function *Conflict = TheModule.getFunction(Name);
84 if (Conflict) {
85 // Decide which version to take. If the conflict is a definition
86 // we are forced to take that, otherwise assume the runtime
87 // knows best.
88 if (!Conflict->isDeclaration()) {
89 llvm::Value *Casted =
90 llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
91 Fn->replaceAllUsesWith(Casted);
92 Fn->eraseFromParent();
93 } else {
94 Fn->takeName(Conflict);
95 llvm::Value *Casted =
96 llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
97 Conflict->replaceAllUsesWith(Casted);
98 Conflict->eraseFromParent();
99 }
100 } else {
101 // FIXME: There still may be conflicts with aliases and
102 // variables.
103 Fn->setName(Name);
104 }
105 }
106}
107
Daniel Dunbar488e9932008-08-16 00:56:44 +0000108/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000109/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000110void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
111 bool OmitOnError) {
112 if (OmitOnError && getDiags().hasErrorOccurred())
113 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000114 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000115 "cannot codegen this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000116 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000117 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
118 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000119}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000120
Daniel Dunbar488e9932008-08-16 00:56:44 +0000121/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000122/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000123void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
124 bool OmitOnError) {
125 if (OmitOnError && getDiags().hasErrorOccurred())
126 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000127 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000128 "cannot codegen this %0 yet");
129 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000130 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000131}
132
Daniel Dunbar41071de2008-08-15 23:26:23 +0000133/// setGlobalVisibility - Set the visibility for the given LLVM
134/// GlobalValue according to the given clang AST visibility value.
135static void setGlobalVisibility(llvm::GlobalValue *GV,
136 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000137 switch (Vis) {
138 default: assert(0 && "Unknown visibility!");
139 case VisibilityAttr::DefaultVisibility:
140 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
141 break;
142 case VisibilityAttr::HiddenVisibility:
143 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
144 break;
145 case VisibilityAttr::ProtectedVisibility:
146 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
147 break;
148 }
149}
150
Chris Lattner6d397602008-03-14 17:18:18 +0000151/// AddGlobalCtor - Add a function to the list that will be called before
152/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000153void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000154 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000155 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000156}
157
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000158/// AddGlobalDtor - Add a function to the list that will be called
159/// when the module is unloaded.
160void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000161 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000162 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
163}
164
165void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
166 // Ctor function type is void()*.
167 llvm::FunctionType* CtorFTy =
168 llvm::FunctionType::get(llvm::Type::VoidTy,
169 std::vector<const llvm::Type*>(),
170 false);
171 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
172
173 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000174 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000175 llvm::StructType::get(llvm::Type::Int32Ty,
176 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000177
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000178 // Construct the constructor and destructor arrays.
179 std::vector<llvm::Constant*> Ctors;
180 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
181 std::vector<llvm::Constant*> S;
182 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
183 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
184 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000185 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000186
187 if (!Ctors.empty()) {
188 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
189 new llvm::GlobalVariable(AT, false,
190 llvm::GlobalValue::AppendingLinkage,
191 llvm::ConstantArray::get(AT, Ctors),
192 GlobalName,
193 &TheModule);
194 }
Chris Lattner6d397602008-03-14 17:18:18 +0000195}
196
Nate Begeman532485c2008-04-18 23:43:57 +0000197void CodeGenModule::EmitAnnotations() {
198 if (Annotations.empty())
199 return;
200
201 // Create a new global variable for the ConstantStruct in the Module.
202 llvm::Constant *Array =
203 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
204 Annotations.size()),
205 Annotations);
206 llvm::GlobalValue *gv =
207 new llvm::GlobalVariable(Array->getType(), false,
208 llvm::GlobalValue::AppendingLinkage, Array,
209 "llvm.global.annotations", &TheModule);
210 gv->setSection("llvm.metadata");
211}
212
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000213static void SetGlobalValueAttributes(const Decl *D,
214 bool IsInternal,
215 bool IsInline,
Daniel Dunbar219df662008-09-08 23:44:31 +0000216 llvm::GlobalValue *GV,
217 bool ForDefinition) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000218 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000219 // approximation of what we really want.
Daniel Dunbar219df662008-09-08 23:44:31 +0000220 if (!ForDefinition) {
221 // Only a few attributes are set on declarations.
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000222 if (D->getAttr<DLLImportAttr>()) {
223 // The dllimport attribute is overridden by a subsequent declaration as
224 // dllexport.
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000225 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000226 // dllimport attribute can be applied only to function decls, not to
227 // definitions.
228 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
229 if (!FD->getBody())
230 GV->setLinkage(llvm::Function::DLLImportLinkage);
231 } else
232 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000233 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000234 }
Daniel Dunbar219df662008-09-08 23:44:31 +0000235 } else {
236 if (IsInternal) {
237 GV->setLinkage(llvm::Function::InternalLinkage);
238 } else {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000239 if (D->getAttr<DLLExportAttr>()) {
240 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
241 // The dllexport attribute is ignored for undefined symbols.
242 if (FD->getBody())
243 GV->setLinkage(llvm::Function::DLLExportLinkage);
244 } else
245 GV->setLinkage(llvm::Function::DLLExportLinkage);
246 } else if (D->getAttr<WeakAttr>() || IsInline)
Daniel Dunbar219df662008-09-08 23:44:31 +0000247 GV->setLinkage(llvm::Function::WeakLinkage);
248 }
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000249 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000250
Daniel Dunbar49988882009-01-13 02:25:00 +0000251 // FIXME: Figure out the relative priority of the attribute,
252 // -fvisibility, and private_extern.
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000253 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000254 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000255 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000256
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000257 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbara735ad82008-08-06 00:03:29 +0000258 // Prefaced with special LLVM marker to indicate that the name
259 // should not be munged.
260 GV->setName("\01" + ALA->getLabel());
261 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000262}
263
Devang Patel761d7f72008-09-25 21:02:23 +0000264void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000265 const CGFunctionInfo &Info,
Daniel Dunbarb7688072008-09-10 00:41:16 +0000266 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000267 AttributeListType AttributeList;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000268 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000269
Devang Patel761d7f72008-09-25 21:02:23 +0000270 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
271 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000272
273 // Set the appropriate calling convention for the Function.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000274 if (D->getAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000275 F->setCallingConv(llvm::CallingConv::X86_FastCall);
276
277 if (D->getAttr<StdCallAttr>())
278 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000279}
280
281/// SetFunctionAttributesForDefinition - Set function attributes
282/// specific to a function definition.
Daniel Dunbar219df662008-09-08 23:44:31 +0000283void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
284 llvm::Function *F) {
285 if (isa<ObjCMethodDecl>(D)) {
286 SetGlobalValueAttributes(D, true, false, F, true);
287 } else {
288 const FunctionDecl *FD = cast<FunctionDecl>(D);
289 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
290 FD->isInline(), F, true);
291 }
292
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000293 if (!Features.Exceptions)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000294 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000295
296 if (D->getAttr<AlwaysInlineAttr>())
297 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000298}
299
300void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
301 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000302 SetFunctionAttributes(MD, CGFunctionInfo(MD, Context), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000303
Daniel Dunbar219df662008-09-08 23:44:31 +0000304 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000305}
306
307void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
308 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000309 SetFunctionAttributes(FD, CGFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000310
Daniel Dunbar219df662008-09-08 23:44:31 +0000311 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
312 FD->isInline(), F, false);
313}
314
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000315
Daniel Dunbar219df662008-09-08 23:44:31 +0000316void CodeGenModule::EmitAliases() {
317 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
318 const FunctionDecl *D = Aliases[i];
319 const AliasAttr *AA = D->getAttr<AliasAttr>();
320
321 // This is something of a hack, if the FunctionDecl got overridden
322 // then its attributes will be moved to the new declaration. In
323 // this case the current decl has no alias attribute, but we will
324 // eventually see it.
325 if (!AA)
326 continue;
327
328 const std::string& aliaseeName = AA->getAliasee();
329 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
330 if (!aliasee) {
331 // FIXME: This isn't unsupported, this is just an error, which
332 // sema should catch, but...
333 ErrorUnsupported(D, "alias referencing a missing function");
334 continue;
335 }
336
337 llvm::GlobalValue *GA =
338 new llvm::GlobalAlias(aliasee->getType(),
339 llvm::Function::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000340 D->getNameAsString(), aliasee, &getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000341
342 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
343 if (Entry) {
344 // If we created a dummy function for this then replace it.
345 GA->takeName(Entry);
346
347 llvm::Value *Casted =
348 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
349 Entry->replaceAllUsesWith(Casted);
350 Entry->eraseFromParent();
351
352 Entry = GA;
353 }
354
355 // Alias should never be internal or inline.
356 SetGlobalValueAttributes(D, false, false, GA, true);
357 }
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000358}
359
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000360void CodeGenModule::EmitStatics() {
361 // Emit code for each used static decl encountered. Since a previously unused
362 // static decl may become used during the generation of code for a static
363 // function, iterate until no changes are made.
364 bool Changed;
365 do {
366 Changed = false;
Anders Carlssonb723f752009-01-04 02:08:04 +0000367
368 for (std::list<const ValueDecl*>::iterator i = StaticDecls.begin(),
369 e = StaticDecls.end(); i != e; ) {
370 const ValueDecl *D = *i;
371
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000372 // Check if we have used a decl with the same name
373 // FIXME: The AST should have some sort of aggregate decls or
374 // global symbol map.
Daniel Dunbar219df662008-09-08 23:44:31 +0000375 // FIXME: This is missing some important cases. For example, we
376 // need to check for uses in an alias and in a constructor.
Anders Carlssonb723f752009-01-04 02:08:04 +0000377 if (!GlobalDeclMap.count(D->getIdentifier())) {
378 i++;
Daniel Dunbara735ad82008-08-06 00:03:29 +0000379 continue;
Anders Carlssonb723f752009-01-04 02:08:04 +0000380 }
381
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000382 // Emit the definition.
383 EmitGlobalDefinition(D);
384
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000385 // Erase the used decl from the list.
Anders Carlssonb723f752009-01-04 02:08:04 +0000386 i = StaticDecls.erase(i);
387
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000388 // Remember that we made a change.
389 Changed = true;
390 }
391 } while (Changed);
Reid Spencer5f016e22007-07-11 17:01:13 +0000392}
393
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000394/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
395/// annotation information for a given GlobalValue. The annotation struct is
396/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000397/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000398/// created from the AnnotateAttr's annotation. The third field is a constant
399/// string containing the name of the translation unit. The fourth field is
400/// the line number in the file of the annotated value declaration.
401///
402/// FIXME: this does not unique the annotation string constants, as llvm-gcc
403/// appears to.
404///
405llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
406 const AnnotateAttr *AA,
407 unsigned LineNo) {
408 llvm::Module *M = &getModule();
409
410 // get [N x i8] constants for the annotation string, and the filename string
411 // which are the 2nd and 3rd elements of the global annotation structure.
412 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
413 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
414 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
415 true);
416
417 // Get the two global values corresponding to the ConstantArrays we just
418 // created to hold the bytes of the strings.
419 llvm::GlobalValue *annoGV =
420 new llvm::GlobalVariable(anno->getType(), false,
421 llvm::GlobalValue::InternalLinkage, anno,
422 GV->getName() + ".str", M);
423 // translation unit name string, emitted into the llvm.metadata section.
424 llvm::GlobalValue *unitGV =
425 new llvm::GlobalVariable(unit->getType(), false,
426 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
427
428 // Create the ConstantStruct that is the global annotion.
429 llvm::Constant *Fields[4] = {
430 llvm::ConstantExpr::getBitCast(GV, SBP),
431 llvm::ConstantExpr::getBitCast(annoGV, SBP),
432 llvm::ConstantExpr::getBitCast(unitGV, SBP),
433 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
434 };
435 return llvm::ConstantStruct::get(Fields, 4, false);
436}
437
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000438void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
439 bool isDef, isStatic;
440
441 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000442 // Aliases are deferred until code for everything else has been
443 // emitted.
444 if (FD->getAttr<AliasAttr>()) {
445 assert(!FD->isThisDeclarationADefinition() &&
446 "Function alias cannot have a definition!");
447 Aliases.push_back(FD);
448 return;
449 }
450
451 isDef = FD->isThisDeclarationADefinition();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000452 isStatic = FD->getStorageClass() == FunctionDecl::Static;
453 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
454 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
455
Daniel Dunbar49988882009-01-13 02:25:00 +0000456 isDef = !((VD->getStorageClass() == VarDecl::Extern ||
457 VD->getStorageClass() == VarDecl::PrivateExtern) &&
458 VD->getInit() == 0);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000459 isStatic = VD->getStorageClass() == VarDecl::Static;
460 } else {
461 assert(0 && "Invalid argument to EmitGlobal");
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000462 return;
463 }
464
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000465 // Forward declarations are emitted lazily on first use.
466 if (!isDef)
Chris Lattner88a69ad2007-07-13 05:13:43 +0000467 return;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000468
469 // If the global is a static, defer code generation until later so
470 // we can easily omit unused statics.
471 if (isStatic) {
472 StaticDecls.push_back(Global);
473 return;
474 }
475
476 // Otherwise emit the definition.
477 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000478}
479
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000480void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
481 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
482 EmitGlobalFunctionDefinition(FD);
483 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
484 EmitGlobalVarDefinition(VD);
485 } else {
486 assert(0 && "Invalid argument to EmitGlobalDefinition()");
487 }
488}
489
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000490 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000491 assert(D->hasGlobalStorage() && "Not a global variable");
492
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000493 QualType ASTTy = D->getType();
494 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000495 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000496
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000497 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000498 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar49988882009-01-13 02:25:00 +0000499 if (!Entry) {
500 llvm::GlobalVariable *GV =
501 new llvm::GlobalVariable(Ty, false,
502 llvm::GlobalValue::ExternalLinkage,
503 0, D->getNameAsString(), &getModule(), 0,
504 ASTTy.getAddressSpace());
505 Entry = GV;
506
507 // Handle things which are present even on external declarations.
508
509 // FIXME: This code is overly simple and should be merged with
510 // other global handling.
511
512 GV->setConstant(D->getType().isConstant(Context));
513
514 if (D->getStorageClass() == VarDecl::PrivateExtern)
515 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
516 }
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000517
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000518 // Make sure the result is of the correct type.
519 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000520}
521
522void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000523 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000524 QualType ASTTy = D->getType();
525 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000526
Chris Lattner8f32f712007-07-14 00:23:28 +0000527 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000528 // This is a tentative definition; tentative definitions are
529 // implicitly initialized with { 0 }
530 const llvm::Type* InitTy;
531 if (ASTTy->isIncompleteArrayType()) {
532 // An incomplete array is normally [ TYPE x 0 ], but we need
533 // to fix it to [ TYPE x 1 ].
534 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
535 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
536 } else {
537 InitTy = VarTy;
538 }
539 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000540 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000541 Init = EmitConstantExpr(D->getInit());
Eli Friedman77ba7082008-05-30 19:50:47 +0000542 }
543 const llvm::Type* InitType = Init->getType();
544
Daniel Dunbar90db8822008-08-25 06:18:57 +0000545 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000546 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
547
Eli Friedman77ba7082008-05-30 19:50:47 +0000548 if (!GV) {
549 GV = new llvm::GlobalVariable(InitType, false,
550 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000551 0, D->getNameAsString(), &getModule(), 0,
Eli Friedman77ba7082008-05-30 19:50:47 +0000552 ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000553 } else if (GV->getType() !=
554 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000555 // We have a definition after a prototype with the wrong type.
556 // We must make a new GlobalVariable* and update everything that used OldGV
557 // (a declaration or tentative definition) with the new GlobalVariable*
558 // (which will be a definition).
559 //
560 // This happens if there is a prototype for a global (e.g. "extern int x[];")
561 // and then a definition of a different type (e.g. "int x[10];"). This also
562 // happens when an initializer has a different type from the type of the
563 // global (this happens with unions).
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000564 //
565 // FIXME: This also ends up happening if there's a definition followed by
566 // a tentative definition! (Although Sema rejects that construct
567 // at the moment.)
Eli Friedman77ba7082008-05-30 19:50:47 +0000568
569 // Save the old global
570 llvm::GlobalVariable *OldGV = GV;
571
572 // Make a new global with the correct type
573 GV = new llvm::GlobalVariable(InitType, false,
574 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000575 0, D->getNameAsString(), &getModule(), 0,
Eli Friedman77ba7082008-05-30 19:50:47 +0000576 ASTTy.getAddressSpace());
577 // Steal the name of the old global
578 GV->takeName(OldGV);
579
580 // Replace all uses of the old global with the new global
581 llvm::Constant *NewPtrForOldDecl =
582 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
583 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000584
585 // Erase the old global, since it is no longer used.
586 OldGV->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000587 }
Devang Patel8e53e722007-10-26 16:31:40 +0000588
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000589 Entry = GV;
Devang Patel8e53e722007-10-26 16:31:40 +0000590
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000591 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
592 SourceManager &SM = Context.getSourceManager();
593 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000594 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000595 }
596
Chris Lattner88a69ad2007-07-13 05:13:43 +0000597 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000598 GV->setConstant(D->getType().isConstant(Context));
Chris Lattnerddee4232008-03-03 03:28:21 +0000599
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000600 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
601 unsigned Align;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000602 if (const IncompleteArrayType* IAT =
603 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000604 Align = Context.getTypeAlign(IAT->getElementType());
605 else
606 Align = Context.getTypeAlign(D->getType());
Eli Friedman08d78022008-05-29 11:10:27 +0000607 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
608 Align = std::max(Align, AA->getAlignment());
609 }
610 GV->setAlignment(Align / 8);
611
Chris Lattnerddee4232008-03-03 03:28:21 +0000612 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000613 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000614 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000615
616 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
617 // Prefaced with special LLVM marker to indicate that the name
618 // should not be munged.
619 GV->setName("\01" + ALA->getLabel());
620 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000621
622 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000623 if (D->getStorageClass() == VarDecl::Static)
624 GV->setLinkage(llvm::Function::InternalLinkage);
625 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000626 GV->setLinkage(llvm::Function::DLLImportLinkage);
627 else if (D->getAttr<DLLExportAttr>())
628 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000629 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000630 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000631 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000632 // FIXME: This isn't right. This should handle common linkage and other
633 // stuff.
634 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000635 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000636 case VarDecl::Auto:
637 case VarDecl::Register:
638 assert(0 && "Can't have auto or register globals");
639 case VarDecl::None:
640 if (!D->getInit())
Eli Friedmana07b7642008-05-29 11:03:17 +0000641 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson98883e12008-12-03 05:51:23 +0000642 else
643 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000644 break;
645 case VarDecl::Extern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000646 // FIXME: common
647 break;
648
Chris Lattnerddee4232008-03-03 03:28:21 +0000649 case VarDecl::PrivateExtern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000650 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
651 // FIXME: common
Chris Lattnerddee4232008-03-03 03:28:21 +0000652 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000653 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000654 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000655
656 // Emit global variable debug information.
657 CGDebugInfo *DI = getDebugInfo();
658 if(DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000659 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000660 DI->EmitGlobalVariable(GV, D);
661 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000662}
Reid Spencer5f016e22007-07-11 17:01:13 +0000663
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000664llvm::GlobalValue *
665CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000666 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
667 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
668 llvm::Function::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000669 D->getNameAsString(),&getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000670 SetFunctionAttributes(D, F);
671 return F;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000672}
673
674llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000675 QualType ASTTy = D->getType();
676 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
677 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000678
679 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000680 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000681 if (!Entry)
682 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000683
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000684 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000685}
686
687void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar90db8822008-08-25 06:18:57 +0000688 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000689 if (!Entry) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000690 Entry = EmitForwardFunctionDefinition(D);
691 } else {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000692 // If the types mismatch then we have to rewrite the definition.
693 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
694 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000695 // Otherwise, we have a definition after a prototype with the wrong type.
696 // F is the Function* for the one with the wrong type, we must make a new
697 // Function* and update everything that used F (a declaration) with the new
698 // Function* (which will be a definition).
699 //
700 // This happens if there is a prototype for a function (e.g. "int f()") and
701 // then a definition of a different type (e.g. "int f(int x)"). Start by
702 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000703 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
704 NewFn->takeName(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000705
706 // Replace uses of F with the Function we will endow with a body.
707 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000708 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
709 Entry->replaceAllUsesWith(NewPtrForOldDecl);
710
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000711 // Ok, delete the old function now, which is dead.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000712 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar219df662008-09-08 23:44:31 +0000713 Entry->eraseFromParent();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000714
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000715 Entry = NewFn;
716 }
717 }
718
Daniel Dunbar219df662008-09-08 23:44:31 +0000719 llvm::Function *Fn = cast<llvm::Function>(Entry);
720 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000721
Daniel Dunbar219df662008-09-08 23:44:31 +0000722 SetFunctionAttributesForDefinition(D, Fn);
723
724 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
725 AddGlobalCtor(Fn, CA->getPriority());
726 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
727 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000728 }
729}
730
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000731llvm::Function *
732CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
733 const std::string &Name) {
734 llvm::Function *Fn = llvm::Function::Create(FTy,
735 llvm::Function::ExternalLinkage,
736 "", &TheModule);
737 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
738 return Fn;
739}
740
Chris Lattnerc5b88062008-02-06 05:08:19 +0000741void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
742 // Make sure that this type is translated.
743 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000744}
745
746
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000747/// getBuiltinLibFunction
748llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000749 if (BuiltinID > BuiltinFunctions.size())
750 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000751
Chris Lattner1426fec2007-12-13 00:38:03 +0000752 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
753 // a slot for it.
754 assert(BuiltinID && "Invalid Builtin ID");
755 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000756 if (FunctionSlot)
757 return FunctionSlot;
758
759 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
760
761 // Get the name, skip over the __builtin_ prefix.
762 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
763
764 // Get the type for the builtin.
765 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
766 const llvm::FunctionType *Ty =
767 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
768
769 // FIXME: This has a serious problem with code like this:
770 // void abs() {}
771 // ... __builtin_abs(x);
772 // The two versions of abs will collide. The fix is for the builtin to win,
773 // and for the existing one to be turned into a constantexpr cast of the
774 // builtin. In the case where the existing one is a static function, it
775 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000776 if (llvm::Function *Existing = getModule().getFunction(Name)) {
777 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
778 return FunctionSlot = Existing;
779 assert(Existing == 0 && "FIXME: Name collision");
780 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000781
782 // FIXME: param attributes for sext/zext etc.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000783 return FunctionSlot =
784 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
785 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000786}
787
Chris Lattner7acda7c2007-12-18 00:25:38 +0000788llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
789 unsigned NumTys) {
790 return llvm::Intrinsic::getDeclaration(&getModule(),
791 (llvm::Intrinsic::ID)IID, Tys, NumTys);
792}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000793
Reid Spencer5f016e22007-07-11 17:01:13 +0000794llvm::Function *CodeGenModule::getMemCpyFn() {
795 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000796 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
797 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000798}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000799
Eli Friedman0c995092008-05-26 12:59:39 +0000800llvm::Function *CodeGenModule::getMemMoveFn() {
801 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000802 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
803 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +0000804}
805
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000806llvm::Function *CodeGenModule::getMemSetFn() {
807 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000808 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
809 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000810}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000811
Anders Carlssone3daa762008-11-15 18:54:24 +0000812static void appendFieldAndPadding(CodeGenModule &CGM,
813 std::vector<llvm::Constant*>& Fields,
Douglas Gregor44b43212008-12-11 16:49:14 +0000814 FieldDecl *FieldD, FieldDecl *NextFieldD,
815 llvm::Constant* Field,
Anders Carlssone3daa762008-11-15 18:54:24 +0000816 RecordDecl* RD, const llvm::StructType *STy)
817{
818 // Append the field.
819 Fields.push_back(Field);
820
Douglas Gregor44b43212008-12-11 16:49:14 +0000821 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000822
823 int NextStructFieldNo;
Douglas Gregor44b43212008-12-11 16:49:14 +0000824 if (!NextFieldD) {
Anders Carlssone3daa762008-11-15 18:54:24 +0000825 NextStructFieldNo = STy->getNumElements();
826 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000827 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +0000828 }
829
830 // Append padding
831 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
832 llvm::Constant *C =
833 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
834
835 Fields.push_back(C);
836 }
837}
838
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000839// We still need to work out the details of handling UTF-16.
840// See: <rdr://2996215>
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000841llvm::Constant *CodeGenModule::
842GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000843 llvm::StringMapEntry<llvm::Constant *> &Entry =
844 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
845
846 if (Entry.getValue())
847 return Entry.getValue();
848
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000849 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
850 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +0000851
852 if (!CFConstantStringClassRef) {
853 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
854 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000855
856 // FIXME: This is fairly broken if
857 // __CFConstantStringClassReference is already defined, in that it
858 // will get renamed and the user will most likely see an opaque
859 // error message. This is a general issue with relying on
860 // particular names.
861 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +0000862 new llvm::GlobalVariable(Ty, false,
863 llvm::GlobalVariable::ExternalLinkage, 0,
864 "__CFConstantStringClassReference",
865 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000866
867 // Decay array -> ptr
868 CFConstantStringClassRef =
869 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000870 }
871
Anders Carlssone3daa762008-11-15 18:54:24 +0000872 QualType CFTy = getContext().getCFConstantStringType();
873 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000874
Anders Carlssone3daa762008-11-15 18:54:24 +0000875 const llvm::StructType *STy =
876 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
877
878 std::vector<llvm::Constant*> Fields;
Douglas Gregor44b43212008-12-11 16:49:14 +0000879 RecordDecl::field_iterator Field = CFRD->field_begin();
880
Anders Carlssonc9e20912007-08-21 00:21:21 +0000881 // Class pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +0000882 FieldDecl *CurField = *Field++;
883 FieldDecl *NextField = *Field++;
884 appendFieldAndPadding(*this, Fields, CurField, NextField,
885 CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000886
887 // Flags.
Douglas Gregor44b43212008-12-11 16:49:14 +0000888 CurField = NextField;
889 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000890 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor44b43212008-12-11 16:49:14 +0000891 appendFieldAndPadding(*this, Fields, CurField, NextField,
892 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000893
894 // String pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +0000895 CurField = NextField;
896 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000897 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000898 C = new llvm::GlobalVariable(C->getType(), true,
899 llvm::GlobalValue::InternalLinkage,
Anders Carlssone3daa762008-11-15 18:54:24 +0000900 C, ".str", &getModule());
Douglas Gregor44b43212008-12-11 16:49:14 +0000901 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlssone3daa762008-11-15 18:54:24 +0000902 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
903 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000904
905 // String length.
Douglas Gregor44b43212008-12-11 16:49:14 +0000906 CurField = NextField;
907 NextField = 0;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000908 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor44b43212008-12-11 16:49:14 +0000909 appendFieldAndPadding(*this, Fields, CurField, NextField,
910 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000911
912 // The struct.
Anders Carlssone3daa762008-11-15 18:54:24 +0000913 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000914 llvm::GlobalVariable *GV =
915 new llvm::GlobalVariable(C->getType(), true,
916 llvm::GlobalVariable::InternalLinkage,
917 C, "", &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000918
Anders Carlsson0c678292007-11-01 00:41:52 +0000919 GV->setSection("__DATA,__cfstring");
920 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000921
Anders Carlsson0c678292007-11-01 00:41:52 +0000922 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000923}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000924
Daniel Dunbar61432932008-08-13 23:20:05 +0000925/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +0000926/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +0000927std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar662174c82008-08-29 17:28:43 +0000928 if (E->isWide()) {
929 ErrorUnsupported(E, "wide string");
930 return "FIXME";
931 }
932
Daniel Dunbar1e049762008-08-10 20:25:57 +0000933 const char *StrData = E->getStrData();
934 unsigned Len = E->getByteLength();
935
936 const ConstantArrayType *CAT =
937 getContext().getAsConstantArrayType(E->getType());
938 assert(CAT && "String isn't pointer or array!");
939
940 // Resize the string to the right size
941 // FIXME: What about wchar_t strings?
942 std::string Str(StrData, StrData+Len);
943 uint64_t RealLen = CAT->getSize().getZExtValue();
944 Str.resize(RealLen, '\0');
945
946 return Str;
947}
948
Daniel Dunbar61432932008-08-13 23:20:05 +0000949/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
950/// constant array for the given string literal.
951llvm::Constant *
952CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
953 // FIXME: This can be more efficient.
954 return GetAddrOfConstantString(GetStringForStringLiteral(S));
955}
956
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000957/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000958static llvm::Constant *GenerateStringLiteral(const std::string &str,
959 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000960 CodeGenModule &CGM,
961 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +0000962 // Create Constant for this string literal. Don't add a '\0'.
963 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000964
965 // Create a global variable for this string
966 C = new llvm::GlobalVariable(C->getType(), constant,
967 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000968 C,
969 GlobalName ? GlobalName : ".str",
970 &CGM.getModule());
Daniel Dunbar61432932008-08-13 23:20:05 +0000971
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000972 return C;
973}
974
Daniel Dunbar61432932008-08-13 23:20:05 +0000975/// GetAddrOfConstantString - Returns a pointer to a character array
976/// containing the literal. This contents are exactly that of the
977/// given string, i.e. it will not be null terminated automatically;
978/// see GetAddrOfConstantCString. Note that whether the result is
979/// actually a pointer to an LLVM constant depends on
980/// Feature.WriteableStrings.
981///
982/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000983llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
984 const char *GlobalName) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000985 // Don't share any string literals if writable-strings is turned on.
986 if (Features.WritableStrings)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000987 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000988
989 llvm::StringMapEntry<llvm::Constant *> &Entry =
990 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
991
992 if (Entry.getValue())
993 return Entry.getValue();
994
995 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000996 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000997 Entry.setValue(C);
998 return C;
999}
Daniel Dunbar61432932008-08-13 23:20:05 +00001000
1001/// GetAddrOfConstantCString - Returns a pointer to a character
1002/// array containing the literal and a terminating '\-'
1003/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001004llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1005 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001006 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001007}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001008
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001009/// EmitObjCPropertyImplementations - Emit information for synthesized
1010/// properties for an implementation.
1011void CodeGenModule::EmitObjCPropertyImplementations(const
1012 ObjCImplementationDecl *D) {
1013 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1014 e = D->propimpl_end(); i != e; ++i) {
1015 ObjCPropertyImplDecl *PID = *i;
1016
1017 // Dynamic is just for type-checking.
1018 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1019 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1020
1021 // Determine which methods need to be implemented, some may have
1022 // been overridden. Note that ::isSynthesized is not the method
1023 // we want, that just indicates if the decl came from a
1024 // property. What we want to know is if the method is defined in
1025 // this implementation.
1026 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001027 CodeGenFunction(*this).GenerateObjCGetter(
1028 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001029 if (!PD->isReadOnly() &&
1030 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001031 CodeGenFunction(*this).GenerateObjCSetter(
1032 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001033 }
1034 }
1035}
1036
Daniel Dunbar41071de2008-08-15 23:26:23 +00001037/// EmitTopLevelDecl - Emit code for a single top level declaration.
1038void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1039 // If an error has occurred, stop code generation, but continue
1040 // parsing and semantic analysis (to ensure all warnings and errors
1041 // are emitted).
1042 if (Diags.hasErrorOccurred())
1043 return;
1044
1045 switch (D->getKind()) {
1046 case Decl::Function:
1047 case Decl::Var:
1048 EmitGlobal(cast<ValueDecl>(D));
1049 break;
1050
1051 case Decl::Namespace:
Daniel Dunbar662174c82008-08-29 17:28:43 +00001052 ErrorUnsupported(D, "namespace");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001053 break;
1054
1055 // Objective-C Decls
1056
1057 // Forward declarations, no (immediate) code generation.
1058 case Decl::ObjCClass:
1059 case Decl::ObjCCategory:
1060 case Decl::ObjCForwardProtocol:
1061 case Decl::ObjCInterface:
1062 break;
1063
1064 case Decl::ObjCProtocol:
1065 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1066 break;
1067
1068 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001069 // Categories have properties but don't support synthesize so we
1070 // can ignore them here.
1071
Daniel Dunbar41071de2008-08-15 23:26:23 +00001072 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1073 break;
1074
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001075 case Decl::ObjCImplementation: {
1076 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1077 EmitObjCPropertyImplementations(OMD);
1078 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001079 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001080 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001081 case Decl::ObjCMethod: {
1082 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1083 // If this is not a prototype, emit the body.
1084 if (OMD->getBody())
1085 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1086 break;
1087 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001088 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001089 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001090 break;
1091
1092 case Decl::LinkageSpec: {
1093 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1094 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar488e9932008-08-16 00:56:44 +00001095 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001096 // FIXME: implement C++ linkage, C linkage works mostly by C
1097 // language reuse already.
1098 break;
1099 }
1100
1101 case Decl::FileScopeAsm: {
1102 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1103 std::string AsmString(AD->getAsmString()->getStrData(),
1104 AD->getAsmString()->getByteLength());
1105
1106 const std::string &S = getModule().getModuleInlineAsm();
1107 if (S.empty())
1108 getModule().setModuleInlineAsm(AsmString);
1109 else
1110 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1111 break;
1112 }
1113
1114 default:
1115 // Make sure we handled everything we should, every other kind is
1116 // a non-top-level decl. FIXME: Would be nice to have an
1117 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1118 // that easily.
1119 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1120 }
1121}
1122