blob: f0aa8b7d141d61cc1a85a6089b02644e87c43177 [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) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000042 Runtime = CreateMacObjCRuntime(*this);
43 } else {
44 Runtime = CreateGNUObjCRuntime(*this);
45 }
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000046 }
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000047
48 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek815c78f2008-08-05 18:50:11 +000049 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000050}
51
52CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000053 delete Runtime;
54 delete DebugInfo;
55}
56
57void CodeGenModule::Release() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000058 EmitStatics();
Daniel Dunbar219df662008-09-08 23:44:31 +000059 EmitAliases();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000060 if (Runtime)
61 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
62 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000063 EmitCtorList(GlobalCtors, "llvm.global_ctors");
64 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000065 EmitAnnotations();
Daniel Dunbarf1968f22008-10-01 00:49:24 +000066 BindRuntimeFunctions();
Chris Lattner2b94fe32008-03-01 08:45:05 +000067}
Reid Spencer5f016e22007-07-11 17:01:13 +000068
Daniel Dunbarf1968f22008-10-01 00:49:24 +000069void CodeGenModule::BindRuntimeFunctions() {
70 // Deal with protecting runtime function names.
71 for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
72 llvm::Function *Fn = RuntimeFunctions[i].first;
73 const std::string &Name = RuntimeFunctions[i].second;
74
Daniel Dunbar0293d542008-11-19 06:15:35 +000075 // Discard unused runtime functions.
76 if (Fn->use_empty()) {
77 Fn->eraseFromParent();
78 continue;
79 }
80
Daniel Dunbarf1968f22008-10-01 00:49:24 +000081 // See if there is a conflict against a function.
82 llvm::Function *Conflict = TheModule.getFunction(Name);
83 if (Conflict) {
84 // Decide which version to take. If the conflict is a definition
85 // we are forced to take that, otherwise assume the runtime
86 // knows best.
87 if (!Conflict->isDeclaration()) {
88 llvm::Value *Casted =
89 llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
90 Fn->replaceAllUsesWith(Casted);
91 Fn->eraseFromParent();
92 } else {
93 Fn->takeName(Conflict);
94 llvm::Value *Casted =
95 llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
96 Conflict->replaceAllUsesWith(Casted);
97 Conflict->eraseFromParent();
98 }
99 } else {
100 // FIXME: There still may be conflicts with aliases and
101 // variables.
102 Fn->setName(Name);
103 }
104 }
105}
106
Daniel Dunbar488e9932008-08-16 00:56:44 +0000107/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000108/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000109void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
110 bool OmitOnError) {
111 if (OmitOnError && getDiags().hasErrorOccurred())
112 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000113 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000114 "cannot codegen this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000115 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000116 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
117 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000118}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000119
Daniel Dunbar488e9932008-08-16 00:56:44 +0000120/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000121/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000122void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
123 bool OmitOnError) {
124 if (OmitOnError && getDiags().hasErrorOccurred())
125 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +0000126 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000127 "cannot codegen this %0 yet");
128 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000129 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000130}
131
Daniel Dunbar41071de2008-08-15 23:26:23 +0000132/// setGlobalVisibility - Set the visibility for the given LLVM
133/// GlobalValue according to the given clang AST visibility value.
134static void setGlobalVisibility(llvm::GlobalValue *GV,
135 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000136 switch (Vis) {
137 default: assert(0 && "Unknown visibility!");
138 case VisibilityAttr::DefaultVisibility:
139 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
140 break;
141 case VisibilityAttr::HiddenVisibility:
142 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
143 break;
144 case VisibilityAttr::ProtectedVisibility:
145 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
146 break;
147 }
148}
149
Chris Lattner6d397602008-03-14 17:18:18 +0000150/// AddGlobalCtor - Add a function to the list that will be called before
151/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000152void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner6d397602008-03-14 17:18:18 +0000153 // TODO: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000154 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000155}
156
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000157/// AddGlobalDtor - Add a function to the list that will be called
158/// when the module is unloaded.
159void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
160 // TODO: Type coercion of void()* types.
161 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
162}
163
164void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
165 // Ctor function type is void()*.
166 llvm::FunctionType* CtorFTy =
167 llvm::FunctionType::get(llvm::Type::VoidTy,
168 std::vector<const llvm::Type*>(),
169 false);
170 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
171
172 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000173 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000174 llvm::StructType::get(llvm::Type::Int32Ty,
175 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000176
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000177 // Construct the constructor and destructor arrays.
178 std::vector<llvm::Constant*> Ctors;
179 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
180 std::vector<llvm::Constant*> S;
181 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
182 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
183 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000184 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000185
186 if (!Ctors.empty()) {
187 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
188 new llvm::GlobalVariable(AT, false,
189 llvm::GlobalValue::AppendingLinkage,
190 llvm::ConstantArray::get(AT, Ctors),
191 GlobalName,
192 &TheModule);
193 }
Chris Lattner6d397602008-03-14 17:18:18 +0000194}
195
Nate Begeman532485c2008-04-18 23:43:57 +0000196void CodeGenModule::EmitAnnotations() {
197 if (Annotations.empty())
198 return;
199
200 // Create a new global variable for the ConstantStruct in the Module.
201 llvm::Constant *Array =
202 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
203 Annotations.size()),
204 Annotations);
205 llvm::GlobalValue *gv =
206 new llvm::GlobalVariable(Array->getType(), false,
207 llvm::GlobalValue::AppendingLinkage, Array,
208 "llvm.global.annotations", &TheModule);
209 gv->setSection("llvm.metadata");
210}
211
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000212static void SetGlobalValueAttributes(const Decl *D,
213 bool IsInternal,
214 bool IsInline,
Daniel Dunbar219df662008-09-08 23:44:31 +0000215 llvm::GlobalValue *GV,
216 bool ForDefinition) {
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000217 // TODO: Set up linkage and many other things. Note, this is a simple
218 // approximation of what we really want.
Daniel Dunbar219df662008-09-08 23:44:31 +0000219 if (!ForDefinition) {
220 // Only a few attributes are set on declarations.
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000221 if (D->getAttr<DLLImportAttr>())
222 GV->setLinkage(llvm::Function::DLLImportLinkage);
Daniel Dunbar219df662008-09-08 23:44:31 +0000223 } else {
224 if (IsInternal) {
225 GV->setLinkage(llvm::Function::InternalLinkage);
226 } else {
227 if (D->getAttr<DLLImportAttr>())
228 GV->setLinkage(llvm::Function::DLLImportLinkage);
229 else if (D->getAttr<DLLExportAttr>())
230 GV->setLinkage(llvm::Function::DLLExportLinkage);
231 else if (D->getAttr<WeakAttr>() || IsInline)
232 GV->setLinkage(llvm::Function::WeakLinkage);
233 }
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000234 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000235
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000236 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000237 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000238 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000239
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000240 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbara735ad82008-08-06 00:03:29 +0000241 // Prefaced with special LLVM marker to indicate that the name
242 // should not be munged.
243 GV->setName("\01" + ALA->getLabel());
244 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000245}
246
Devang Patel761d7f72008-09-25 21:02:23 +0000247void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000248 const CGFunctionInfo &Info,
Daniel Dunbarb7688072008-09-10 00:41:16 +0000249 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000250 AttributeListType AttributeList;
251 ConstructAttributeList(D, Info.argtypes_begin(), Info.argtypes_end(),
252 AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000253
Devang Patel761d7f72008-09-25 21:02:23 +0000254 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
255 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000256
257 // Set the appropriate calling convention for the Function.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000258 if (D->getAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000259 F->setCallingConv(llvm::CallingConv::X86_FastCall);
260
261 if (D->getAttr<StdCallAttr>())
262 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000263}
264
265/// SetFunctionAttributesForDefinition - Set function attributes
266/// specific to a function definition.
Daniel Dunbar219df662008-09-08 23:44:31 +0000267void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
268 llvm::Function *F) {
269 if (isa<ObjCMethodDecl>(D)) {
270 SetGlobalValueAttributes(D, true, false, F, true);
271 } else {
272 const FunctionDecl *FD = cast<FunctionDecl>(D);
273 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
274 FD->isInline(), F, true);
275 }
276
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000277 if (!Features.Exceptions)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000278 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000279
280 if (D->getAttr<AlwaysInlineAttr>())
281 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000282}
283
284void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
285 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000286 SetFunctionAttributes(MD, CGFunctionInfo(MD, Context), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000287
Daniel Dunbar219df662008-09-08 23:44:31 +0000288 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000289}
290
291void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
292 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000293 SetFunctionAttributes(FD, CGFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000294
Daniel Dunbar219df662008-09-08 23:44:31 +0000295 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
296 FD->isInline(), F, false);
297}
298
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000299
Daniel Dunbar219df662008-09-08 23:44:31 +0000300void CodeGenModule::EmitAliases() {
301 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
302 const FunctionDecl *D = Aliases[i];
303 const AliasAttr *AA = D->getAttr<AliasAttr>();
304
305 // This is something of a hack, if the FunctionDecl got overridden
306 // then its attributes will be moved to the new declaration. In
307 // this case the current decl has no alias attribute, but we will
308 // eventually see it.
309 if (!AA)
310 continue;
311
312 const std::string& aliaseeName = AA->getAliasee();
313 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
314 if (!aliasee) {
315 // FIXME: This isn't unsupported, this is just an error, which
316 // sema should catch, but...
317 ErrorUnsupported(D, "alias referencing a missing function");
318 continue;
319 }
320
321 llvm::GlobalValue *GA =
322 new llvm::GlobalAlias(aliasee->getType(),
323 llvm::Function::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000324 D->getNameAsString(), aliasee, &getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000325
326 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
327 if (Entry) {
328 // If we created a dummy function for this then replace it.
329 GA->takeName(Entry);
330
331 llvm::Value *Casted =
332 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
333 Entry->replaceAllUsesWith(Casted);
334 Entry->eraseFromParent();
335
336 Entry = GA;
337 }
338
339 // Alias should never be internal or inline.
340 SetGlobalValueAttributes(D, false, false, GA, true);
341 }
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000342}
343
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000344void CodeGenModule::EmitStatics() {
345 // Emit code for each used static decl encountered. Since a previously unused
346 // static decl may become used during the generation of code for a static
347 // function, iterate until no changes are made.
348 bool Changed;
349 do {
350 Changed = false;
351 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000352 const ValueDecl *D = StaticDecls[i];
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000353
354 // Check if we have used a decl with the same name
355 // FIXME: The AST should have some sort of aggregate decls or
356 // global symbol map.
Daniel Dunbar219df662008-09-08 23:44:31 +0000357 // FIXME: This is missing some important cases. For example, we
358 // need to check for uses in an alias and in a constructor.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000359 if (!GlobalDeclMap.count(D->getIdentifier()))
Daniel Dunbara735ad82008-08-06 00:03:29 +0000360 continue;
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000361
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000362 // Emit the definition.
363 EmitGlobalDefinition(D);
364
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000365 // Erase the used decl from the list.
366 StaticDecls[i] = StaticDecls.back();
367 StaticDecls.pop_back();
368 --i;
369 --e;
370
371 // Remember that we made a change.
372 Changed = true;
373 }
374 } while (Changed);
Reid Spencer5f016e22007-07-11 17:01:13 +0000375}
376
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000377/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
378/// annotation information for a given GlobalValue. The annotation struct is
379/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000380/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000381/// created from the AnnotateAttr's annotation. The third field is a constant
382/// string containing the name of the translation unit. The fourth field is
383/// the line number in the file of the annotated value declaration.
384///
385/// FIXME: this does not unique the annotation string constants, as llvm-gcc
386/// appears to.
387///
388llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
389 const AnnotateAttr *AA,
390 unsigned LineNo) {
391 llvm::Module *M = &getModule();
392
393 // get [N x i8] constants for the annotation string, and the filename string
394 // which are the 2nd and 3rd elements of the global annotation structure.
395 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
396 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
397 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
398 true);
399
400 // Get the two global values corresponding to the ConstantArrays we just
401 // created to hold the bytes of the strings.
402 llvm::GlobalValue *annoGV =
403 new llvm::GlobalVariable(anno->getType(), false,
404 llvm::GlobalValue::InternalLinkage, anno,
405 GV->getName() + ".str", M);
406 // translation unit name string, emitted into the llvm.metadata section.
407 llvm::GlobalValue *unitGV =
408 new llvm::GlobalVariable(unit->getType(), false,
409 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
410
411 // Create the ConstantStruct that is the global annotion.
412 llvm::Constant *Fields[4] = {
413 llvm::ConstantExpr::getBitCast(GV, SBP),
414 llvm::ConstantExpr::getBitCast(annoGV, SBP),
415 llvm::ConstantExpr::getBitCast(unitGV, SBP),
416 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
417 };
418 return llvm::ConstantStruct::get(Fields, 4, false);
419}
420
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000421void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
422 bool isDef, isStatic;
423
424 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000425 // Aliases are deferred until code for everything else has been
426 // emitted.
427 if (FD->getAttr<AliasAttr>()) {
428 assert(!FD->isThisDeclarationADefinition() &&
429 "Function alias cannot have a definition!");
430 Aliases.push_back(FD);
431 return;
432 }
433
434 isDef = FD->isThisDeclarationADefinition();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000435 isStatic = FD->getStorageClass() == FunctionDecl::Static;
436 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
437 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
438
439 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
440 isStatic = VD->getStorageClass() == VarDecl::Static;
441 } else {
442 assert(0 && "Invalid argument to EmitGlobal");
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000443 return;
444 }
445
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000446 // Forward declarations are emitted lazily on first use.
447 if (!isDef)
Chris Lattner88a69ad2007-07-13 05:13:43 +0000448 return;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000449
450 // If the global is a static, defer code generation until later so
451 // we can easily omit unused statics.
452 if (isStatic) {
453 StaticDecls.push_back(Global);
454 return;
455 }
456
457 // Otherwise emit the definition.
458 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000459}
460
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000461void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
462 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
463 EmitGlobalFunctionDefinition(FD);
464 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
465 EmitGlobalVarDefinition(VD);
466 } else {
467 assert(0 && "Invalid argument to EmitGlobalDefinition()");
468 }
469}
470
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000471 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000472 assert(D->hasGlobalStorage() && "Not a global variable");
473
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000474 QualType ASTTy = D->getType();
475 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000476 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000477
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000478 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000479 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000480 if (!Entry)
481 Entry = new llvm::GlobalVariable(Ty, false,
482 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000483 0, D->getNameAsString(), &getModule(), 0,
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000484 ASTTy.getAddressSpace());
485
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000486 // Make sure the result is of the correct type.
487 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000488}
489
490void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000491 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000492 QualType ASTTy = D->getType();
493 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000494
Chris Lattner8f32f712007-07-14 00:23:28 +0000495 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000496 // This is a tentative definition; tentative definitions are
497 // implicitly initialized with { 0 }
498 const llvm::Type* InitTy;
499 if (ASTTy->isIncompleteArrayType()) {
500 // An incomplete array is normally [ TYPE x 0 ], but we need
501 // to fix it to [ TYPE x 1 ].
502 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
503 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
504 } else {
505 InitTy = VarTy;
506 }
507 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000508 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000509 Init = EmitConstantExpr(D->getInit());
Eli Friedman77ba7082008-05-30 19:50:47 +0000510 }
511 const llvm::Type* InitType = Init->getType();
512
Daniel Dunbar90db8822008-08-25 06:18:57 +0000513 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000514 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
515
Eli Friedman77ba7082008-05-30 19:50:47 +0000516 if (!GV) {
517 GV = new llvm::GlobalVariable(InitType, false,
518 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000519 0, D->getNameAsString(), &getModule(), 0,
Eli Friedman77ba7082008-05-30 19:50:47 +0000520 ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000521 } else if (GV->getType() !=
522 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000523 // We have a definition after a prototype with the wrong type.
524 // We must make a new GlobalVariable* and update everything that used OldGV
525 // (a declaration or tentative definition) with the new GlobalVariable*
526 // (which will be a definition).
527 //
528 // This happens if there is a prototype for a global (e.g. "extern int x[];")
529 // and then a definition of a different type (e.g. "int x[10];"). This also
530 // happens when an initializer has a different type from the type of the
531 // global (this happens with unions).
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000532 //
533 // FIXME: This also ends up happening if there's a definition followed by
534 // a tentative definition! (Although Sema rejects that construct
535 // at the moment.)
Eli Friedman77ba7082008-05-30 19:50:47 +0000536
537 // Save the old global
538 llvm::GlobalVariable *OldGV = GV;
539
540 // Make a new global with the correct type
541 GV = new llvm::GlobalVariable(InitType, false,
542 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000543 0, D->getNameAsString(), &getModule(), 0,
Eli Friedman77ba7082008-05-30 19:50:47 +0000544 ASTTy.getAddressSpace());
545 // Steal the name of the old global
546 GV->takeName(OldGV);
547
548 // Replace all uses of the old global with the new global
549 llvm::Constant *NewPtrForOldDecl =
550 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
551 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000552
553 // Erase the old global, since it is no longer used.
554 OldGV->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000555 }
Devang Patel8e53e722007-10-26 16:31:40 +0000556
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000557 Entry = GV;
Devang Patel8e53e722007-10-26 16:31:40 +0000558
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000559 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
560 SourceManager &SM = Context.getSourceManager();
561 AddAnnotation(EmitAnnotateAttr(GV, AA,
562 SM.getLogicalLineNumber(D->getLocation())));
563 }
564
Chris Lattner88a69ad2007-07-13 05:13:43 +0000565 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000566 GV->setConstant(D->getType().isConstant(Context));
Chris Lattnerddee4232008-03-03 03:28:21 +0000567
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000568 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
569 unsigned Align;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000570 if (const IncompleteArrayType* IAT =
571 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000572 Align = Context.getTypeAlign(IAT->getElementType());
573 else
574 Align = Context.getTypeAlign(D->getType());
Eli Friedman08d78022008-05-29 11:10:27 +0000575 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
576 Align = std::max(Align, AA->getAlignment());
577 }
578 GV->setAlignment(Align / 8);
579
Chris Lattnerddee4232008-03-03 03:28:21 +0000580 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000581 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000582 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000583
584 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
585 // Prefaced with special LLVM marker to indicate that the name
586 // should not be munged.
587 GV->setName("\01" + ALA->getLabel());
588 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000589
590 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000591 if (D->getStorageClass() == VarDecl::Static)
592 GV->setLinkage(llvm::Function::InternalLinkage);
593 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000594 GV->setLinkage(llvm::Function::DLLImportLinkage);
595 else if (D->getAttr<DLLExportAttr>())
596 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000597 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000598 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000599 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000600 // FIXME: This isn't right. This should handle common linkage and other
601 // stuff.
602 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000603 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000604 case VarDecl::Auto:
605 case VarDecl::Register:
606 assert(0 && "Can't have auto or register globals");
607 case VarDecl::None:
608 if (!D->getInit())
Eli Friedmana07b7642008-05-29 11:03:17 +0000609 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000610 break;
611 case VarDecl::Extern:
612 case VarDecl::PrivateExtern:
613 // todo: common
614 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000615 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000616 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000617
618 // Emit global variable debug information.
619 CGDebugInfo *DI = getDebugInfo();
620 if(DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000621 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000622 DI->EmitGlobalVariable(GV, D);
623 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000624}
Reid Spencer5f016e22007-07-11 17:01:13 +0000625
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000626llvm::GlobalValue *
627CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar219df662008-09-08 23:44:31 +0000628 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
629 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
630 llvm::Function::ExternalLinkage,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000631 D->getNameAsString(),&getModule());
Daniel Dunbar219df662008-09-08 23:44:31 +0000632 SetFunctionAttributes(D, F);
633 return F;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000634}
635
636llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000637 QualType ASTTy = D->getType();
638 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
639 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000640
641 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000642 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000643 if (!Entry)
644 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000645
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000646 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000647}
648
649void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar90db8822008-08-25 06:18:57 +0000650 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000651 if (!Entry) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000652 Entry = EmitForwardFunctionDefinition(D);
653 } else {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000654 // If the types mismatch then we have to rewrite the definition.
655 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
656 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000657 // Otherwise, we have a definition after a prototype with the wrong type.
658 // F is the Function* for the one with the wrong type, we must make a new
659 // Function* and update everything that used F (a declaration) with the new
660 // Function* (which will be a definition).
661 //
662 // This happens if there is a prototype for a function (e.g. "int f()") and
663 // then a definition of a different type (e.g. "int f(int x)"). Start by
664 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000665 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
666 NewFn->takeName(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000667
668 // Replace uses of F with the Function we will endow with a body.
669 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000670 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
671 Entry->replaceAllUsesWith(NewPtrForOldDecl);
672
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000673 // Ok, delete the old function now, which is dead.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000674 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar219df662008-09-08 23:44:31 +0000675 Entry->eraseFromParent();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000676
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000677 Entry = NewFn;
678 }
679 }
680
Daniel Dunbar219df662008-09-08 23:44:31 +0000681 llvm::Function *Fn = cast<llvm::Function>(Entry);
682 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000683
Daniel Dunbar219df662008-09-08 23:44:31 +0000684 SetFunctionAttributesForDefinition(D, Fn);
685
686 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
687 AddGlobalCtor(Fn, CA->getPriority());
688 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
689 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000690 }
691}
692
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000693llvm::Function *
694CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
695 const std::string &Name) {
696 llvm::Function *Fn = llvm::Function::Create(FTy,
697 llvm::Function::ExternalLinkage,
698 "", &TheModule);
699 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
700 return Fn;
701}
702
Chris Lattnerc5b88062008-02-06 05:08:19 +0000703void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
704 // Make sure that this type is translated.
705 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000706}
707
708
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000709/// getBuiltinLibFunction
710llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000711 if (BuiltinID > BuiltinFunctions.size())
712 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000713
Chris Lattner1426fec2007-12-13 00:38:03 +0000714 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
715 // a slot for it.
716 assert(BuiltinID && "Invalid Builtin ID");
717 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000718 if (FunctionSlot)
719 return FunctionSlot;
720
721 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
722
723 // Get the name, skip over the __builtin_ prefix.
724 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
725
726 // Get the type for the builtin.
727 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
728 const llvm::FunctionType *Ty =
729 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
730
731 // FIXME: This has a serious problem with code like this:
732 // void abs() {}
733 // ... __builtin_abs(x);
734 // The two versions of abs will collide. The fix is for the builtin to win,
735 // and for the existing one to be turned into a constantexpr cast of the
736 // builtin. In the case where the existing one is a static function, it
737 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000738 if (llvm::Function *Existing = getModule().getFunction(Name)) {
739 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
740 return FunctionSlot = Existing;
741 assert(Existing == 0 && "FIXME: Name collision");
742 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000743
744 // FIXME: param attributes for sext/zext etc.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000745 return FunctionSlot =
746 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
747 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000748}
749
Chris Lattner7acda7c2007-12-18 00:25:38 +0000750llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
751 unsigned NumTys) {
752 return llvm::Intrinsic::getDeclaration(&getModule(),
753 (llvm::Intrinsic::ID)IID, Tys, NumTys);
754}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000755
Reid Spencer5f016e22007-07-11 17:01:13 +0000756llvm::Function *CodeGenModule::getMemCpyFn() {
757 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000758 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
759 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000760}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000761
Eli Friedman0c995092008-05-26 12:59:39 +0000762llvm::Function *CodeGenModule::getMemMoveFn() {
763 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000764 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
765 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +0000766}
767
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000768llvm::Function *CodeGenModule::getMemSetFn() {
769 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +0000770 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
771 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000772}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000773
Anders Carlssone3daa762008-11-15 18:54:24 +0000774static void appendFieldAndPadding(CodeGenModule &CGM,
775 std::vector<llvm::Constant*>& Fields,
776 int FieldNo, llvm::Constant* Field,
777 RecordDecl* RD, const llvm::StructType *STy)
778{
779 // Append the field.
780 Fields.push_back(Field);
781
782 int StructFieldNo =
783 CGM.getTypes().getLLVMFieldNo(RD->getMember(FieldNo));
784
785 int NextStructFieldNo;
786 if (FieldNo + 1 == RD->getNumMembers()) {
787 NextStructFieldNo = STy->getNumElements();
788 } else {
789 NextStructFieldNo =
790 CGM.getTypes().getLLVMFieldNo(RD->getMember(FieldNo + 1));
791 }
792
793 // Append padding
794 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
795 llvm::Constant *C =
796 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
797
798 Fields.push_back(C);
799 }
800}
801
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000802// We still need to work out the details of handling UTF-16.
803// See: <rdr://2996215>
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000804llvm::Constant *CodeGenModule::
805GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000806 llvm::StringMapEntry<llvm::Constant *> &Entry =
807 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
808
809 if (Entry.getValue())
810 return Entry.getValue();
811
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000812 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
813 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +0000814
815 if (!CFConstantStringClassRef) {
816 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
817 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000818
819 // FIXME: This is fairly broken if
820 // __CFConstantStringClassReference is already defined, in that it
821 // will get renamed and the user will most likely see an opaque
822 // error message. This is a general issue with relying on
823 // particular names.
824 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +0000825 new llvm::GlobalVariable(Ty, false,
826 llvm::GlobalVariable::ExternalLinkage, 0,
827 "__CFConstantStringClassReference",
828 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000829
830 // Decay array -> ptr
831 CFConstantStringClassRef =
832 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000833 }
834
Anders Carlssone3daa762008-11-15 18:54:24 +0000835 QualType CFTy = getContext().getCFConstantStringType();
836 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000837
Anders Carlssone3daa762008-11-15 18:54:24 +0000838 const llvm::StructType *STy =
839 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
840
841 std::vector<llvm::Constant*> Fields;
842
843
Anders Carlssonc9e20912007-08-21 00:21:21 +0000844 // Class pointer.
Anders Carlssone3daa762008-11-15 18:54:24 +0000845 appendFieldAndPadding(*this, Fields, 0, CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000846
847 // Flags.
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000848 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Anders Carlssone3daa762008-11-15 18:54:24 +0000849 appendFieldAndPadding(*this, Fields, 1, llvm::ConstantInt::get(Ty, 0x07C8),
850 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000851
852 // String pointer.
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000853 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000854 C = new llvm::GlobalVariable(C->getType(), true,
855 llvm::GlobalValue::InternalLinkage,
Anders Carlssone3daa762008-11-15 18:54:24 +0000856 C, ".str", &getModule());
857 appendFieldAndPadding(*this, Fields, 2,
858 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
859 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000860
861 // String length.
862 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlssone3daa762008-11-15 18:54:24 +0000863 appendFieldAndPadding(*this, Fields, 3, llvm::ConstantInt::get(Ty, str.length()),
864 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000865
866 // The struct.
Anders Carlssone3daa762008-11-15 18:54:24 +0000867 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000868 llvm::GlobalVariable *GV =
869 new llvm::GlobalVariable(C->getType(), true,
870 llvm::GlobalVariable::InternalLinkage,
871 C, "", &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000872
Anders Carlsson0c678292007-11-01 00:41:52 +0000873 GV->setSection("__DATA,__cfstring");
874 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000875
Anders Carlsson0c678292007-11-01 00:41:52 +0000876 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000877}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000878
Daniel Dunbar61432932008-08-13 23:20:05 +0000879/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +0000880/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +0000881std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar662174c82008-08-29 17:28:43 +0000882 if (E->isWide()) {
883 ErrorUnsupported(E, "wide string");
884 return "FIXME";
885 }
886
Daniel Dunbar1e049762008-08-10 20:25:57 +0000887 const char *StrData = E->getStrData();
888 unsigned Len = E->getByteLength();
889
890 const ConstantArrayType *CAT =
891 getContext().getAsConstantArrayType(E->getType());
892 assert(CAT && "String isn't pointer or array!");
893
894 // Resize the string to the right size
895 // FIXME: What about wchar_t strings?
896 std::string Str(StrData, StrData+Len);
897 uint64_t RealLen = CAT->getSize().getZExtValue();
898 Str.resize(RealLen, '\0');
899
900 return Str;
901}
902
Daniel Dunbar61432932008-08-13 23:20:05 +0000903/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
904/// constant array for the given string literal.
905llvm::Constant *
906CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
907 // FIXME: This can be more efficient.
908 return GetAddrOfConstantString(GetStringForStringLiteral(S));
909}
910
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000911/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000912static llvm::Constant *GenerateStringLiteral(const std::string &str,
913 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000914 CodeGenModule &CGM,
915 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +0000916 // Create Constant for this string literal. Don't add a '\0'.
917 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000918
919 // Create a global variable for this string
920 C = new llvm::GlobalVariable(C->getType(), constant,
921 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000922 C,
923 GlobalName ? GlobalName : ".str",
924 &CGM.getModule());
Daniel Dunbar61432932008-08-13 23:20:05 +0000925
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000926 return C;
927}
928
Daniel Dunbar61432932008-08-13 23:20:05 +0000929/// GetAddrOfConstantString - Returns a pointer to a character array
930/// containing the literal. This contents are exactly that of the
931/// given string, i.e. it will not be null terminated automatically;
932/// see GetAddrOfConstantCString. Note that whether the result is
933/// actually a pointer to an LLVM constant depends on
934/// Feature.WriteableStrings.
935///
936/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000937llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
938 const char *GlobalName) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000939 // Don't share any string literals if writable-strings is turned on.
940 if (Features.WritableStrings)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000941 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000942
943 llvm::StringMapEntry<llvm::Constant *> &Entry =
944 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
945
946 if (Entry.getValue())
947 return Entry.getValue();
948
949 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000950 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000951 Entry.setValue(C);
952 return C;
953}
Daniel Dunbar61432932008-08-13 23:20:05 +0000954
955/// GetAddrOfConstantCString - Returns a pointer to a character
956/// array containing the literal and a terminating '\-'
957/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +0000958llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
959 const char *GlobalName){
960 return GetAddrOfConstantString(str + "\0", GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +0000961}
Daniel Dunbar41071de2008-08-15 23:26:23 +0000962
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000963/// EmitObjCPropertyImplementations - Emit information for synthesized
964/// properties for an implementation.
965void CodeGenModule::EmitObjCPropertyImplementations(const
966 ObjCImplementationDecl *D) {
967 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
968 e = D->propimpl_end(); i != e; ++i) {
969 ObjCPropertyImplDecl *PID = *i;
970
971 // Dynamic is just for type-checking.
972 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
973 ObjCPropertyDecl *PD = PID->getPropertyDecl();
974
975 // Determine which methods need to be implemented, some may have
976 // been overridden. Note that ::isSynthesized is not the method
977 // we want, that just indicates if the decl came from a
978 // property. What we want to know is if the method is defined in
979 // this implementation.
980 if (!D->getInstanceMethod(PD->getGetterName()))
981 CodeGenFunction(*this).GenerateObjCGetter(PID);
982 if (!PD->isReadOnly() &&
983 !D->getInstanceMethod(PD->getSetterName()))
984 CodeGenFunction(*this).GenerateObjCSetter(PID);
985 }
986 }
987}
988
Daniel Dunbar41071de2008-08-15 23:26:23 +0000989/// EmitTopLevelDecl - Emit code for a single top level declaration.
990void CodeGenModule::EmitTopLevelDecl(Decl *D) {
991 // If an error has occurred, stop code generation, but continue
992 // parsing and semantic analysis (to ensure all warnings and errors
993 // are emitted).
994 if (Diags.hasErrorOccurred())
995 return;
996
997 switch (D->getKind()) {
998 case Decl::Function:
999 case Decl::Var:
1000 EmitGlobal(cast<ValueDecl>(D));
1001 break;
1002
1003 case Decl::Namespace:
Daniel Dunbar662174c82008-08-29 17:28:43 +00001004 ErrorUnsupported(D, "namespace");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001005 break;
1006
1007 // Objective-C Decls
1008
1009 // Forward declarations, no (immediate) code generation.
1010 case Decl::ObjCClass:
1011 case Decl::ObjCCategory:
1012 case Decl::ObjCForwardProtocol:
1013 case Decl::ObjCInterface:
1014 break;
1015
1016 case Decl::ObjCProtocol:
1017 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1018 break;
1019
1020 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001021 // Categories have properties but don't support synthesize so we
1022 // can ignore them here.
1023
Daniel Dunbar41071de2008-08-15 23:26:23 +00001024 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1025 break;
1026
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001027 case Decl::ObjCImplementation: {
1028 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1029 EmitObjCPropertyImplementations(OMD);
1030 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001031 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001032 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001033 case Decl::ObjCMethod: {
1034 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1035 // If this is not a prototype, emit the body.
1036 if (OMD->getBody())
1037 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1038 break;
1039 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001040 case Decl::ObjCCompatibleAlias:
Daniel Dunbar662174c82008-08-29 17:28:43 +00001041 ErrorUnsupported(D, "Objective-C compatible alias");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001042 break;
1043
1044 case Decl::LinkageSpec: {
1045 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1046 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar488e9932008-08-16 00:56:44 +00001047 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar41071de2008-08-15 23:26:23 +00001048 // FIXME: implement C++ linkage, C linkage works mostly by C
1049 // language reuse already.
1050 break;
1051 }
1052
1053 case Decl::FileScopeAsm: {
1054 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1055 std::string AsmString(AD->getAsmString()->getStrData(),
1056 AD->getAsmString()->getByteLength());
1057
1058 const std::string &S = getModule().getModuleInlineAsm();
1059 if (S.empty())
1060 getModule().setModuleInlineAsm(AsmString);
1061 else
1062 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1063 break;
1064 }
1065
1066 default:
1067 // Make sure we handled everything we should, every other kind is
1068 // a non-top-level decl. FIXME: Would be nice to have an
1069 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1070 // that easily.
1071 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1072 }
1073}
1074