blob: 2ca893fb41fe51842d640764511d448cab690555 [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 Lattnercf9c9d02007-12-02 07:19:18 +000021#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000024#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000025#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000027#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29using namespace CodeGen;
30
31
Chris Lattnerdb6be562007-11-28 05:34:05 +000032CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000033 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar1be1df32008-08-11 21:35:06 +000034 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000035 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000036 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Eli Friedman8f08a252008-05-26 12:59:39 +000037 CFConstantStringClassRef(0) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000038
39 if (Features.ObjC1) {
Daniel Dunbar1be1df32008-08-11 21:35:06 +000040 if (Features.NeXTRuntime) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000041 Runtime = CreateMacObjCRuntime(*this);
42 } else {
43 Runtime = CreateGNUObjCRuntime(*this);
44 }
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000045 }
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000046
47 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000048 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000049}
50
51CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000052 delete Runtime;
53 delete DebugInfo;
54}
55
56void CodeGenModule::Release() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000057 EmitStatics();
Daniel Dunbar566a6502008-09-08 23:44:31 +000058 EmitAliases();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000059 if (Runtime)
60 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
61 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000062 EmitCtorList(GlobalCtors, "llvm.global_ctors");
63 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000064 EmitAnnotations();
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000065 BindRuntimeFunctions();
Chris Lattnercbfb5512008-03-01 08:45:05 +000066}
Chris Lattner4b009652007-07-25 00:24:17 +000067
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000068void CodeGenModule::BindRuntimeFunctions() {
69 // Deal with protecting runtime function names.
70 for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
71 llvm::Function *Fn = RuntimeFunctions[i].first;
72 const std::string &Name = RuntimeFunctions[i].second;
73
74 // See if there is a conflict against a function.
75 llvm::Function *Conflict = TheModule.getFunction(Name);
76 if (Conflict) {
77 // Decide which version to take. If the conflict is a definition
78 // we are forced to take that, otherwise assume the runtime
79 // knows best.
80 if (!Conflict->isDeclaration()) {
81 llvm::Value *Casted =
82 llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
83 Fn->replaceAllUsesWith(Casted);
84 Fn->eraseFromParent();
85 } else {
86 Fn->takeName(Conflict);
87 llvm::Value *Casted =
88 llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
89 Conflict->replaceAllUsesWith(Casted);
90 Conflict->eraseFromParent();
91 }
92 } else {
93 // FIXME: There still may be conflicts with aliases and
94 // variables.
95 Fn->setName(Name);
96 }
97 }
98}
99
Daniel Dunbar9503b782008-08-16 00:56:44 +0000100/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000101/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000102void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
103 bool OmitOnError) {
104 if (OmitOnError && getDiags().hasErrorOccurred())
105 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000106 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000107 "cannot codegen this %0 yet");
108 SourceRange Range = S->getSourceRange();
109 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000110 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000111 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000112}
Chris Lattner0e4755d2007-12-02 06:27:33 +0000113
Daniel Dunbar9503b782008-08-16 00:56:44 +0000114/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +0000115/// specified decl yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000116void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
117 bool OmitOnError) {
118 if (OmitOnError && getDiags().hasErrorOccurred())
119 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000120 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner806a5f52008-01-12 07:05:38 +0000121 "cannot codegen this %0 yet");
122 std::string Msg = Type;
123 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
124 &Msg, 1);
125}
126
Daniel Dunbar27250d32008-08-15 23:26:23 +0000127/// setGlobalVisibility - Set the visibility for the given LLVM
128/// GlobalValue according to the given clang AST visibility value.
129static void setGlobalVisibility(llvm::GlobalValue *GV,
130 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4751a3a2008-05-22 00:50:06 +0000131 switch (Vis) {
132 default: assert(0 && "Unknown visibility!");
133 case VisibilityAttr::DefaultVisibility:
134 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
135 break;
136 case VisibilityAttr::HiddenVisibility:
137 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
138 break;
139 case VisibilityAttr::ProtectedVisibility:
140 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
141 break;
142 }
143}
144
Chris Lattner753d2592008-03-14 17:18:18 +0000145/// AddGlobalCtor - Add a function to the list that will be called before
146/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000147void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner753d2592008-03-14 17:18:18 +0000148 // TODO: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000149 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000150}
151
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000152/// AddGlobalDtor - Add a function to the list that will be called
153/// when the module is unloaded.
154void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
155 // TODO: Type coercion of void()* types.
156 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
157}
158
159void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
160 // Ctor function type is void()*.
161 llvm::FunctionType* CtorFTy =
162 llvm::FunctionType::get(llvm::Type::VoidTy,
163 std::vector<const llvm::Type*>(),
164 false);
165 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
166
167 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000168 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000169 llvm::StructType::get(llvm::Type::Int32Ty,
170 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000171
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000172 // Construct the constructor and destructor arrays.
173 std::vector<llvm::Constant*> Ctors;
174 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
175 std::vector<llvm::Constant*> S;
176 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
177 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
178 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000179 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000180
181 if (!Ctors.empty()) {
182 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
183 new llvm::GlobalVariable(AT, false,
184 llvm::GlobalValue::AppendingLinkage,
185 llvm::ConstantArray::get(AT, Ctors),
186 GlobalName,
187 &TheModule);
188 }
Chris Lattner753d2592008-03-14 17:18:18 +0000189}
190
Nate Begeman52da5c72008-04-18 23:43:57 +0000191void CodeGenModule::EmitAnnotations() {
192 if (Annotations.empty())
193 return;
194
195 // Create a new global variable for the ConstantStruct in the Module.
196 llvm::Constant *Array =
197 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
198 Annotations.size()),
199 Annotations);
200 llvm::GlobalValue *gv =
201 new llvm::GlobalVariable(Array->getType(), false,
202 llvm::GlobalValue::AppendingLinkage, Array,
203 "llvm.global.annotations", &TheModule);
204 gv->setSection("llvm.metadata");
205}
206
Daniel Dunbara8f02052008-09-08 21:33:45 +0000207static void SetGlobalValueAttributes(const Decl *D,
208 bool IsInternal,
209 bool IsInline,
Daniel Dunbar566a6502008-09-08 23:44:31 +0000210 llvm::GlobalValue *GV,
211 bool ForDefinition) {
Nuno Lopes78534382008-06-08 15:45:52 +0000212 // TODO: Set up linkage and many other things. Note, this is a simple
213 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000214 if (!ForDefinition) {
215 // Only a few attributes are set on declarations.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000216 if (D->getAttr<DLLImportAttr>())
217 GV->setLinkage(llvm::Function::DLLImportLinkage);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000218 } else {
219 if (IsInternal) {
220 GV->setLinkage(llvm::Function::InternalLinkage);
221 } else {
222 if (D->getAttr<DLLImportAttr>())
223 GV->setLinkage(llvm::Function::DLLImportLinkage);
224 else if (D->getAttr<DLLExportAttr>())
225 GV->setLinkage(llvm::Function::DLLExportLinkage);
226 else if (D->getAttr<WeakAttr>() || IsInline)
227 GV->setLinkage(llvm::Function::WeakLinkage);
228 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000229 }
Nuno Lopes78534382008-06-08 15:45:52 +0000230
Daniel Dunbara8f02052008-09-08 21:33:45 +0000231 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000232 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000233 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000234
Daniel Dunbara8f02052008-09-08 21:33:45 +0000235 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbarced89142008-08-06 00:03:29 +0000236 // Prefaced with special LLVM marker to indicate that the name
237 // should not be munged.
238 GV->setName("\01" + ALA->getLabel());
239 }
Nuno Lopes78534382008-06-08 15:45:52 +0000240}
241
Devang Patela85a9ef2008-09-25 21:02:23 +0000242void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000243 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000244 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000245 AttributeListType AttributeList;
246 ConstructAttributeList(D, Info.argtypes_begin(), Info.argtypes_end(),
247 AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000248
Devang Patela85a9ef2008-09-25 21:02:23 +0000249 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
250 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000251
252 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000253 if (D->getAttr<FastCallAttr>())
Eli Friedman9be42212008-06-01 15:54:49 +0000254 F->setCallingConv(llvm::CallingConv::Fast);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000255}
256
257/// SetFunctionAttributesForDefinition - Set function attributes
258/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000259void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
260 llvm::Function *F) {
261 if (isa<ObjCMethodDecl>(D)) {
262 SetGlobalValueAttributes(D, true, false, F, true);
263 } else {
264 const FunctionDecl *FD = cast<FunctionDecl>(D);
265 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
266 FD->isInline(), F, true);
267 }
268
Daniel Dunbarf2787002008-09-04 23:41:35 +0000269 if (!Features.Exceptions)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000270 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000271
272 if (D->getAttr<AlwaysInlineAttr>())
273 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000274}
275
276void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
277 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000278 SetFunctionAttributes(MD, CGFunctionInfo(MD, Context), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000279
Daniel Dunbar566a6502008-09-08 23:44:31 +0000280 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000281}
282
283void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
284 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000285 SetFunctionAttributes(FD, CGFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000286
Daniel Dunbar566a6502008-09-08 23:44:31 +0000287 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
288 FD->isInline(), F, false);
289}
290
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000291
Daniel Dunbar566a6502008-09-08 23:44:31 +0000292void CodeGenModule::EmitAliases() {
293 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
294 const FunctionDecl *D = Aliases[i];
295 const AliasAttr *AA = D->getAttr<AliasAttr>();
296
297 // This is something of a hack, if the FunctionDecl got overridden
298 // then its attributes will be moved to the new declaration. In
299 // this case the current decl has no alias attribute, but we will
300 // eventually see it.
301 if (!AA)
302 continue;
303
304 const std::string& aliaseeName = AA->getAliasee();
305 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
306 if (!aliasee) {
307 // FIXME: This isn't unsupported, this is just an error, which
308 // sema should catch, but...
309 ErrorUnsupported(D, "alias referencing a missing function");
310 continue;
311 }
312
313 llvm::GlobalValue *GA =
314 new llvm::GlobalAlias(aliasee->getType(),
315 llvm::Function::ExternalLinkage,
316 D->getName(),
317 aliasee,
318 &getModule());
319
320 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
321 if (Entry) {
322 // If we created a dummy function for this then replace it.
323 GA->takeName(Entry);
324
325 llvm::Value *Casted =
326 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
327 Entry->replaceAllUsesWith(Casted);
328 Entry->eraseFromParent();
329
330 Entry = GA;
331 }
332
333 // Alias should never be internal or inline.
334 SetGlobalValueAttributes(D, false, false, GA, true);
335 }
Eli Friedman9be42212008-06-01 15:54:49 +0000336}
337
Nate Begemanad320b62008-04-20 06:29:50 +0000338void CodeGenModule::EmitStatics() {
339 // Emit code for each used static decl encountered. Since a previously unused
340 // static decl may become used during the generation of code for a static
341 // function, iterate until no changes are made.
342 bool Changed;
343 do {
344 Changed = false;
345 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000346 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000347
348 // Check if we have used a decl with the same name
349 // FIXME: The AST should have some sort of aggregate decls or
350 // global symbol map.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000351 // FIXME: This is missing some important cases. For example, we
352 // need to check for uses in an alias and in a constructor.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000353 if (!GlobalDeclMap.count(D->getIdentifier()))
Daniel Dunbarced89142008-08-06 00:03:29 +0000354 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000355
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000356 // Emit the definition.
357 EmitGlobalDefinition(D);
358
Nate Begemanad320b62008-04-20 06:29:50 +0000359 // Erase the used decl from the list.
360 StaticDecls[i] = StaticDecls.back();
361 StaticDecls.pop_back();
362 --i;
363 --e;
364
365 // Remember that we made a change.
366 Changed = true;
367 }
368 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000369}
370
Nate Begeman8a704172008-04-19 04:17:09 +0000371/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
372/// annotation information for a given GlobalValue. The annotation struct is
373/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000374/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000375/// created from the AnnotateAttr's annotation. The third field is a constant
376/// string containing the name of the translation unit. The fourth field is
377/// the line number in the file of the annotated value declaration.
378///
379/// FIXME: this does not unique the annotation string constants, as llvm-gcc
380/// appears to.
381///
382llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
383 const AnnotateAttr *AA,
384 unsigned LineNo) {
385 llvm::Module *M = &getModule();
386
387 // get [N x i8] constants for the annotation string, and the filename string
388 // which are the 2nd and 3rd elements of the global annotation structure.
389 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
390 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
391 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
392 true);
393
394 // Get the two global values corresponding to the ConstantArrays we just
395 // created to hold the bytes of the strings.
396 llvm::GlobalValue *annoGV =
397 new llvm::GlobalVariable(anno->getType(), false,
398 llvm::GlobalValue::InternalLinkage, anno,
399 GV->getName() + ".str", M);
400 // translation unit name string, emitted into the llvm.metadata section.
401 llvm::GlobalValue *unitGV =
402 new llvm::GlobalVariable(unit->getType(), false,
403 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
404
405 // Create the ConstantStruct that is the global annotion.
406 llvm::Constant *Fields[4] = {
407 llvm::ConstantExpr::getBitCast(GV, SBP),
408 llvm::ConstantExpr::getBitCast(annoGV, SBP),
409 llvm::ConstantExpr::getBitCast(unitGV, SBP),
410 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
411 };
412 return llvm::ConstantStruct::get(Fields, 4, false);
413}
414
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000415void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
416 bool isDef, isStatic;
417
418 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000419 // Aliases are deferred until code for everything else has been
420 // emitted.
421 if (FD->getAttr<AliasAttr>()) {
422 assert(!FD->isThisDeclarationADefinition() &&
423 "Function alias cannot have a definition!");
424 Aliases.push_back(FD);
425 return;
426 }
427
428 isDef = FD->isThisDeclarationADefinition();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000429 isStatic = FD->getStorageClass() == FunctionDecl::Static;
430 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
431 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
432
433 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
434 isStatic = VD->getStorageClass() == VarDecl::Static;
435 } else {
436 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000437 return;
438 }
439
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000440 // Forward declarations are emitted lazily on first use.
441 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000442 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000443
444 // If the global is a static, defer code generation until later so
445 // we can easily omit unused statics.
446 if (isStatic) {
447 StaticDecls.push_back(Global);
448 return;
449 }
450
451 // Otherwise emit the definition.
452 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000453}
454
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000455void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
456 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
457 EmitGlobalFunctionDefinition(FD);
458 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
459 EmitGlobalVarDefinition(VD);
460 } else {
461 assert(0 && "Invalid argument to EmitGlobalDefinition()");
462 }
463}
464
Daniel Dunbar2188c532008-07-30 16:32:24 +0000465 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000466 assert(D->hasGlobalStorage() && "Not a global variable");
467
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000468 QualType ASTTy = D->getType();
469 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000470 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000471
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000472 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000473 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000474 if (!Entry)
475 Entry = new llvm::GlobalVariable(Ty, false,
476 llvm::GlobalValue::ExternalLinkage,
477 0, D->getName(), &getModule(), 0,
478 ASTTy.getAddressSpace());
479
Daniel Dunbar2188c532008-07-30 16:32:24 +0000480 // Make sure the result is of the correct type.
481 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000482}
483
484void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000485 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000486 QualType ASTTy = D->getType();
487 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000488
Chris Lattner4b009652007-07-25 00:24:17 +0000489 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000490 // This is a tentative definition; tentative definitions are
491 // implicitly initialized with { 0 }
492 const llvm::Type* InitTy;
493 if (ASTTy->isIncompleteArrayType()) {
494 // An incomplete array is normally [ TYPE x 0 ], but we need
495 // to fix it to [ TYPE x 1 ].
496 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
497 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
498 } else {
499 InitTy = VarTy;
500 }
501 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000502 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000503 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000504 }
505 const llvm::Type* InitType = Init->getType();
506
Daniel Dunbarad30be42008-08-25 06:18:57 +0000507 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000508 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
509
Eli Friedman43a0ce82008-05-30 19:50:47 +0000510 if (!GV) {
511 GV = new llvm::GlobalVariable(InitType, false,
512 llvm::GlobalValue::ExternalLinkage,
513 0, D->getName(), &getModule(), 0,
514 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000515 } else if (GV->getType() !=
516 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000517 // We have a definition after a prototype with the wrong type.
518 // We must make a new GlobalVariable* and update everything that used OldGV
519 // (a declaration or tentative definition) with the new GlobalVariable*
520 // (which will be a definition).
521 //
522 // This happens if there is a prototype for a global (e.g. "extern int x[];")
523 // and then a definition of a different type (e.g. "int x[10];"). This also
524 // happens when an initializer has a different type from the type of the
525 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000526 //
527 // FIXME: This also ends up happening if there's a definition followed by
528 // a tentative definition! (Although Sema rejects that construct
529 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000530
531 // Save the old global
532 llvm::GlobalVariable *OldGV = GV;
533
534 // Make a new global with the correct type
535 GV = new llvm::GlobalVariable(InitType, false,
536 llvm::GlobalValue::ExternalLinkage,
537 0, D->getName(), &getModule(), 0,
538 ASTTy.getAddressSpace());
539 // Steal the name of the old global
540 GV->takeName(OldGV);
541
542 // Replace all uses of the old global with the new global
543 llvm::Constant *NewPtrForOldDecl =
544 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
545 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000546
547 // Erase the old global, since it is no longer used.
548 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000549 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000550
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000551 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000552
Nate Begeman8a704172008-04-19 04:17:09 +0000553 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
554 SourceManager &SM = Context.getSourceManager();
555 AddAnnotation(EmitAnnotateAttr(GV, AA,
556 SM.getLogicalLineNumber(D->getLocation())));
557 }
558
Chris Lattner4b009652007-07-25 00:24:17 +0000559 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000560 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner402b3372008-03-03 03:28:21 +0000561
Eli Friedman7008e9a2008-05-30 20:39:54 +0000562 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
563 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000564 if (const IncompleteArrayType* IAT =
565 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000566 Align = Context.getTypeAlign(IAT->getElementType());
567 else
568 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000569 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
570 Align = std::max(Align, AA->getAlignment());
571 }
572 GV->setAlignment(Align / 8);
573
Chris Lattner402b3372008-03-03 03:28:21 +0000574 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000575 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000576 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000577
578 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
579 // Prefaced with special LLVM marker to indicate that the name
580 // should not be munged.
581 GV->setName("\01" + ALA->getLabel());
582 }
Chris Lattner4b009652007-07-25 00:24:17 +0000583
584 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000585 if (D->getStorageClass() == VarDecl::Static)
586 GV->setLinkage(llvm::Function::InternalLinkage);
587 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000588 GV->setLinkage(llvm::Function::DLLImportLinkage);
589 else if (D->getAttr<DLLExportAttr>())
590 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000591 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000592 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000593 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000594 // FIXME: This isn't right. This should handle common linkage and other
595 // stuff.
596 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000597 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000598 case VarDecl::Auto:
599 case VarDecl::Register:
600 assert(0 && "Can't have auto or register globals");
601 case VarDecl::None:
602 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000603 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000604 break;
605 case VarDecl::Extern:
606 case VarDecl::PrivateExtern:
607 // todo: common
608 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000609 }
Chris Lattner4b009652007-07-25 00:24:17 +0000610 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000611
612 // Emit global variable debug information.
613 CGDebugInfo *DI = getDebugInfo();
614 if(DI) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000615 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000616 DI->EmitGlobalVariable(GV, D);
617 }
Chris Lattner4b009652007-07-25 00:24:17 +0000618}
619
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000620llvm::GlobalValue *
621CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000622 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
623 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
624 llvm::Function::ExternalLinkage,
625 D->getName(), &getModule());
626 SetFunctionAttributes(D, F);
627 return F;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000628}
629
630llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000631 QualType ASTTy = D->getType();
632 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
633 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000634
635 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000636 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000637 if (!Entry)
638 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000639
Daniel Dunbar2188c532008-07-30 16:32:24 +0000640 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000641}
642
643void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbarad30be42008-08-25 06:18:57 +0000644 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000645 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000646 Entry = EmitForwardFunctionDefinition(D);
647 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000648 // If the types mismatch then we have to rewrite the definition.
649 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
650 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000651 // Otherwise, we have a definition after a prototype with the wrong type.
652 // F is the Function* for the one with the wrong type, we must make a new
653 // Function* and update everything that used F (a declaration) with the new
654 // Function* (which will be a definition).
655 //
656 // This happens if there is a prototype for a function (e.g. "int f()") and
657 // then a definition of a different type (e.g. "int f(int x)"). Start by
658 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000659 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
660 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000661
662 // Replace uses of F with the Function we will endow with a body.
663 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000664 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
665 Entry->replaceAllUsesWith(NewPtrForOldDecl);
666
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000667 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000668 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar566a6502008-09-08 23:44:31 +0000669 Entry->eraseFromParent();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000670
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000671 Entry = NewFn;
672 }
673 }
674
Daniel Dunbar566a6502008-09-08 23:44:31 +0000675 llvm::Function *Fn = cast<llvm::Function>(Entry);
676 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000677
Daniel Dunbar566a6502008-09-08 23:44:31 +0000678 SetFunctionAttributesForDefinition(D, Fn);
679
680 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
681 AddGlobalCtor(Fn, CA->getPriority());
682 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
683 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000684 }
685}
686
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000687llvm::Function *
688CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
689 const std::string &Name) {
690 llvm::Function *Fn = llvm::Function::Create(FTy,
691 llvm::Function::ExternalLinkage,
692 "", &TheModule);
693 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
694 return Fn;
695}
696
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000697void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
698 // Make sure that this type is translated.
699 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000700}
701
702
Chris Lattnerab862cc2007-08-31 04:31:45 +0000703/// getBuiltinLibFunction
704llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000705 if (BuiltinID > BuiltinFunctions.size())
706 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000707
Chris Lattner9f2d6892007-12-13 00:38:03 +0000708 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
709 // a slot for it.
710 assert(BuiltinID && "Invalid Builtin ID");
711 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000712 if (FunctionSlot)
713 return FunctionSlot;
714
715 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
716
717 // Get the name, skip over the __builtin_ prefix.
718 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
719
720 // Get the type for the builtin.
721 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
722 const llvm::FunctionType *Ty =
723 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
724
725 // FIXME: This has a serious problem with code like this:
726 // void abs() {}
727 // ... __builtin_abs(x);
728 // The two versions of abs will collide. The fix is for the builtin to win,
729 // and for the existing one to be turned into a constantexpr cast of the
730 // builtin. In the case where the existing one is a static function, it
731 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000732 if (llvm::Function *Existing = getModule().getFunction(Name)) {
733 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
734 return FunctionSlot = Existing;
735 assert(Existing == 0 && "FIXME: Name collision");
736 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000737
738 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000739 return FunctionSlot =
740 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
741 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000742}
743
Chris Lattner4b23f942007-12-18 00:25:38 +0000744llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
745 unsigned NumTys) {
746 return llvm::Intrinsic::getDeclaration(&getModule(),
747 (llvm::Intrinsic::ID)IID, Tys, NumTys);
748}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000749
Chris Lattner4b009652007-07-25 00:24:17 +0000750llvm::Function *CodeGenModule::getMemCpyFn() {
751 if (MemCpyFn) return MemCpyFn;
752 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000753 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000754 default: assert(0 && "Unknown ptr width");
755 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
756 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
757 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000758 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000759}
Anders Carlsson36a04872007-08-21 00:21:21 +0000760
Eli Friedman8f08a252008-05-26 12:59:39 +0000761llvm::Function *CodeGenModule::getMemMoveFn() {
762 if (MemMoveFn) return MemMoveFn;
763 llvm::Intrinsic::ID IID;
764 switch (Context.Target.getPointerWidth(0)) {
765 default: assert(0 && "Unknown ptr width");
766 case 32: IID = llvm::Intrinsic::memmove_i32; break;
767 case 64: IID = llvm::Intrinsic::memmove_i64; break;
768 }
769 return MemMoveFn = getIntrinsic(IID);
770}
771
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000772llvm::Function *CodeGenModule::getMemSetFn() {
773 if (MemSetFn) return MemSetFn;
774 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000775 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000776 default: assert(0 && "Unknown ptr width");
777 case 32: IID = llvm::Intrinsic::memset_i32; break;
778 case 64: IID = llvm::Intrinsic::memset_i64; break;
779 }
780 return MemSetFn = getIntrinsic(IID);
781}
Chris Lattner4b23f942007-12-18 00:25:38 +0000782
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000783// We still need to work out the details of handling UTF-16.
784// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +0000785llvm::Constant *CodeGenModule::
786GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000787 llvm::StringMapEntry<llvm::Constant *> &Entry =
788 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
789
790 if (Entry.getValue())
791 return Entry.getValue();
792
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000793 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
794 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +0000795
796 if (!CFConstantStringClassRef) {
797 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
798 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000799
800 // FIXME: This is fairly broken if
801 // __CFConstantStringClassReference is already defined, in that it
802 // will get renamed and the user will most likely see an opaque
803 // error message. This is a general issue with relying on
804 // particular names.
805 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +0000806 new llvm::GlobalVariable(Ty, false,
807 llvm::GlobalVariable::ExternalLinkage, 0,
808 "__CFConstantStringClassReference",
809 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000810
811 // Decay array -> ptr
812 CFConstantStringClassRef =
813 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +0000814 }
815
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000816 std::vector<llvm::Constant*> Fields(4);
817
Anders Carlsson36a04872007-08-21 00:21:21 +0000818 // Class pointer.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000819 Fields[0] = CFConstantStringClassRef;
Anders Carlsson36a04872007-08-21 00:21:21 +0000820
821 // Flags.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000822 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
823 Fields[1] = llvm::ConstantInt::get(Ty, 0x07C8);
Anders Carlsson36a04872007-08-21 00:21:21 +0000824
825 // String pointer.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000826 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +0000827 C = new llvm::GlobalVariable(C->getType(), true,
828 llvm::GlobalValue::InternalLinkage,
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000829 C, ".str", &getModule());
830 Fields[2] = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +0000831
832 // String length.
833 Ty = getTypes().ConvertType(getContext().LongTy);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000834 Fields[3] = llvm::ConstantInt::get(Ty, str.length());
Anders Carlsson36a04872007-08-21 00:21:21 +0000835
836 // The struct.
837 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
838 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000839 llvm::GlobalVariable *GV =
840 new llvm::GlobalVariable(C->getType(), true,
841 llvm::GlobalVariable::InternalLinkage,
842 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000843
Anders Carlsson9be009e2007-11-01 00:41:52 +0000844 GV->setSection("__DATA,__cfstring");
845 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000846
Anders Carlsson9be009e2007-11-01 00:41:52 +0000847 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000848}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000849
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000850/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000851/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000852std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar952f4732008-08-29 17:28:43 +0000853 if (E->isWide()) {
854 ErrorUnsupported(E, "wide string");
855 return "FIXME";
856 }
857
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000858 const char *StrData = E->getStrData();
859 unsigned Len = E->getByteLength();
860
861 const ConstantArrayType *CAT =
862 getContext().getAsConstantArrayType(E->getType());
863 assert(CAT && "String isn't pointer or array!");
864
865 // Resize the string to the right size
866 // FIXME: What about wchar_t strings?
867 std::string Str(StrData, StrData+Len);
868 uint64_t RealLen = CAT->getSize().getZExtValue();
869 Str.resize(RealLen, '\0');
870
871 return Str;
872}
873
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000874/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
875/// constant array for the given string literal.
876llvm::Constant *
877CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
878 // FIXME: This can be more efficient.
879 return GetAddrOfConstantString(GetStringForStringLiteral(S));
880}
881
Chris Lattnera6dcce32008-02-11 00:02:17 +0000882/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000883static llvm::Constant *GenerateStringLiteral(const std::string &str,
884 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000885 CodeGenModule &CGM,
886 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000887 // Create Constant for this string literal. Don't add a '\0'.
888 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000889
890 // Create a global variable for this string
891 C = new llvm::GlobalVariable(C->getType(), constant,
892 llvm::GlobalValue::InternalLinkage,
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000893 C,
894 GlobalName ? GlobalName : ".str",
895 &CGM.getModule());
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000896
Chris Lattnerdb6be562007-11-28 05:34:05 +0000897 return C;
898}
899
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000900/// GetAddrOfConstantString - Returns a pointer to a character array
901/// containing the literal. This contents are exactly that of the
902/// given string, i.e. it will not be null terminated automatically;
903/// see GetAddrOfConstantCString. Note that whether the result is
904/// actually a pointer to an LLVM constant depends on
905/// Feature.WriteableStrings.
906///
907/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000908llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
909 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000910 // Don't share any string literals if writable-strings is turned on.
911 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000912 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000913
914 llvm::StringMapEntry<llvm::Constant *> &Entry =
915 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
916
917 if (Entry.getValue())
918 return Entry.getValue();
919
920 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000921 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000922 Entry.setValue(C);
923 return C;
924}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000925
926/// GetAddrOfConstantCString - Returns a pointer to a character
927/// array containing the literal and a terminating '\-'
928/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000929llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
930 const char *GlobalName){
931 return GetAddrOfConstantString(str + "\0", GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000932}
Daniel Dunbar27250d32008-08-15 23:26:23 +0000933
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000934/// EmitObjCPropertyImplementations - Emit information for synthesized
935/// properties for an implementation.
936void CodeGenModule::EmitObjCPropertyImplementations(const
937 ObjCImplementationDecl *D) {
938 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
939 e = D->propimpl_end(); i != e; ++i) {
940 ObjCPropertyImplDecl *PID = *i;
941
942 // Dynamic is just for type-checking.
943 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
944 ObjCPropertyDecl *PD = PID->getPropertyDecl();
945
946 // Determine which methods need to be implemented, some may have
947 // been overridden. Note that ::isSynthesized is not the method
948 // we want, that just indicates if the decl came from a
949 // property. What we want to know is if the method is defined in
950 // this implementation.
951 if (!D->getInstanceMethod(PD->getGetterName()))
952 CodeGenFunction(*this).GenerateObjCGetter(PID);
953 if (!PD->isReadOnly() &&
954 !D->getInstanceMethod(PD->getSetterName()))
955 CodeGenFunction(*this).GenerateObjCSetter(PID);
956 }
957 }
958}
959
Daniel Dunbar27250d32008-08-15 23:26:23 +0000960/// EmitTopLevelDecl - Emit code for a single top level declaration.
961void CodeGenModule::EmitTopLevelDecl(Decl *D) {
962 // If an error has occurred, stop code generation, but continue
963 // parsing and semantic analysis (to ensure all warnings and errors
964 // are emitted).
965 if (Diags.hasErrorOccurred())
966 return;
967
968 switch (D->getKind()) {
969 case Decl::Function:
970 case Decl::Var:
971 EmitGlobal(cast<ValueDecl>(D));
972 break;
973
974 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +0000975 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +0000976 break;
977
978 // Objective-C Decls
979
980 // Forward declarations, no (immediate) code generation.
981 case Decl::ObjCClass:
982 case Decl::ObjCCategory:
983 case Decl::ObjCForwardProtocol:
984 case Decl::ObjCInterface:
985 break;
986
987 case Decl::ObjCProtocol:
988 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
989 break;
990
991 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000992 // Categories have properties but don't support synthesize so we
993 // can ignore them here.
994
Daniel Dunbar27250d32008-08-15 23:26:23 +0000995 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
996 break;
997
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000998 case Decl::ObjCImplementation: {
999 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1000 EmitObjCPropertyImplementations(OMD);
1001 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001002 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001003 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001004 case Decl::ObjCMethod: {
1005 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1006 // If this is not a prototype, emit the body.
1007 if (OMD->getBody())
1008 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1009 break;
1010 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001011 case Decl::ObjCCompatibleAlias:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001012 ErrorUnsupported(D, "Objective-C compatible alias");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001013 break;
1014
1015 case Decl::LinkageSpec: {
1016 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1017 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001018 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001019 // FIXME: implement C++ linkage, C linkage works mostly by C
1020 // language reuse already.
1021 break;
1022 }
1023
1024 case Decl::FileScopeAsm: {
1025 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1026 std::string AsmString(AD->getAsmString()->getStrData(),
1027 AD->getAsmString()->getByteLength());
1028
1029 const std::string &S = getModule().getModuleInlineAsm();
1030 if (S.empty())
1031 getModule().setModuleInlineAsm(AsmString);
1032 else
1033 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1034 break;
1035 }
1036
1037 default:
1038 // Make sure we handled everything we should, every other kind is
1039 // a non-top-level decl. FIXME: Would be nice to have an
1040 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1041 // that easily.
1042 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1043 }
1044}
1045