blob: fc1b108b0d6e722bb5abfe4801f819d2c397276e [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
Daniel Dunbara8f02052008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner825f6ea2008-11-04 16:51:42 +000021#include "clang/AST/DeclCXX.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000022#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000023#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000025#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000026#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000028#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30using namespace CodeGen;
31
32
Chris Lattnerdb6be562007-11-28 05:34:05 +000033CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000034 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar1be1df32008-08-11 21:35:06 +000035 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000036 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000037 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Eli Friedman8f08a252008-05-26 12:59:39 +000038 CFConstantStringClassRef(0) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000039
40 if (Features.ObjC1) {
Daniel Dunbar1be1df32008-08-11 21:35:06 +000041 if (Features.NeXTRuntime) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000042 Runtime = CreateMacObjCRuntime(*this);
43 } else {
44 Runtime = CreateGNUObjCRuntime(*this);
45 }
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000046 }
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000047
48 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000049 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000050}
51
52CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000053 delete Runtime;
54 delete DebugInfo;
55}
56
57void CodeGenModule::Release() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000058 EmitStatics();
Daniel Dunbar566a6502008-09-08 23:44:31 +000059 EmitAliases();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000060 if (Runtime)
61 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
62 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000063 EmitCtorList(GlobalCtors, "llvm.global_ctors");
64 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000065 EmitAnnotations();
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000066 BindRuntimeFunctions();
Chris Lattnercbfb5512008-03-01 08:45:05 +000067}
Chris Lattner4b009652007-07-25 00:24:17 +000068
Daniel Dunbar18c2ec62008-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 Dunbarfc1543e2008-11-19 06:15:35 +000075 // Discard unused runtime functions.
76 if (Fn->use_empty()) {
77 Fn->eraseFromParent();
78 continue;
79 }
80
Daniel Dunbar18c2ec62008-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 Dunbar9503b782008-08-16 00:56:44 +0000107/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000108/// specified stmt yet.
Daniel Dunbar49bddf72008-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 Dunbar9503b782008-08-16 00:56:44 +0000113 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000114 "cannot codegen this %0 yet");
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000115 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +0000116 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
117 << Msg << S->getSourceRange();
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000118}
Chris Lattner0e4755d2007-12-02 06:27:33 +0000119
Daniel Dunbar9503b782008-08-16 00:56:44 +0000120/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +0000121/// specified decl yet.
Daniel Dunbar49bddf72008-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 Dunbar9503b782008-08-16 00:56:44 +0000126 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner806a5f52008-01-12 07:05:38 +0000127 "cannot codegen this %0 yet");
128 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +0000129 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner806a5f52008-01-12 07:05:38 +0000130}
131
Daniel Dunbar27250d32008-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 Gohman4751a3a2008-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 Lattner753d2592008-03-14 17:18:18 +0000150/// AddGlobalCtor - Add a function to the list that will be called before
151/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000152void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner753d2592008-03-14 17:18:18 +0000153 // TODO: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000154 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000155}
156
Daniel Dunbardd2e9ca2008-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 Lattnera18c12e2008-03-19 05:24:56 +0000173 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000174 llvm::StructType::get(llvm::Type::Int32Ty,
175 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000176
Daniel Dunbardd2e9ca2008-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 Lattner753d2592008-03-14 17:18:18 +0000184 }
Daniel Dunbardd2e9ca2008-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 Lattner753d2592008-03-14 17:18:18 +0000194}
195
Nate Begeman52da5c72008-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 Dunbara8f02052008-09-08 21:33:45 +0000212static void SetGlobalValueAttributes(const Decl *D,
213 bool IsInternal,
214 bool IsInline,
Daniel Dunbar566a6502008-09-08 23:44:31 +0000215 llvm::GlobalValue *GV,
216 bool ForDefinition) {
Nuno Lopes78534382008-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 Dunbar566a6502008-09-08 23:44:31 +0000219 if (!ForDefinition) {
220 // Only a few attributes are set on declarations.
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000221 if (D->getAttr<DLLImportAttr>()) {
222 // The dllimport attribute is overridden by a subsequent declaration as
223 // dllexport.
224 if (!D->getAttr<DLLExportAttr>())
225 // dllimport attribute can be applied only to function decls, not to
226 // definitions.
227 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
228 if (!FD->getBody())
229 GV->setLinkage(llvm::Function::DLLImportLinkage);
230 } else
231 GV->setLinkage(llvm::Function::DLLImportLinkage);
232 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000233 } else {
234 if (IsInternal) {
235 GV->setLinkage(llvm::Function::InternalLinkage);
236 } else {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000237 if (D->getAttr<DLLExportAttr>()) {
238 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
239 // The dllexport attribute is ignored for undefined symbols.
240 if (FD->getBody())
241 GV->setLinkage(llvm::Function::DLLExportLinkage);
242 } else
243 GV->setLinkage(llvm::Function::DLLExportLinkage);
244 } else if (D->getAttr<WeakAttr>() || IsInline)
Daniel Dunbar566a6502008-09-08 23:44:31 +0000245 GV->setLinkage(llvm::Function::WeakLinkage);
246 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000247 }
Nuno Lopes78534382008-06-08 15:45:52 +0000248
Daniel Dunbara8f02052008-09-08 21:33:45 +0000249 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000250 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000251 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000252
Daniel Dunbara8f02052008-09-08 21:33:45 +0000253 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbarced89142008-08-06 00:03:29 +0000254 // Prefaced with special LLVM marker to indicate that the name
255 // should not be munged.
256 GV->setName("\01" + ALA->getLabel());
257 }
Nuno Lopes78534382008-06-08 15:45:52 +0000258}
259
Devang Patela85a9ef2008-09-25 21:02:23 +0000260void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000261 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000262 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000263 AttributeListType AttributeList;
264 ConstructAttributeList(D, Info.argtypes_begin(), Info.argtypes_end(),
265 AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000266
Devang Patela85a9ef2008-09-25 21:02:23 +0000267 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
268 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000269
270 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000271 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000272 F->setCallingConv(llvm::CallingConv::X86_FastCall);
273
274 if (D->getAttr<StdCallAttr>())
275 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000276}
277
278/// SetFunctionAttributesForDefinition - Set function attributes
279/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000280void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
281 llvm::Function *F) {
282 if (isa<ObjCMethodDecl>(D)) {
283 SetGlobalValueAttributes(D, true, false, F, true);
284 } else {
285 const FunctionDecl *FD = cast<FunctionDecl>(D);
286 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
287 FD->isInline(), F, true);
288 }
289
Daniel Dunbarf2787002008-09-04 23:41:35 +0000290 if (!Features.Exceptions)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000291 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000292
293 if (D->getAttr<AlwaysInlineAttr>())
294 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000295}
296
297void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
298 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000299 SetFunctionAttributes(MD, CGFunctionInfo(MD, Context), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000300
Daniel Dunbar566a6502008-09-08 23:44:31 +0000301 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000302}
303
304void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
305 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000306 SetFunctionAttributes(FD, CGFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000307
Daniel Dunbar566a6502008-09-08 23:44:31 +0000308 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
309 FD->isInline(), F, false);
310}
311
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000312
Daniel Dunbar566a6502008-09-08 23:44:31 +0000313void CodeGenModule::EmitAliases() {
314 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
315 const FunctionDecl *D = Aliases[i];
316 const AliasAttr *AA = D->getAttr<AliasAttr>();
317
318 // This is something of a hack, if the FunctionDecl got overridden
319 // then its attributes will be moved to the new declaration. In
320 // this case the current decl has no alias attribute, but we will
321 // eventually see it.
322 if (!AA)
323 continue;
324
325 const std::string& aliaseeName = AA->getAliasee();
326 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
327 if (!aliasee) {
328 // FIXME: This isn't unsupported, this is just an error, which
329 // sema should catch, but...
330 ErrorUnsupported(D, "alias referencing a missing function");
331 continue;
332 }
333
334 llvm::GlobalValue *GA =
335 new llvm::GlobalAlias(aliasee->getType(),
336 llvm::Function::ExternalLinkage,
Chris Lattner271d4c22008-11-24 05:29:24 +0000337 D->getNameAsString(), aliasee, &getModule());
Daniel Dunbar566a6502008-09-08 23:44:31 +0000338
339 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
340 if (Entry) {
341 // If we created a dummy function for this then replace it.
342 GA->takeName(Entry);
343
344 llvm::Value *Casted =
345 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
346 Entry->replaceAllUsesWith(Casted);
347 Entry->eraseFromParent();
348
349 Entry = GA;
350 }
351
352 // Alias should never be internal or inline.
353 SetGlobalValueAttributes(D, false, false, GA, true);
354 }
Eli Friedman9be42212008-06-01 15:54:49 +0000355}
356
Nate Begemanad320b62008-04-20 06:29:50 +0000357void CodeGenModule::EmitStatics() {
358 // Emit code for each used static decl encountered. Since a previously unused
359 // static decl may become used during the generation of code for a static
360 // function, iterate until no changes are made.
361 bool Changed;
362 do {
363 Changed = false;
364 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000365 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000366
367 // Check if we have used a decl with the same name
368 // FIXME: The AST should have some sort of aggregate decls or
369 // global symbol map.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000370 // FIXME: This is missing some important cases. For example, we
371 // need to check for uses in an alias and in a constructor.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000372 if (!GlobalDeclMap.count(D->getIdentifier()))
Daniel Dunbarced89142008-08-06 00:03:29 +0000373 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000374
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000375 // Emit the definition.
376 EmitGlobalDefinition(D);
377
Nate Begemanad320b62008-04-20 06:29:50 +0000378 // Erase the used decl from the list.
379 StaticDecls[i] = StaticDecls.back();
380 StaticDecls.pop_back();
381 --i;
382 --e;
383
384 // Remember that we made a change.
385 Changed = true;
386 }
387 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000388}
389
Nate Begeman8a704172008-04-19 04:17:09 +0000390/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
391/// annotation information for a given GlobalValue. The annotation struct is
392/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000393/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000394/// created from the AnnotateAttr's annotation. The third field is a constant
395/// string containing the name of the translation unit. The fourth field is
396/// the line number in the file of the annotated value declaration.
397///
398/// FIXME: this does not unique the annotation string constants, as llvm-gcc
399/// appears to.
400///
401llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
402 const AnnotateAttr *AA,
403 unsigned LineNo) {
404 llvm::Module *M = &getModule();
405
406 // get [N x i8] constants for the annotation string, and the filename string
407 // which are the 2nd and 3rd elements of the global annotation structure.
408 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
409 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
410 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
411 true);
412
413 // Get the two global values corresponding to the ConstantArrays we just
414 // created to hold the bytes of the strings.
415 llvm::GlobalValue *annoGV =
416 new llvm::GlobalVariable(anno->getType(), false,
417 llvm::GlobalValue::InternalLinkage, anno,
418 GV->getName() + ".str", M);
419 // translation unit name string, emitted into the llvm.metadata section.
420 llvm::GlobalValue *unitGV =
421 new llvm::GlobalVariable(unit->getType(), false,
422 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
423
424 // Create the ConstantStruct that is the global annotion.
425 llvm::Constant *Fields[4] = {
426 llvm::ConstantExpr::getBitCast(GV, SBP),
427 llvm::ConstantExpr::getBitCast(annoGV, SBP),
428 llvm::ConstantExpr::getBitCast(unitGV, SBP),
429 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
430 };
431 return llvm::ConstantStruct::get(Fields, 4, false);
432}
433
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000434void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
435 bool isDef, isStatic;
436
437 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000438 // Aliases are deferred until code for everything else has been
439 // emitted.
440 if (FD->getAttr<AliasAttr>()) {
441 assert(!FD->isThisDeclarationADefinition() &&
442 "Function alias cannot have a definition!");
443 Aliases.push_back(FD);
444 return;
445 }
446
447 isDef = FD->isThisDeclarationADefinition();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000448 isStatic = FD->getStorageClass() == FunctionDecl::Static;
449 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
450 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
451
452 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
453 isStatic = VD->getStorageClass() == VarDecl::Static;
454 } else {
455 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000456 return;
457 }
458
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000459 // Forward declarations are emitted lazily on first use.
460 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000461 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000462
463 // If the global is a static, defer code generation until later so
464 // we can easily omit unused statics.
465 if (isStatic) {
466 StaticDecls.push_back(Global);
467 return;
468 }
469
470 // Otherwise emit the definition.
471 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000472}
473
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000474void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
475 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
476 EmitGlobalFunctionDefinition(FD);
477 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
478 EmitGlobalVarDefinition(VD);
479 } else {
480 assert(0 && "Invalid argument to EmitGlobalDefinition()");
481 }
482}
483
Daniel Dunbar2188c532008-07-30 16:32:24 +0000484 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000485 assert(D->hasGlobalStorage() && "Not a global variable");
486
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000487 QualType ASTTy = D->getType();
488 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000489 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000490
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000491 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000492 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000493 if (!Entry)
494 Entry = new llvm::GlobalVariable(Ty, false,
495 llvm::GlobalValue::ExternalLinkage,
Chris Lattner271d4c22008-11-24 05:29:24 +0000496 0, D->getNameAsString(), &getModule(), 0,
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000497 ASTTy.getAddressSpace());
498
Daniel Dunbar2188c532008-07-30 16:32:24 +0000499 // Make sure the result is of the correct type.
500 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000501}
502
503void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000504 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000505 QualType ASTTy = D->getType();
506 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000507
Chris Lattner4b009652007-07-25 00:24:17 +0000508 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000509 // This is a tentative definition; tentative definitions are
510 // implicitly initialized with { 0 }
511 const llvm::Type* InitTy;
512 if (ASTTy->isIncompleteArrayType()) {
513 // An incomplete array is normally [ TYPE x 0 ], but we need
514 // to fix it to [ TYPE x 1 ].
515 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
516 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
517 } else {
518 InitTy = VarTy;
519 }
520 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000521 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000522 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000523 }
524 const llvm::Type* InitType = Init->getType();
525
Daniel Dunbarad30be42008-08-25 06:18:57 +0000526 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000527 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
528
Eli Friedman43a0ce82008-05-30 19:50:47 +0000529 if (!GV) {
530 GV = new llvm::GlobalVariable(InitType, false,
531 llvm::GlobalValue::ExternalLinkage,
Chris Lattner271d4c22008-11-24 05:29:24 +0000532 0, D->getNameAsString(), &getModule(), 0,
Eli Friedman43a0ce82008-05-30 19:50:47 +0000533 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000534 } else if (GV->getType() !=
535 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000536 // We have a definition after a prototype with the wrong type.
537 // We must make a new GlobalVariable* and update everything that used OldGV
538 // (a declaration or tentative definition) with the new GlobalVariable*
539 // (which will be a definition).
540 //
541 // This happens if there is a prototype for a global (e.g. "extern int x[];")
542 // and then a definition of a different type (e.g. "int x[10];"). This also
543 // happens when an initializer has a different type from the type of the
544 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000545 //
546 // FIXME: This also ends up happening if there's a definition followed by
547 // a tentative definition! (Although Sema rejects that construct
548 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000549
550 // Save the old global
551 llvm::GlobalVariable *OldGV = GV;
552
553 // Make a new global with the correct type
554 GV = new llvm::GlobalVariable(InitType, false,
555 llvm::GlobalValue::ExternalLinkage,
Chris Lattner271d4c22008-11-24 05:29:24 +0000556 0, D->getNameAsString(), &getModule(), 0,
Eli Friedman43a0ce82008-05-30 19:50:47 +0000557 ASTTy.getAddressSpace());
558 // Steal the name of the old global
559 GV->takeName(OldGV);
560
561 // Replace all uses of the old global with the new global
562 llvm::Constant *NewPtrForOldDecl =
563 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
564 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000565
566 // Erase the old global, since it is no longer used.
567 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000568 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000569
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000570 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000571
Nate Begeman8a704172008-04-19 04:17:09 +0000572 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
573 SourceManager &SM = Context.getSourceManager();
574 AddAnnotation(EmitAnnotateAttr(GV, AA,
575 SM.getLogicalLineNumber(D->getLocation())));
576 }
577
Chris Lattner4b009652007-07-25 00:24:17 +0000578 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000579 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner402b3372008-03-03 03:28:21 +0000580
Eli Friedman7008e9a2008-05-30 20:39:54 +0000581 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
582 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000583 if (const IncompleteArrayType* IAT =
584 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000585 Align = Context.getTypeAlign(IAT->getElementType());
586 else
587 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000588 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
589 Align = std::max(Align, AA->getAlignment());
590 }
591 GV->setAlignment(Align / 8);
592
Chris Lattner402b3372008-03-03 03:28:21 +0000593 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000594 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000595 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000596
597 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
598 // Prefaced with special LLVM marker to indicate that the name
599 // should not be munged.
600 GV->setName("\01" + ALA->getLabel());
601 }
Chris Lattner4b009652007-07-25 00:24:17 +0000602
603 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000604 if (D->getStorageClass() == VarDecl::Static)
605 GV->setLinkage(llvm::Function::InternalLinkage);
606 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000607 GV->setLinkage(llvm::Function::DLLImportLinkage);
608 else if (D->getAttr<DLLExportAttr>())
609 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000610 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000611 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000612 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000613 // FIXME: This isn't right. This should handle common linkage and other
614 // stuff.
615 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000616 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000617 case VarDecl::Auto:
618 case VarDecl::Register:
619 assert(0 && "Can't have auto or register globals");
620 case VarDecl::None:
621 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000622 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson689bba82008-12-03 05:51:23 +0000623 else
624 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000625 break;
626 case VarDecl::Extern:
627 case VarDecl::PrivateExtern:
628 // todo: common
629 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000630 }
Chris Lattner4b009652007-07-25 00:24:17 +0000631 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000632
633 // Emit global variable debug information.
634 CGDebugInfo *DI = getDebugInfo();
635 if(DI) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000636 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000637 DI->EmitGlobalVariable(GV, D);
638 }
Chris Lattner4b009652007-07-25 00:24:17 +0000639}
640
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000641llvm::GlobalValue *
642CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000643 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
644 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
645 llvm::Function::ExternalLinkage,
Chris Lattner271d4c22008-11-24 05:29:24 +0000646 D->getNameAsString(),&getModule());
Daniel Dunbar566a6502008-09-08 23:44:31 +0000647 SetFunctionAttributes(D, F);
648 return F;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000649}
650
651llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000652 QualType ASTTy = D->getType();
653 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
654 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000655
656 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000657 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000658 if (!Entry)
659 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000660
Daniel Dunbar2188c532008-07-30 16:32:24 +0000661 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000662}
663
664void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbarad30be42008-08-25 06:18:57 +0000665 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000666 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000667 Entry = EmitForwardFunctionDefinition(D);
668 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000669 // If the types mismatch then we have to rewrite the definition.
670 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
671 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000672 // Otherwise, we have a definition after a prototype with the wrong type.
673 // F is the Function* for the one with the wrong type, we must make a new
674 // Function* and update everything that used F (a declaration) with the new
675 // Function* (which will be a definition).
676 //
677 // This happens if there is a prototype for a function (e.g. "int f()") and
678 // then a definition of a different type (e.g. "int f(int x)"). Start by
679 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000680 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
681 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000682
683 // Replace uses of F with the Function we will endow with a body.
684 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000685 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
686 Entry->replaceAllUsesWith(NewPtrForOldDecl);
687
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000688 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000689 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar566a6502008-09-08 23:44:31 +0000690 Entry->eraseFromParent();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000691
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000692 Entry = NewFn;
693 }
694 }
695
Daniel Dunbar566a6502008-09-08 23:44:31 +0000696 llvm::Function *Fn = cast<llvm::Function>(Entry);
697 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000698
Daniel Dunbar566a6502008-09-08 23:44:31 +0000699 SetFunctionAttributesForDefinition(D, Fn);
700
701 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
702 AddGlobalCtor(Fn, CA->getPriority());
703 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
704 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000705 }
706}
707
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000708llvm::Function *
709CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
710 const std::string &Name) {
711 llvm::Function *Fn = llvm::Function::Create(FTy,
712 llvm::Function::ExternalLinkage,
713 "", &TheModule);
714 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
715 return Fn;
716}
717
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000718void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
719 // Make sure that this type is translated.
720 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000721}
722
723
Chris Lattnerab862cc2007-08-31 04:31:45 +0000724/// getBuiltinLibFunction
725llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000726 if (BuiltinID > BuiltinFunctions.size())
727 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000728
Chris Lattner9f2d6892007-12-13 00:38:03 +0000729 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
730 // a slot for it.
731 assert(BuiltinID && "Invalid Builtin ID");
732 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000733 if (FunctionSlot)
734 return FunctionSlot;
735
736 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
737
738 // Get the name, skip over the __builtin_ prefix.
739 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
740
741 // Get the type for the builtin.
742 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
743 const llvm::FunctionType *Ty =
744 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
745
746 // FIXME: This has a serious problem with code like this:
747 // void abs() {}
748 // ... __builtin_abs(x);
749 // The two versions of abs will collide. The fix is for the builtin to win,
750 // and for the existing one to be turned into a constantexpr cast of the
751 // builtin. In the case where the existing one is a static function, it
752 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000753 if (llvm::Function *Existing = getModule().getFunction(Name)) {
754 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
755 return FunctionSlot = Existing;
756 assert(Existing == 0 && "FIXME: Name collision");
757 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000758
759 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000760 return FunctionSlot =
761 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
762 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000763}
764
Chris Lattner4b23f942007-12-18 00:25:38 +0000765llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
766 unsigned NumTys) {
767 return llvm::Intrinsic::getDeclaration(&getModule(),
768 (llvm::Intrinsic::ID)IID, Tys, NumTys);
769}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000770
Chris Lattner4b009652007-07-25 00:24:17 +0000771llvm::Function *CodeGenModule::getMemCpyFn() {
772 if (MemCpyFn) return MemCpyFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000773 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
774 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000775}
Anders Carlsson36a04872007-08-21 00:21:21 +0000776
Eli Friedman8f08a252008-05-26 12:59:39 +0000777llvm::Function *CodeGenModule::getMemMoveFn() {
778 if (MemMoveFn) return MemMoveFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000779 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
780 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman8f08a252008-05-26 12:59:39 +0000781}
782
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000783llvm::Function *CodeGenModule::getMemSetFn() {
784 if (MemSetFn) return MemSetFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000785 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
786 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000787}
Chris Lattner4b23f942007-12-18 00:25:38 +0000788
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000789static void appendFieldAndPadding(CodeGenModule &CGM,
790 std::vector<llvm::Constant*>& Fields,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000791 FieldDecl *FieldD, FieldDecl *NextFieldD,
792 llvm::Constant* Field,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000793 RecordDecl* RD, const llvm::StructType *STy)
794{
795 // Append the field.
796 Fields.push_back(Field);
797
Douglas Gregor8acb7272008-12-11 16:49:14 +0000798 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000799
800 int NextStructFieldNo;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000801 if (!NextFieldD) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000802 NextStructFieldNo = STy->getNumElements();
803 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000804 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000805 }
806
807 // Append padding
808 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
809 llvm::Constant *C =
810 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
811
812 Fields.push_back(C);
813 }
814}
815
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000816// We still need to work out the details of handling UTF-16.
817// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +0000818llvm::Constant *CodeGenModule::
819GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000820 llvm::StringMapEntry<llvm::Constant *> &Entry =
821 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
822
823 if (Entry.getValue())
824 return Entry.getValue();
825
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000826 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
827 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +0000828
829 if (!CFConstantStringClassRef) {
830 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
831 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000832
833 // FIXME: This is fairly broken if
834 // __CFConstantStringClassReference is already defined, in that it
835 // will get renamed and the user will most likely see an opaque
836 // error message. This is a general issue with relying on
837 // particular names.
838 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +0000839 new llvm::GlobalVariable(Ty, false,
840 llvm::GlobalVariable::ExternalLinkage, 0,
841 "__CFConstantStringClassReference",
842 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000843
844 // Decay array -> ptr
845 CFConstantStringClassRef =
846 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +0000847 }
848
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000849 QualType CFTy = getContext().getCFConstantStringType();
850 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000851
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000852 const llvm::StructType *STy =
853 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
854
855 std::vector<llvm::Constant*> Fields;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000856 RecordDecl::field_iterator Field = CFRD->field_begin();
857
Anders Carlsson36a04872007-08-21 00:21:21 +0000858 // Class pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000859 FieldDecl *CurField = *Field++;
860 FieldDecl *NextField = *Field++;
861 appendFieldAndPadding(*this, Fields, CurField, NextField,
862 CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000863
864 // Flags.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000865 CurField = NextField;
866 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000867 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000868 appendFieldAndPadding(*this, Fields, CurField, NextField,
869 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000870
871 // String pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000872 CurField = NextField;
873 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000874 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +0000875 C = new llvm::GlobalVariable(C->getType(), true,
876 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000877 C, ".str", &getModule());
Douglas Gregor8acb7272008-12-11 16:49:14 +0000878 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000879 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
880 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000881
882 // String length.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000883 CurField = NextField;
884 NextField = 0;
Anders Carlsson36a04872007-08-21 00:21:21 +0000885 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000886 appendFieldAndPadding(*this, Fields, CurField, NextField,
887 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000888
889 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000890 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000891 llvm::GlobalVariable *GV =
892 new llvm::GlobalVariable(C->getType(), true,
893 llvm::GlobalVariable::InternalLinkage,
894 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000895
Anders Carlsson9be009e2007-11-01 00:41:52 +0000896 GV->setSection("__DATA,__cfstring");
897 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000898
Anders Carlsson9be009e2007-11-01 00:41:52 +0000899 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000900}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000901
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000902/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000903/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000904std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar952f4732008-08-29 17:28:43 +0000905 if (E->isWide()) {
906 ErrorUnsupported(E, "wide string");
907 return "FIXME";
908 }
909
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000910 const char *StrData = E->getStrData();
911 unsigned Len = E->getByteLength();
912
913 const ConstantArrayType *CAT =
914 getContext().getAsConstantArrayType(E->getType());
915 assert(CAT && "String isn't pointer or array!");
916
917 // Resize the string to the right size
918 // FIXME: What about wchar_t strings?
919 std::string Str(StrData, StrData+Len);
920 uint64_t RealLen = CAT->getSize().getZExtValue();
921 Str.resize(RealLen, '\0');
922
923 return Str;
924}
925
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000926/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
927/// constant array for the given string literal.
928llvm::Constant *
929CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
930 // FIXME: This can be more efficient.
931 return GetAddrOfConstantString(GetStringForStringLiteral(S));
932}
933
Chris Lattnera6dcce32008-02-11 00:02:17 +0000934/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000935static llvm::Constant *GenerateStringLiteral(const std::string &str,
936 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000937 CodeGenModule &CGM,
938 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000939 // Create Constant for this string literal. Don't add a '\0'.
940 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000941
942 // Create a global variable for this string
943 C = new llvm::GlobalVariable(C->getType(), constant,
944 llvm::GlobalValue::InternalLinkage,
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000945 C,
946 GlobalName ? GlobalName : ".str",
947 &CGM.getModule());
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000948
Chris Lattnerdb6be562007-11-28 05:34:05 +0000949 return C;
950}
951
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000952/// GetAddrOfConstantString - Returns a pointer to a character array
953/// containing the literal. This contents are exactly that of the
954/// given string, i.e. it will not be null terminated automatically;
955/// see GetAddrOfConstantCString. Note that whether the result is
956/// actually a pointer to an LLVM constant depends on
957/// Feature.WriteableStrings.
958///
959/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000960llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
961 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000962 // Don't share any string literals if writable-strings is turned on.
963 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000964 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000965
966 llvm::StringMapEntry<llvm::Constant *> &Entry =
967 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
968
969 if (Entry.getValue())
970 return Entry.getValue();
971
972 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000973 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000974 Entry.setValue(C);
975 return C;
976}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000977
978/// GetAddrOfConstantCString - Returns a pointer to a character
979/// array containing the literal and a terminating '\-'
980/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000981llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
982 const char *GlobalName){
Chris Lattnerb2176012008-12-09 19:10:54 +0000983 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000984}
Daniel Dunbar27250d32008-08-15 23:26:23 +0000985
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000986/// EmitObjCPropertyImplementations - Emit information for synthesized
987/// properties for an implementation.
988void CodeGenModule::EmitObjCPropertyImplementations(const
989 ObjCImplementationDecl *D) {
990 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
991 e = D->propimpl_end(); i != e; ++i) {
992 ObjCPropertyImplDecl *PID = *i;
993
994 // Dynamic is just for type-checking.
995 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
996 ObjCPropertyDecl *PD = PID->getPropertyDecl();
997
998 // Determine which methods need to be implemented, some may have
999 // been overridden. Note that ::isSynthesized is not the method
1000 // we want, that just indicates if the decl came from a
1001 // property. What we want to know is if the method is defined in
1002 // this implementation.
1003 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001004 CodeGenFunction(*this).GenerateObjCGetter(
1005 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001006 if (!PD->isReadOnly() &&
1007 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001008 CodeGenFunction(*this).GenerateObjCSetter(
1009 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001010 }
1011 }
1012}
1013
Daniel Dunbar27250d32008-08-15 23:26:23 +00001014/// EmitTopLevelDecl - Emit code for a single top level declaration.
1015void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1016 // If an error has occurred, stop code generation, but continue
1017 // parsing and semantic analysis (to ensure all warnings and errors
1018 // are emitted).
1019 if (Diags.hasErrorOccurred())
1020 return;
1021
1022 switch (D->getKind()) {
1023 case Decl::Function:
1024 case Decl::Var:
1025 EmitGlobal(cast<ValueDecl>(D));
1026 break;
1027
1028 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001029 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001030 break;
1031
1032 // Objective-C Decls
1033
1034 // Forward declarations, no (immediate) code generation.
1035 case Decl::ObjCClass:
1036 case Decl::ObjCCategory:
1037 case Decl::ObjCForwardProtocol:
1038 case Decl::ObjCInterface:
1039 break;
1040
1041 case Decl::ObjCProtocol:
1042 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1043 break;
1044
1045 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001046 // Categories have properties but don't support synthesize so we
1047 // can ignore them here.
1048
Daniel Dunbar27250d32008-08-15 23:26:23 +00001049 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1050 break;
1051
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001052 case Decl::ObjCImplementation: {
1053 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1054 EmitObjCPropertyImplementations(OMD);
1055 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001056 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001057 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001058 case Decl::ObjCMethod: {
1059 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1060 // If this is not a prototype, emit the body.
1061 if (OMD->getBody())
1062 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1063 break;
1064 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001065 case Decl::ObjCCompatibleAlias:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001066 ErrorUnsupported(D, "Objective-C compatible alias");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001067 break;
1068
1069 case Decl::LinkageSpec: {
1070 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1071 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001072 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001073 // FIXME: implement C++ linkage, C linkage works mostly by C
1074 // language reuse already.
1075 break;
1076 }
1077
1078 case Decl::FileScopeAsm: {
1079 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1080 std::string AsmString(AD->getAsmString()->getStrData(),
1081 AD->getAsmString()->getByteLength());
1082
1083 const std::string &S = getModule().getModuleInlineAsm();
1084 if (S.empty())
1085 getModule().setModuleInlineAsm(AsmString);
1086 else
1087 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1088 break;
1089 }
1090
1091 default:
1092 // Make sure we handled everything we should, every other kind is
1093 // a non-top-level decl. FIXME: Would be nice to have an
1094 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1095 // that easily.
1096 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1097 }
1098}
1099