blob: 7ea52deb2ad44c6057c9f720203b15d6616540aa [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.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000221 if (D->getAttr<DLLImportAttr>())
222 GV->setLinkage(llvm::Function::DLLImportLinkage);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000223 } else {
224 if (IsInternal) {
225 GV->setLinkage(llvm::Function::InternalLinkage);
226 } else {
227 if (D->getAttr<DLLImportAttr>())
228 GV->setLinkage(llvm::Function::DLLImportLinkage);
229 else if (D->getAttr<DLLExportAttr>())
230 GV->setLinkage(llvm::Function::DLLExportLinkage);
231 else if (D->getAttr<WeakAttr>() || IsInline)
232 GV->setLinkage(llvm::Function::WeakLinkage);
233 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000234 }
Nuno Lopes78534382008-06-08 15:45:52 +0000235
Daniel Dunbara8f02052008-09-08 21:33:45 +0000236 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000237 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000238 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000239
Daniel Dunbara8f02052008-09-08 21:33:45 +0000240 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbarced89142008-08-06 00:03:29 +0000241 // Prefaced with special LLVM marker to indicate that the name
242 // should not be munged.
243 GV->setName("\01" + ALA->getLabel());
244 }
Nuno Lopes78534382008-06-08 15:45:52 +0000245}
246
Devang Patela85a9ef2008-09-25 21:02:23 +0000247void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000248 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000249 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000250 AttributeListType AttributeList;
251 ConstructAttributeList(D, Info.argtypes_begin(), Info.argtypes_end(),
252 AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000253
Devang Patela85a9ef2008-09-25 21:02:23 +0000254 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
255 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000256
257 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000258 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000259 F->setCallingConv(llvm::CallingConv::X86_FastCall);
260
261 if (D->getAttr<StdCallAttr>())
262 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000263}
264
265/// SetFunctionAttributesForDefinition - Set function attributes
266/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000267void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
268 llvm::Function *F) {
269 if (isa<ObjCMethodDecl>(D)) {
270 SetGlobalValueAttributes(D, true, false, F, true);
271 } else {
272 const FunctionDecl *FD = cast<FunctionDecl>(D);
273 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
274 FD->isInline(), F, true);
275 }
276
Daniel Dunbarf2787002008-09-04 23:41:35 +0000277 if (!Features.Exceptions)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000278 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000279
280 if (D->getAttr<AlwaysInlineAttr>())
281 F->addFnAttr(llvm::Attribute::AlwaysInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000282}
283
284void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
285 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000286 SetFunctionAttributes(MD, CGFunctionInfo(MD, Context), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000287
Daniel Dunbar566a6502008-09-08 23:44:31 +0000288 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000289}
290
291void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
292 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000293 SetFunctionAttributes(FD, CGFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000294
Daniel Dunbar566a6502008-09-08 23:44:31 +0000295 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
296 FD->isInline(), F, false);
297}
298
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000299
Daniel Dunbar566a6502008-09-08 23:44:31 +0000300void CodeGenModule::EmitAliases() {
301 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
302 const FunctionDecl *D = Aliases[i];
303 const AliasAttr *AA = D->getAttr<AliasAttr>();
304
305 // This is something of a hack, if the FunctionDecl got overridden
306 // then its attributes will be moved to the new declaration. In
307 // this case the current decl has no alias attribute, but we will
308 // eventually see it.
309 if (!AA)
310 continue;
311
312 const std::string& aliaseeName = AA->getAliasee();
313 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
314 if (!aliasee) {
315 // FIXME: This isn't unsupported, this is just an error, which
316 // sema should catch, but...
317 ErrorUnsupported(D, "alias referencing a missing function");
318 continue;
319 }
320
321 llvm::GlobalValue *GA =
322 new llvm::GlobalAlias(aliasee->getType(),
323 llvm::Function::ExternalLinkage,
324 D->getName(),
325 aliasee,
326 &getModule());
327
328 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
329 if (Entry) {
330 // If we created a dummy function for this then replace it.
331 GA->takeName(Entry);
332
333 llvm::Value *Casted =
334 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
335 Entry->replaceAllUsesWith(Casted);
336 Entry->eraseFromParent();
337
338 Entry = GA;
339 }
340
341 // Alias should never be internal or inline.
342 SetGlobalValueAttributes(D, false, false, GA, true);
343 }
Eli Friedman9be42212008-06-01 15:54:49 +0000344}
345
Nate Begemanad320b62008-04-20 06:29:50 +0000346void CodeGenModule::EmitStatics() {
347 // Emit code for each used static decl encountered. Since a previously unused
348 // static decl may become used during the generation of code for a static
349 // function, iterate until no changes are made.
350 bool Changed;
351 do {
352 Changed = false;
353 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000354 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000355
356 // Check if we have used a decl with the same name
357 // FIXME: The AST should have some sort of aggregate decls or
358 // global symbol map.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000359 // FIXME: This is missing some important cases. For example, we
360 // need to check for uses in an alias and in a constructor.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000361 if (!GlobalDeclMap.count(D->getIdentifier()))
Daniel Dunbarced89142008-08-06 00:03:29 +0000362 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000363
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000364 // Emit the definition.
365 EmitGlobalDefinition(D);
366
Nate Begemanad320b62008-04-20 06:29:50 +0000367 // Erase the used decl from the list.
368 StaticDecls[i] = StaticDecls.back();
369 StaticDecls.pop_back();
370 --i;
371 --e;
372
373 // Remember that we made a change.
374 Changed = true;
375 }
376 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000377}
378
Nate Begeman8a704172008-04-19 04:17:09 +0000379/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
380/// annotation information for a given GlobalValue. The annotation struct is
381/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000382/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000383/// created from the AnnotateAttr's annotation. The third field is a constant
384/// string containing the name of the translation unit. The fourth field is
385/// the line number in the file of the annotated value declaration.
386///
387/// FIXME: this does not unique the annotation string constants, as llvm-gcc
388/// appears to.
389///
390llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
391 const AnnotateAttr *AA,
392 unsigned LineNo) {
393 llvm::Module *M = &getModule();
394
395 // get [N x i8] constants for the annotation string, and the filename string
396 // which are the 2nd and 3rd elements of the global annotation structure.
397 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
398 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
399 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
400 true);
401
402 // Get the two global values corresponding to the ConstantArrays we just
403 // created to hold the bytes of the strings.
404 llvm::GlobalValue *annoGV =
405 new llvm::GlobalVariable(anno->getType(), false,
406 llvm::GlobalValue::InternalLinkage, anno,
407 GV->getName() + ".str", M);
408 // translation unit name string, emitted into the llvm.metadata section.
409 llvm::GlobalValue *unitGV =
410 new llvm::GlobalVariable(unit->getType(), false,
411 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
412
413 // Create the ConstantStruct that is the global annotion.
414 llvm::Constant *Fields[4] = {
415 llvm::ConstantExpr::getBitCast(GV, SBP),
416 llvm::ConstantExpr::getBitCast(annoGV, SBP),
417 llvm::ConstantExpr::getBitCast(unitGV, SBP),
418 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
419 };
420 return llvm::ConstantStruct::get(Fields, 4, false);
421}
422
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000423void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
424 bool isDef, isStatic;
425
426 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000427 // Aliases are deferred until code for everything else has been
428 // emitted.
429 if (FD->getAttr<AliasAttr>()) {
430 assert(!FD->isThisDeclarationADefinition() &&
431 "Function alias cannot have a definition!");
432 Aliases.push_back(FD);
433 return;
434 }
435
436 isDef = FD->isThisDeclarationADefinition();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000437 isStatic = FD->getStorageClass() == FunctionDecl::Static;
438 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
439 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
440
441 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
442 isStatic = VD->getStorageClass() == VarDecl::Static;
443 } else {
444 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000445 return;
446 }
447
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000448 // Forward declarations are emitted lazily on first use.
449 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000450 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000451
452 // If the global is a static, defer code generation until later so
453 // we can easily omit unused statics.
454 if (isStatic) {
455 StaticDecls.push_back(Global);
456 return;
457 }
458
459 // Otherwise emit the definition.
460 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000461}
462
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000463void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
464 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
465 EmitGlobalFunctionDefinition(FD);
466 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
467 EmitGlobalVarDefinition(VD);
468 } else {
469 assert(0 && "Invalid argument to EmitGlobalDefinition()");
470 }
471}
472
Daniel Dunbar2188c532008-07-30 16:32:24 +0000473 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000474 assert(D->hasGlobalStorage() && "Not a global variable");
475
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000476 QualType ASTTy = D->getType();
477 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000478 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000479
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000480 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000481 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000482 if (!Entry)
483 Entry = new llvm::GlobalVariable(Ty, false,
484 llvm::GlobalValue::ExternalLinkage,
485 0, D->getName(), &getModule(), 0,
486 ASTTy.getAddressSpace());
487
Daniel Dunbar2188c532008-07-30 16:32:24 +0000488 // Make sure the result is of the correct type.
489 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000490}
491
492void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000493 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000494 QualType ASTTy = D->getType();
495 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000496
Chris Lattner4b009652007-07-25 00:24:17 +0000497 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000498 // This is a tentative definition; tentative definitions are
499 // implicitly initialized with { 0 }
500 const llvm::Type* InitTy;
501 if (ASTTy->isIncompleteArrayType()) {
502 // An incomplete array is normally [ TYPE x 0 ], but we need
503 // to fix it to [ TYPE x 1 ].
504 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
505 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
506 } else {
507 InitTy = VarTy;
508 }
509 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000510 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000511 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000512 }
513 const llvm::Type* InitType = Init->getType();
514
Daniel Dunbarad30be42008-08-25 06:18:57 +0000515 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000516 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
517
Eli Friedman43a0ce82008-05-30 19:50:47 +0000518 if (!GV) {
519 GV = new llvm::GlobalVariable(InitType, false,
520 llvm::GlobalValue::ExternalLinkage,
521 0, D->getName(), &getModule(), 0,
522 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000523 } else if (GV->getType() !=
524 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000525 // We have a definition after a prototype with the wrong type.
526 // We must make a new GlobalVariable* and update everything that used OldGV
527 // (a declaration or tentative definition) with the new GlobalVariable*
528 // (which will be a definition).
529 //
530 // This happens if there is a prototype for a global (e.g. "extern int x[];")
531 // and then a definition of a different type (e.g. "int x[10];"). This also
532 // happens when an initializer has a different type from the type of the
533 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000534 //
535 // FIXME: This also ends up happening if there's a definition followed by
536 // a tentative definition! (Although Sema rejects that construct
537 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000538
539 // Save the old global
540 llvm::GlobalVariable *OldGV = GV;
541
542 // Make a new global with the correct type
543 GV = new llvm::GlobalVariable(InitType, false,
544 llvm::GlobalValue::ExternalLinkage,
545 0, D->getName(), &getModule(), 0,
546 ASTTy.getAddressSpace());
547 // Steal the name of the old global
548 GV->takeName(OldGV);
549
550 // Replace all uses of the old global with the new global
551 llvm::Constant *NewPtrForOldDecl =
552 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
553 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000554
555 // Erase the old global, since it is no longer used.
556 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000557 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000558
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000559 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000560
Nate Begeman8a704172008-04-19 04:17:09 +0000561 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
562 SourceManager &SM = Context.getSourceManager();
563 AddAnnotation(EmitAnnotateAttr(GV, AA,
564 SM.getLogicalLineNumber(D->getLocation())));
565 }
566
Chris Lattner4b009652007-07-25 00:24:17 +0000567 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000568 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner402b3372008-03-03 03:28:21 +0000569
Eli Friedman7008e9a2008-05-30 20:39:54 +0000570 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
571 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000572 if (const IncompleteArrayType* IAT =
573 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000574 Align = Context.getTypeAlign(IAT->getElementType());
575 else
576 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000577 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
578 Align = std::max(Align, AA->getAlignment());
579 }
580 GV->setAlignment(Align / 8);
581
Chris Lattner402b3372008-03-03 03:28:21 +0000582 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000583 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000584 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000585
586 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
587 // Prefaced with special LLVM marker to indicate that the name
588 // should not be munged.
589 GV->setName("\01" + ALA->getLabel());
590 }
Chris Lattner4b009652007-07-25 00:24:17 +0000591
592 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000593 if (D->getStorageClass() == VarDecl::Static)
594 GV->setLinkage(llvm::Function::InternalLinkage);
595 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000596 GV->setLinkage(llvm::Function::DLLImportLinkage);
597 else if (D->getAttr<DLLExportAttr>())
598 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000599 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000600 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000601 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000602 // FIXME: This isn't right. This should handle common linkage and other
603 // stuff.
604 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000605 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000606 case VarDecl::Auto:
607 case VarDecl::Register:
608 assert(0 && "Can't have auto or register globals");
609 case VarDecl::None:
610 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000611 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000612 break;
613 case VarDecl::Extern:
614 case VarDecl::PrivateExtern:
615 // todo: common
616 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000617 }
Chris Lattner4b009652007-07-25 00:24:17 +0000618 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000619
620 // Emit global variable debug information.
621 CGDebugInfo *DI = getDebugInfo();
622 if(DI) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000623 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000624 DI->EmitGlobalVariable(GV, D);
625 }
Chris Lattner4b009652007-07-25 00:24:17 +0000626}
627
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000628llvm::GlobalValue *
629CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000630 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
631 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
632 llvm::Function::ExternalLinkage,
633 D->getName(), &getModule());
634 SetFunctionAttributes(D, F);
635 return F;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000636}
637
638llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000639 QualType ASTTy = D->getType();
640 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
641 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000642
643 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000644 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000645 if (!Entry)
646 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000647
Daniel Dunbar2188c532008-07-30 16:32:24 +0000648 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000649}
650
651void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbarad30be42008-08-25 06:18:57 +0000652 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000653 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000654 Entry = EmitForwardFunctionDefinition(D);
655 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000656 // If the types mismatch then we have to rewrite the definition.
657 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
658 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000659 // Otherwise, we have a definition after a prototype with the wrong type.
660 // F is the Function* for the one with the wrong type, we must make a new
661 // Function* and update everything that used F (a declaration) with the new
662 // Function* (which will be a definition).
663 //
664 // This happens if there is a prototype for a function (e.g. "int f()") and
665 // then a definition of a different type (e.g. "int f(int x)"). Start by
666 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000667 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
668 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000669
670 // Replace uses of F with the Function we will endow with a body.
671 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000672 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
673 Entry->replaceAllUsesWith(NewPtrForOldDecl);
674
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000675 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000676 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar566a6502008-09-08 23:44:31 +0000677 Entry->eraseFromParent();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000678
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000679 Entry = NewFn;
680 }
681 }
682
Daniel Dunbar566a6502008-09-08 23:44:31 +0000683 llvm::Function *Fn = cast<llvm::Function>(Entry);
684 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000685
Daniel Dunbar566a6502008-09-08 23:44:31 +0000686 SetFunctionAttributesForDefinition(D, Fn);
687
688 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
689 AddGlobalCtor(Fn, CA->getPriority());
690 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
691 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000692 }
693}
694
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000695llvm::Function *
696CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
697 const std::string &Name) {
698 llvm::Function *Fn = llvm::Function::Create(FTy,
699 llvm::Function::ExternalLinkage,
700 "", &TheModule);
701 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
702 return Fn;
703}
704
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000705void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
706 // Make sure that this type is translated.
707 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000708}
709
710
Chris Lattnerab862cc2007-08-31 04:31:45 +0000711/// getBuiltinLibFunction
712llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000713 if (BuiltinID > BuiltinFunctions.size())
714 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000715
Chris Lattner9f2d6892007-12-13 00:38:03 +0000716 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
717 // a slot for it.
718 assert(BuiltinID && "Invalid Builtin ID");
719 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000720 if (FunctionSlot)
721 return FunctionSlot;
722
723 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
724
725 // Get the name, skip over the __builtin_ prefix.
726 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
727
728 // Get the type for the builtin.
729 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
730 const llvm::FunctionType *Ty =
731 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
732
733 // FIXME: This has a serious problem with code like this:
734 // void abs() {}
735 // ... __builtin_abs(x);
736 // The two versions of abs will collide. The fix is for the builtin to win,
737 // and for the existing one to be turned into a constantexpr cast of the
738 // builtin. In the case where the existing one is a static function, it
739 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000740 if (llvm::Function *Existing = getModule().getFunction(Name)) {
741 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
742 return FunctionSlot = Existing;
743 assert(Existing == 0 && "FIXME: Name collision");
744 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000745
746 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000747 return FunctionSlot =
748 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
749 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000750}
751
Chris Lattner4b23f942007-12-18 00:25:38 +0000752llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
753 unsigned NumTys) {
754 return llvm::Intrinsic::getDeclaration(&getModule(),
755 (llvm::Intrinsic::ID)IID, Tys, NumTys);
756}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000757
Chris Lattner4b009652007-07-25 00:24:17 +0000758llvm::Function *CodeGenModule::getMemCpyFn() {
759 if (MemCpyFn) return MemCpyFn;
760 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000761 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000762 default: assert(0 && "Unknown ptr width");
Sanjiv Guptae6b85312008-11-19 09:02:07 +0000763 case 16: IID = llvm::Intrinsic::memcpy_i16; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000764 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
765 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
766 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000767 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000768}
Anders Carlsson36a04872007-08-21 00:21:21 +0000769
Eli Friedman8f08a252008-05-26 12:59:39 +0000770llvm::Function *CodeGenModule::getMemMoveFn() {
771 if (MemMoveFn) return MemMoveFn;
772 llvm::Intrinsic::ID IID;
773 switch (Context.Target.getPointerWidth(0)) {
774 default: assert(0 && "Unknown ptr width");
Sanjiv Guptae6b85312008-11-19 09:02:07 +0000775 case 16: IID = llvm::Intrinsic::memmove_i16; break;
Eli Friedman8f08a252008-05-26 12:59:39 +0000776 case 32: IID = llvm::Intrinsic::memmove_i32; break;
777 case 64: IID = llvm::Intrinsic::memmove_i64; break;
778 }
779 return MemMoveFn = getIntrinsic(IID);
780}
781
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000782llvm::Function *CodeGenModule::getMemSetFn() {
783 if (MemSetFn) return MemSetFn;
784 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000785 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000786 default: assert(0 && "Unknown ptr width");
Sanjiv Guptae6b85312008-11-19 09:02:07 +0000787 case 16: IID = llvm::Intrinsic::memset_i16; break;
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000788 case 32: IID = llvm::Intrinsic::memset_i32; break;
789 case 64: IID = llvm::Intrinsic::memset_i64; break;
790 }
791 return MemSetFn = getIntrinsic(IID);
792}
Chris Lattner4b23f942007-12-18 00:25:38 +0000793
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000794static void appendFieldAndPadding(CodeGenModule &CGM,
795 std::vector<llvm::Constant*>& Fields,
796 int FieldNo, llvm::Constant* Field,
797 RecordDecl* RD, const llvm::StructType *STy)
798{
799 // Append the field.
800 Fields.push_back(Field);
801
802 int StructFieldNo =
803 CGM.getTypes().getLLVMFieldNo(RD->getMember(FieldNo));
804
805 int NextStructFieldNo;
806 if (FieldNo + 1 == RD->getNumMembers()) {
807 NextStructFieldNo = STy->getNumElements();
808 } else {
809 NextStructFieldNo =
810 CGM.getTypes().getLLVMFieldNo(RD->getMember(FieldNo + 1));
811 }
812
813 // Append padding
814 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
815 llvm::Constant *C =
816 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
817
818 Fields.push_back(C);
819 }
820}
821
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000822// We still need to work out the details of handling UTF-16.
823// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +0000824llvm::Constant *CodeGenModule::
825GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000826 llvm::StringMapEntry<llvm::Constant *> &Entry =
827 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
828
829 if (Entry.getValue())
830 return Entry.getValue();
831
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000832 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
833 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +0000834
835 if (!CFConstantStringClassRef) {
836 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
837 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000838
839 // FIXME: This is fairly broken if
840 // __CFConstantStringClassReference is already defined, in that it
841 // will get renamed and the user will most likely see an opaque
842 // error message. This is a general issue with relying on
843 // particular names.
844 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +0000845 new llvm::GlobalVariable(Ty, false,
846 llvm::GlobalVariable::ExternalLinkage, 0,
847 "__CFConstantStringClassReference",
848 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000849
850 // Decay array -> ptr
851 CFConstantStringClassRef =
852 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +0000853 }
854
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000855 QualType CFTy = getContext().getCFConstantStringType();
856 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000857
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000858 const llvm::StructType *STy =
859 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
860
861 std::vector<llvm::Constant*> Fields;
862
863
Anders Carlsson36a04872007-08-21 00:21:21 +0000864 // Class pointer.
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000865 appendFieldAndPadding(*this, Fields, 0, CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000866
867 // Flags.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000868 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000869 appendFieldAndPadding(*this, Fields, 1, llvm::ConstantInt::get(Ty, 0x07C8),
870 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000871
872 // String pointer.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000873 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +0000874 C = new llvm::GlobalVariable(C->getType(), true,
875 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000876 C, ".str", &getModule());
877 appendFieldAndPadding(*this, Fields, 2,
878 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
879 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000880
881 // String length.
882 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000883 appendFieldAndPadding(*this, Fields, 3, llvm::ConstantInt::get(Ty, str.length()),
884 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +0000885
886 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000887 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000888 llvm::GlobalVariable *GV =
889 new llvm::GlobalVariable(C->getType(), true,
890 llvm::GlobalVariable::InternalLinkage,
891 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000892
Anders Carlsson9be009e2007-11-01 00:41:52 +0000893 GV->setSection("__DATA,__cfstring");
894 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000895
Anders Carlsson9be009e2007-11-01 00:41:52 +0000896 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000897}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000898
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000899/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000900/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000901std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar952f4732008-08-29 17:28:43 +0000902 if (E->isWide()) {
903 ErrorUnsupported(E, "wide string");
904 return "FIXME";
905 }
906
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000907 const char *StrData = E->getStrData();
908 unsigned Len = E->getByteLength();
909
910 const ConstantArrayType *CAT =
911 getContext().getAsConstantArrayType(E->getType());
912 assert(CAT && "String isn't pointer or array!");
913
914 // Resize the string to the right size
915 // FIXME: What about wchar_t strings?
916 std::string Str(StrData, StrData+Len);
917 uint64_t RealLen = CAT->getSize().getZExtValue();
918 Str.resize(RealLen, '\0');
919
920 return Str;
921}
922
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000923/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
924/// constant array for the given string literal.
925llvm::Constant *
926CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
927 // FIXME: This can be more efficient.
928 return GetAddrOfConstantString(GetStringForStringLiteral(S));
929}
930
Chris Lattnera6dcce32008-02-11 00:02:17 +0000931/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000932static llvm::Constant *GenerateStringLiteral(const std::string &str,
933 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000934 CodeGenModule &CGM,
935 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000936 // Create Constant for this string literal. Don't add a '\0'.
937 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000938
939 // Create a global variable for this string
940 C = new llvm::GlobalVariable(C->getType(), constant,
941 llvm::GlobalValue::InternalLinkage,
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000942 C,
943 GlobalName ? GlobalName : ".str",
944 &CGM.getModule());
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000945
Chris Lattnerdb6be562007-11-28 05:34:05 +0000946 return C;
947}
948
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000949/// GetAddrOfConstantString - Returns a pointer to a character array
950/// containing the literal. This contents are exactly that of the
951/// given string, i.e. it will not be null terminated automatically;
952/// see GetAddrOfConstantCString. Note that whether the result is
953/// actually a pointer to an LLVM constant depends on
954/// Feature.WriteableStrings.
955///
956/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000957llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
958 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000959 // Don't share any string literals if writable-strings is turned on.
960 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000961 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000962
963 llvm::StringMapEntry<llvm::Constant *> &Entry =
964 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
965
966 if (Entry.getValue())
967 return Entry.getValue();
968
969 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000970 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000971 Entry.setValue(C);
972 return C;
973}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000974
975/// GetAddrOfConstantCString - Returns a pointer to a character
976/// array containing the literal and a terminating '\-'
977/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +0000978llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
979 const char *GlobalName){
980 return GetAddrOfConstantString(str + "\0", GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000981}
Daniel Dunbar27250d32008-08-15 23:26:23 +0000982
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000983/// EmitObjCPropertyImplementations - Emit information for synthesized
984/// properties for an implementation.
985void CodeGenModule::EmitObjCPropertyImplementations(const
986 ObjCImplementationDecl *D) {
987 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
988 e = D->propimpl_end(); i != e; ++i) {
989 ObjCPropertyImplDecl *PID = *i;
990
991 // Dynamic is just for type-checking.
992 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
993 ObjCPropertyDecl *PD = PID->getPropertyDecl();
994
995 // Determine which methods need to be implemented, some may have
996 // been overridden. Note that ::isSynthesized is not the method
997 // we want, that just indicates if the decl came from a
998 // property. What we want to know is if the method is defined in
999 // this implementation.
1000 if (!D->getInstanceMethod(PD->getGetterName()))
1001 CodeGenFunction(*this).GenerateObjCGetter(PID);
1002 if (!PD->isReadOnly() &&
1003 !D->getInstanceMethod(PD->getSetterName()))
1004 CodeGenFunction(*this).GenerateObjCSetter(PID);
1005 }
1006 }
1007}
1008
Daniel Dunbar27250d32008-08-15 23:26:23 +00001009/// EmitTopLevelDecl - Emit code for a single top level declaration.
1010void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1011 // If an error has occurred, stop code generation, but continue
1012 // parsing and semantic analysis (to ensure all warnings and errors
1013 // are emitted).
1014 if (Diags.hasErrorOccurred())
1015 return;
1016
1017 switch (D->getKind()) {
1018 case Decl::Function:
1019 case Decl::Var:
1020 EmitGlobal(cast<ValueDecl>(D));
1021 break;
1022
1023 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001024 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001025 break;
1026
1027 // Objective-C Decls
1028
1029 // Forward declarations, no (immediate) code generation.
1030 case Decl::ObjCClass:
1031 case Decl::ObjCCategory:
1032 case Decl::ObjCForwardProtocol:
1033 case Decl::ObjCInterface:
1034 break;
1035
1036 case Decl::ObjCProtocol:
1037 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1038 break;
1039
1040 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001041 // Categories have properties but don't support synthesize so we
1042 // can ignore them here.
1043
Daniel Dunbar27250d32008-08-15 23:26:23 +00001044 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1045 break;
1046
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001047 case Decl::ObjCImplementation: {
1048 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1049 EmitObjCPropertyImplementations(OMD);
1050 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001051 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001052 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001053 case Decl::ObjCMethod: {
1054 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1055 // If this is not a prototype, emit the body.
1056 if (OMD->getBody())
1057 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1058 break;
1059 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001060 case Decl::ObjCCompatibleAlias:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001061 ErrorUnsupported(D, "Objective-C compatible alias");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001062 break;
1063
1064 case Decl::LinkageSpec: {
1065 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1066 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001067 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001068 // FIXME: implement C++ linkage, C linkage works mostly by C
1069 // language reuse already.
1070 break;
1071 }
1072
1073 case Decl::FileScopeAsm: {
1074 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1075 std::string AsmString(AD->getAsmString()->getStrData(),
1076 AD->getAsmString()->getByteLength());
1077
1078 const std::string &S = getModule().getModuleInlineAsm();
1079 if (S.empty())
1080 getModule().setModuleInlineAsm(AsmString);
1081 else
1082 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1083 break;
1084 }
1085
1086 default:
1087 // Make sure we handled everything we should, every other kind is
1088 // a non-top-level decl. FIXME: Would be nice to have an
1089 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1090 // that easily.
1091 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1092 }
1093}
1094