blob: 186720724801ff5c44b41c1c073306f2c8fd7a22 [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 Dunbar84bb85f2008-08-13 00:59:25 +000017#include "CGObjCRuntime.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000020#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000023#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000024#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000026#include "llvm/Target/TargetData.h"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000027#include "llvm/Analysis/Verifier.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 Dunbarfc69bde2008-08-11 18:12:00 +000058 if (Runtime)
59 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
60 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000061 EmitCtorList(GlobalCtors, "llvm.global_ctors");
62 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000063 EmitAnnotations();
Chris Lattnerb033c4a2008-04-30 16:05:42 +000064 // Run the verifier to check that the generated code is consistent.
65 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000066}
Chris Lattner4b009652007-07-25 00:24:17 +000067
Daniel Dunbar9503b782008-08-16 00:56:44 +000068/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +000069/// specified stmt yet.
Daniel Dunbar9503b782008-08-16 00:56:44 +000070void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
71 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattnercf9c9d02007-12-02 07:19:18 +000072 "cannot codegen this %0 yet");
73 SourceRange Range = S->getSourceRange();
74 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000075 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000076 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000077}
Chris Lattner0e4755d2007-12-02 06:27:33 +000078
Daniel Dunbar9503b782008-08-16 00:56:44 +000079/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +000080/// specified decl yet.
Daniel Dunbar9503b782008-08-16 00:56:44 +000081void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
82 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner806a5f52008-01-12 07:05:38 +000083 "cannot codegen this %0 yet");
84 std::string Msg = Type;
85 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
86 &Msg, 1);
87}
88
Daniel Dunbar27250d32008-08-15 23:26:23 +000089/// setGlobalVisibility - Set the visibility for the given LLVM
90/// GlobalValue according to the given clang AST visibility value.
91static void setGlobalVisibility(llvm::GlobalValue *GV,
92 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4751a3a2008-05-22 00:50:06 +000093 switch (Vis) {
94 default: assert(0 && "Unknown visibility!");
95 case VisibilityAttr::DefaultVisibility:
96 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
97 break;
98 case VisibilityAttr::HiddenVisibility:
99 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
100 break;
101 case VisibilityAttr::ProtectedVisibility:
102 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
103 break;
104 }
105}
106
Chris Lattner753d2592008-03-14 17:18:18 +0000107/// AddGlobalCtor - Add a function to the list that will be called before
108/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000109void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner753d2592008-03-14 17:18:18 +0000110 // TODO: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000111 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000112}
113
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000114/// AddGlobalDtor - Add a function to the list that will be called
115/// when the module is unloaded.
116void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
117 // TODO: Type coercion of void()* types.
118 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
119}
120
121void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
122 // Ctor function type is void()*.
123 llvm::FunctionType* CtorFTy =
124 llvm::FunctionType::get(llvm::Type::VoidTy,
125 std::vector<const llvm::Type*>(),
126 false);
127 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
128
129 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000130 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000131 llvm::StructType::get(llvm::Type::Int32Ty,
132 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000133
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000134 // Construct the constructor and destructor arrays.
135 std::vector<llvm::Constant*> Ctors;
136 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
137 std::vector<llvm::Constant*> S;
138 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
139 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
140 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000141 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000142
143 if (!Ctors.empty()) {
144 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
145 new llvm::GlobalVariable(AT, false,
146 llvm::GlobalValue::AppendingLinkage,
147 llvm::ConstantArray::get(AT, Ctors),
148 GlobalName,
149 &TheModule);
150 }
Chris Lattner753d2592008-03-14 17:18:18 +0000151}
152
Nate Begeman52da5c72008-04-18 23:43:57 +0000153void CodeGenModule::EmitAnnotations() {
154 if (Annotations.empty())
155 return;
156
157 // Create a new global variable for the ConstantStruct in the Module.
158 llvm::Constant *Array =
159 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
160 Annotations.size()),
161 Annotations);
162 llvm::GlobalValue *gv =
163 new llvm::GlobalVariable(Array->getType(), false,
164 llvm::GlobalValue::AppendingLinkage, Array,
165 "llvm.global.annotations", &TheModule);
166 gv->setSection("llvm.metadata");
167}
168
Eli Friedman9be42212008-06-01 15:54:49 +0000169bool hasAggregateLLVMType(QualType T) {
170 return !T->isRealType() && !T->isPointerLikeType() &&
171 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
172}
173
Nuno Lopes78534382008-06-08 15:45:52 +0000174void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
175 llvm::GlobalValue *GV) {
176 // TODO: Set up linkage and many other things. Note, this is a simple
177 // approximation of what we really want.
178 if (FD->getStorageClass() == FunctionDecl::Static)
179 GV->setLinkage(llvm::Function::InternalLinkage);
180 else if (FD->getAttr<DLLImportAttr>())
181 GV->setLinkage(llvm::Function::DLLImportLinkage);
182 else if (FD->getAttr<DLLExportAttr>())
183 GV->setLinkage(llvm::Function::DLLExportLinkage);
184 else if (FD->getAttr<WeakAttr>() || FD->isInline())
185 GV->setLinkage(llvm::Function::WeakLinkage);
186
187 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000188 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000189 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000190
191 if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) {
192 // Prefaced with special LLVM marker to indicate that the name
193 // should not be munged.
194 GV->setName("\01" + ALA->getLabel());
195 }
Nuno Lopes78534382008-06-08 15:45:52 +0000196}
197
Eli Friedman9be42212008-06-01 15:54:49 +0000198void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
199 llvm::Function *F,
200 const llvm::FunctionType *FTy) {
201 unsigned FuncAttrs = 0;
202 if (FD->getAttr<NoThrowAttr>())
203 FuncAttrs |= llvm::ParamAttr::NoUnwind;
204 if (FD->getAttr<NoReturnAttr>())
205 FuncAttrs |= llvm::ParamAttr::NoReturn;
206
207 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
208 if (FuncAttrs)
209 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
210 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
211 bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
212 if (AggregateReturn)
213 ParamAttrList.push_back(
214 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
215 unsigned increment = AggregateReturn ? 2 : 1;
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000216 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
217 if (FTP) {
218 for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
219 QualType ParamType = FTP->getArgType(i);
220 unsigned ParamAttrs = 0;
221 if (ParamType->isRecordType())
222 ParamAttrs |= llvm::ParamAttr::ByVal;
Chris Lattner578279d2008-06-26 05:08:00 +0000223 if (ParamType->isSignedIntegerType() &&
224 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000225 ParamAttrs |= llvm::ParamAttr::SExt;
Chris Lattner578279d2008-06-26 05:08:00 +0000226 if (ParamType->isUnsignedIntegerType() &&
227 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000228 ParamAttrs |= llvm::ParamAttr::ZExt;
229 if (ParamAttrs)
230 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
231 ParamAttrs));
232 }
Eli Friedman9be42212008-06-01 15:54:49 +0000233 }
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000234
Eli Friedman9be42212008-06-01 15:54:49 +0000235 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
236 ParamAttrList.size()));
237
238 // Set the appropriate calling convention for the Function.
239 if (FD->getAttr<FastCallAttr>())
240 F->setCallingConv(llvm::CallingConv::Fast);
241
Nuno Lopes78534382008-06-08 15:45:52 +0000242 SetGlobalValueAttributes(FD, F);
Eli Friedman9be42212008-06-01 15:54:49 +0000243}
244
Nate Begemanad320b62008-04-20 06:29:50 +0000245void CodeGenModule::EmitStatics() {
246 // Emit code for each used static decl encountered. Since a previously unused
247 // static decl may become used during the generation of code for a static
248 // function, iterate until no changes are made.
249 bool Changed;
250 do {
251 Changed = false;
252 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000253 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000254
255 // Check if we have used a decl with the same name
256 // FIXME: The AST should have some sort of aggregate decls or
257 // global symbol map.
Daniel Dunbarced89142008-08-06 00:03:29 +0000258 if (!GlobalDeclMap.count(D->getName()))
259 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000260
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000261 // Emit the definition.
262 EmitGlobalDefinition(D);
263
Nate Begemanad320b62008-04-20 06:29:50 +0000264 // Erase the used decl from the list.
265 StaticDecls[i] = StaticDecls.back();
266 StaticDecls.pop_back();
267 --i;
268 --e;
269
270 // Remember that we made a change.
271 Changed = true;
272 }
273 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000274}
275
Nate Begeman8a704172008-04-19 04:17:09 +0000276/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
277/// annotation information for a given GlobalValue. The annotation struct is
278/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000279/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000280/// created from the AnnotateAttr's annotation. The third field is a constant
281/// string containing the name of the translation unit. The fourth field is
282/// the line number in the file of the annotated value declaration.
283///
284/// FIXME: this does not unique the annotation string constants, as llvm-gcc
285/// appears to.
286///
287llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
288 const AnnotateAttr *AA,
289 unsigned LineNo) {
290 llvm::Module *M = &getModule();
291
292 // get [N x i8] constants for the annotation string, and the filename string
293 // which are the 2nd and 3rd elements of the global annotation structure.
294 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
295 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
296 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
297 true);
298
299 // Get the two global values corresponding to the ConstantArrays we just
300 // created to hold the bytes of the strings.
301 llvm::GlobalValue *annoGV =
302 new llvm::GlobalVariable(anno->getType(), false,
303 llvm::GlobalValue::InternalLinkage, anno,
304 GV->getName() + ".str", M);
305 // translation unit name string, emitted into the llvm.metadata section.
306 llvm::GlobalValue *unitGV =
307 new llvm::GlobalVariable(unit->getType(), false,
308 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
309
310 // Create the ConstantStruct that is the global annotion.
311 llvm::Constant *Fields[4] = {
312 llvm::ConstantExpr::getBitCast(GV, SBP),
313 llvm::ConstantExpr::getBitCast(annoGV, SBP),
314 llvm::ConstantExpr::getBitCast(unitGV, SBP),
315 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
316 };
317 return llvm::ConstantStruct::get(Fields, 4, false);
318}
319
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000320void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
321 bool isDef, isStatic;
322
323 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
324 isDef = (FD->isThisDeclarationADefinition() ||
325 FD->getAttr<AliasAttr>());
326 isStatic = FD->getStorageClass() == FunctionDecl::Static;
327 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
328 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
329
330 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
331 isStatic = VD->getStorageClass() == VarDecl::Static;
332 } else {
333 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000334 return;
335 }
336
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000337 // Forward declarations are emitted lazily on first use.
338 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000339 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000340
341 // If the global is a static, defer code generation until later so
342 // we can easily omit unused statics.
343 if (isStatic) {
344 StaticDecls.push_back(Global);
345 return;
346 }
347
348 // Otherwise emit the definition.
349 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000350}
351
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000352void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
353 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
354 EmitGlobalFunctionDefinition(FD);
355 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
356 EmitGlobalVarDefinition(VD);
357 } else {
358 assert(0 && "Invalid argument to EmitGlobalDefinition()");
359 }
360}
361
Daniel Dunbar2188c532008-07-30 16:32:24 +0000362 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000363 assert(D->hasGlobalStorage() && "Not a global variable");
364
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000365 QualType ASTTy = D->getType();
366 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000367 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000368
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000369 // Lookup the entry, lazily creating it if necessary.
370 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
371 if (!Entry)
372 Entry = new llvm::GlobalVariable(Ty, false,
373 llvm::GlobalValue::ExternalLinkage,
374 0, D->getName(), &getModule(), 0,
375 ASTTy.getAddressSpace());
376
Daniel Dunbar2188c532008-07-30 16:32:24 +0000377 // Make sure the result is of the correct type.
378 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000379}
380
381void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000382 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000383 QualType ASTTy = D->getType();
384 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000385
Chris Lattner4b009652007-07-25 00:24:17 +0000386 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000387 // This is a tentative definition; tentative definitions are
388 // implicitly initialized with { 0 }
389 const llvm::Type* InitTy;
390 if (ASTTy->isIncompleteArrayType()) {
391 // An incomplete array is normally [ TYPE x 0 ], but we need
392 // to fix it to [ TYPE x 1 ].
393 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
394 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
395 } else {
396 InitTy = VarTy;
397 }
398 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000399 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000400 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000401 }
402 const llvm::Type* InitType = Init->getType();
403
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000404 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
405 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
406
Eli Friedman43a0ce82008-05-30 19:50:47 +0000407 if (!GV) {
408 GV = new llvm::GlobalVariable(InitType, false,
409 llvm::GlobalValue::ExternalLinkage,
410 0, D->getName(), &getModule(), 0,
411 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000412 } else if (GV->getType() !=
413 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000414 // We have a definition after a prototype with the wrong type.
415 // We must make a new GlobalVariable* and update everything that used OldGV
416 // (a declaration or tentative definition) with the new GlobalVariable*
417 // (which will be a definition).
418 //
419 // This happens if there is a prototype for a global (e.g. "extern int x[];")
420 // and then a definition of a different type (e.g. "int x[10];"). This also
421 // happens when an initializer has a different type from the type of the
422 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000423 //
424 // FIXME: This also ends up happening if there's a definition followed by
425 // a tentative definition! (Although Sema rejects that construct
426 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000427
428 // Save the old global
429 llvm::GlobalVariable *OldGV = GV;
430
431 // Make a new global with the correct type
432 GV = new llvm::GlobalVariable(InitType, false,
433 llvm::GlobalValue::ExternalLinkage,
434 0, D->getName(), &getModule(), 0,
435 ASTTy.getAddressSpace());
436 // Steal the name of the old global
437 GV->takeName(OldGV);
438
439 // Replace all uses of the old global with the new global
440 llvm::Constant *NewPtrForOldDecl =
441 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
442 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000443
444 // Erase the old global, since it is no longer used.
445 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000446 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000447
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000448 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000449
Nate Begeman8a704172008-04-19 04:17:09 +0000450 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
451 SourceManager &SM = Context.getSourceManager();
452 AddAnnotation(EmitAnnotateAttr(GV, AA,
453 SM.getLogicalLineNumber(D->getLocation())));
454 }
455
Chris Lattner4b009652007-07-25 00:24:17 +0000456 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000457
Eli Friedman7008e9a2008-05-30 20:39:54 +0000458 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
459 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000460 if (const IncompleteArrayType* IAT =
461 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000462 Align = Context.getTypeAlign(IAT->getElementType());
463 else
464 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000465 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
466 Align = std::max(Align, AA->getAlignment());
467 }
468 GV->setAlignment(Align / 8);
469
Chris Lattner402b3372008-03-03 03:28:21 +0000470 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000471 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000472 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000473
474 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
475 // Prefaced with special LLVM marker to indicate that the name
476 // should not be munged.
477 GV->setName("\01" + ALA->getLabel());
478 }
Chris Lattner4b009652007-07-25 00:24:17 +0000479
480 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000481 if (D->getStorageClass() == VarDecl::Static)
482 GV->setLinkage(llvm::Function::InternalLinkage);
483 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000484 GV->setLinkage(llvm::Function::DLLImportLinkage);
485 else if (D->getAttr<DLLExportAttr>())
486 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000487 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000488 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000489 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000490 // FIXME: This isn't right. This should handle common linkage and other
491 // stuff.
492 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000493 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000494 case VarDecl::Auto:
495 case VarDecl::Register:
496 assert(0 && "Can't have auto or register globals");
497 case VarDecl::None:
498 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000499 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000500 break;
501 case VarDecl::Extern:
502 case VarDecl::PrivateExtern:
503 // todo: common
504 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000505 }
Chris Lattner4b009652007-07-25 00:24:17 +0000506 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000507
508 // Emit global variable debug information.
509 CGDebugInfo *DI = getDebugInfo();
510 if(DI) {
511 if(D->getLocation().isValid())
512 DI->setLocation(D->getLocation());
513 DI->EmitGlobalVariable(GV, D);
514 }
Chris Lattner4b009652007-07-25 00:24:17 +0000515}
516
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000517llvm::GlobalValue *
518CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
519 // FIXME: param attributes for sext/zext etc.
520 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
521 assert(!D->getBody() && "Unexpected alias attr on function with body.");
522
523 const std::string& aliaseeName = AA->getAliasee();
524 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
525 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
526 llvm::Function::ExternalLinkage,
527 D->getName(),
528 aliasee,
529 &getModule());
530 SetGlobalValueAttributes(D, alias);
531 return alias;
532 } else {
533 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
534 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
535 llvm::Function *F = llvm::Function::Create(FTy,
536 llvm::Function::ExternalLinkage,
537 D->getName(), &getModule());
538
539 SetFunctionAttributes(D, F, FTy);
540 return F;
541 }
542}
543
544llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000545 QualType ASTTy = D->getType();
546 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
547 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000548
549 // Lookup the entry, lazily creating it if necessary.
550 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
551 if (!Entry)
552 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000553
Daniel Dunbar2188c532008-07-30 16:32:24 +0000554 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000555}
556
557void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000558 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
559 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000560 Entry = EmitForwardFunctionDefinition(D);
561 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000562 // If the types mismatch then we have to rewrite the definition.
563 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
564 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000565 // Otherwise, we have a definition after a prototype with the wrong type.
566 // F is the Function* for the one with the wrong type, we must make a new
567 // Function* and update everything that used F (a declaration) with the new
568 // Function* (which will be a definition).
569 //
570 // This happens if there is a prototype for a function (e.g. "int f()") and
571 // then a definition of a different type (e.g. "int f(int x)"). Start by
572 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000573 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
574 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000575
576 // Replace uses of F with the Function we will endow with a body.
577 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000578 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
579 Entry->replaceAllUsesWith(NewPtrForOldDecl);
580
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000581 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000582 // FIXME: Add GlobalValue->eraseFromParent().
583 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
584 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
585 F->eraseFromParent();
586 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
587 GA->eraseFromParent();
588 } else {
589 assert(0 && "Invalid global variable type.");
590 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000591
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000592 Entry = NewFn;
593 }
594 }
595
596 if (D->getAttr<AliasAttr>()) {
597 ;
598 } else {
599 llvm::Function *Fn = cast<llvm::Function>(Entry);
600 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000601
Daniel Dunbar91692d92008-08-11 17:36:14 +0000602 // Set attributes specific to definition.
603 // FIXME: This needs to be cleaned up by clearly emitting the
604 // declaration / definition at separate times.
605 if (!Features.Exceptions)
606 Fn->addParamAttr(0, llvm::ParamAttr::NoUnwind);
607
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000608 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
609 AddGlobalCtor(Fn, CA->getPriority());
610 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
611 AddGlobalDtor(Fn, DA->getPriority());
612 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000613 }
614}
615
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000616void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
617 // Make sure that this type is translated.
618 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000619}
620
621
Chris Lattnerab862cc2007-08-31 04:31:45 +0000622/// getBuiltinLibFunction
623llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000624 if (BuiltinID > BuiltinFunctions.size())
625 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000626
Chris Lattner9f2d6892007-12-13 00:38:03 +0000627 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
628 // a slot for it.
629 assert(BuiltinID && "Invalid Builtin ID");
630 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000631 if (FunctionSlot)
632 return FunctionSlot;
633
634 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
635
636 // Get the name, skip over the __builtin_ prefix.
637 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
638
639 // Get the type for the builtin.
640 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
641 const llvm::FunctionType *Ty =
642 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
643
644 // FIXME: This has a serious problem with code like this:
645 // void abs() {}
646 // ... __builtin_abs(x);
647 // The two versions of abs will collide. The fix is for the builtin to win,
648 // and for the existing one to be turned into a constantexpr cast of the
649 // builtin. In the case where the existing one is a static function, it
650 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000651 if (llvm::Function *Existing = getModule().getFunction(Name)) {
652 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
653 return FunctionSlot = Existing;
654 assert(Existing == 0 && "FIXME: Name collision");
655 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000656
657 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000658 return FunctionSlot =
659 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
660 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000661}
662
Chris Lattner4b23f942007-12-18 00:25:38 +0000663llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
664 unsigned NumTys) {
665 return llvm::Intrinsic::getDeclaration(&getModule(),
666 (llvm::Intrinsic::ID)IID, Tys, NumTys);
667}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000668
Chris Lattner4b009652007-07-25 00:24:17 +0000669llvm::Function *CodeGenModule::getMemCpyFn() {
670 if (MemCpyFn) return MemCpyFn;
671 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000672 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000673 default: assert(0 && "Unknown ptr width");
674 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
675 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
676 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000677 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000678}
Anders Carlsson36a04872007-08-21 00:21:21 +0000679
Eli Friedman8f08a252008-05-26 12:59:39 +0000680llvm::Function *CodeGenModule::getMemMoveFn() {
681 if (MemMoveFn) return MemMoveFn;
682 llvm::Intrinsic::ID IID;
683 switch (Context.Target.getPointerWidth(0)) {
684 default: assert(0 && "Unknown ptr width");
685 case 32: IID = llvm::Intrinsic::memmove_i32; break;
686 case 64: IID = llvm::Intrinsic::memmove_i64; break;
687 }
688 return MemMoveFn = getIntrinsic(IID);
689}
690
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000691llvm::Function *CodeGenModule::getMemSetFn() {
692 if (MemSetFn) return MemSetFn;
693 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000694 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000695 default: assert(0 && "Unknown ptr width");
696 case 32: IID = llvm::Intrinsic::memset_i32; break;
697 case 64: IID = llvm::Intrinsic::memset_i64; break;
698 }
699 return MemSetFn = getIntrinsic(IID);
700}
Chris Lattner4b23f942007-12-18 00:25:38 +0000701
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000702// FIXME: This needs moving into an Apple Objective-C runtime class
Chris Lattnerab862cc2007-08-31 04:31:45 +0000703llvm::Constant *CodeGenModule::
704GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000705 llvm::StringMapEntry<llvm::Constant *> &Entry =
706 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
707
708 if (Entry.getValue())
709 return Entry.getValue();
710
711 std::vector<llvm::Constant*> Fields;
712
713 if (!CFConstantStringClassRef) {
714 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
715 Ty = llvm::ArrayType::get(Ty, 0);
716
717 CFConstantStringClassRef =
718 new llvm::GlobalVariable(Ty, false,
719 llvm::GlobalVariable::ExternalLinkage, 0,
720 "__CFConstantStringClassReference",
721 &getModule());
722 }
723
724 // Class pointer.
725 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
726 llvm::Constant *Zeros[] = { Zero, Zero };
727 llvm::Constant *C =
728 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
729 Fields.push_back(C);
730
731 // Flags.
732 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
733 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
734
735 // String pointer.
736 C = llvm::ConstantArray::get(str);
737 C = new llvm::GlobalVariable(C->getType(), true,
738 llvm::GlobalValue::InternalLinkage,
739 C, ".str", &getModule());
740
741 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
742 Fields.push_back(C);
743
744 // String length.
745 Ty = getTypes().ConvertType(getContext().LongTy);
746 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
747
748 // The struct.
749 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
750 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000751 llvm::GlobalVariable *GV =
752 new llvm::GlobalVariable(C->getType(), true,
753 llvm::GlobalVariable::InternalLinkage,
754 C, "", &getModule());
755 GV->setSection("__DATA,__cfstring");
756 Entry.setValue(GV);
757 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000758}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000759
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000760/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000761/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000762std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000763 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
764 const char *StrData = E->getStrData();
765 unsigned Len = E->getByteLength();
766
767 const ConstantArrayType *CAT =
768 getContext().getAsConstantArrayType(E->getType());
769 assert(CAT && "String isn't pointer or array!");
770
771 // Resize the string to the right size
772 // FIXME: What about wchar_t strings?
773 std::string Str(StrData, StrData+Len);
774 uint64_t RealLen = CAT->getSize().getZExtValue();
775 Str.resize(RealLen, '\0');
776
777 return Str;
778}
779
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000780/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
781/// constant array for the given string literal.
782llvm::Constant *
783CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
784 // FIXME: This can be more efficient.
785 return GetAddrOfConstantString(GetStringForStringLiteral(S));
786}
787
Chris Lattnera6dcce32008-02-11 00:02:17 +0000788/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000789static llvm::Constant *GenerateStringLiteral(const std::string &str,
790 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000791 CodeGenModule &CGM) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000792 // Create Constant for this string literal. Don't add a '\0'.
793 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000794
795 // Create a global variable for this string
796 C = new llvm::GlobalVariable(C->getType(), constant,
797 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000798 C, ".str", &CGM.getModule());
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000799
Chris Lattnerdb6be562007-11-28 05:34:05 +0000800 return C;
801}
802
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000803/// GetAddrOfConstantString - Returns a pointer to a character array
804/// containing the literal. This contents are exactly that of the
805/// given string, i.e. it will not be null terminated automatically;
806/// see GetAddrOfConstantCString. Note that whether the result is
807/// actually a pointer to an LLVM constant depends on
808/// Feature.WriteableStrings.
809///
810/// The result has pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000811llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
812 // Don't share any string literals if writable-strings is turned on.
813 if (Features.WritableStrings)
814 return GenerateStringLiteral(str, false, *this);
815
816 llvm::StringMapEntry<llvm::Constant *> &Entry =
817 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
818
819 if (Entry.getValue())
820 return Entry.getValue();
821
822 // Create a global variable for this.
823 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
824 Entry.setValue(C);
825 return C;
826}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000827
828/// GetAddrOfConstantCString - Returns a pointer to a character
829/// array containing the literal and a terminating '\-'
830/// character. The result has pointer to array type.
831llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str) {
Daniel Dunbarb4278222008-08-15 18:29:12 +0000832 return GetAddrOfConstantString(str + "\0");
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000833}
Daniel Dunbar27250d32008-08-15 23:26:23 +0000834
835/// EmitTopLevelDecl - Emit code for a single top level declaration.
836void CodeGenModule::EmitTopLevelDecl(Decl *D) {
837 // If an error has occurred, stop code generation, but continue
838 // parsing and semantic analysis (to ensure all warnings and errors
839 // are emitted).
840 if (Diags.hasErrorOccurred())
841 return;
842
843 switch (D->getKind()) {
844 case Decl::Function:
845 case Decl::Var:
846 EmitGlobal(cast<ValueDecl>(D));
847 break;
848
849 case Decl::Namespace:
850 assert(0 && "FIXME: Namespace unsupported");
851 break;
852
853 // Objective-C Decls
854
855 // Forward declarations, no (immediate) code generation.
856 case Decl::ObjCClass:
857 case Decl::ObjCCategory:
858 case Decl::ObjCForwardProtocol:
859 case Decl::ObjCInterface:
860 break;
861
862 case Decl::ObjCProtocol:
863 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
864 break;
865
866 case Decl::ObjCCategoryImpl:
867 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
868 break;
869
870 case Decl::ObjCImplementation:
871 Runtime->GenerateClass(cast<ObjCImplementationDecl>(D));
872 break;
873
874 case Decl::ObjCMethod: {
875 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
876 // If this is not a prototype, emit the body.
877 if (OMD->getBody())
878 CodeGenFunction(*this).GenerateObjCMethod(OMD);
879 break;
880 }
881 case Decl::ObjCPropertyImpl:
882 assert(0 && "FIXME: ObjCPropertyImpl unsupported");
883 break;
884 case Decl::ObjCCompatibleAlias:
885 assert(0 && "FIXME: ObjCCompatibleAlias unsupported");
886 break;
887
888 case Decl::LinkageSpec: {
889 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
890 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +0000891 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +0000892 // FIXME: implement C++ linkage, C linkage works mostly by C
893 // language reuse already.
894 break;
895 }
896
897 case Decl::FileScopeAsm: {
898 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
899 std::string AsmString(AD->getAsmString()->getStrData(),
900 AD->getAsmString()->getByteLength());
901
902 const std::string &S = getModule().getModuleInlineAsm();
903 if (S.empty())
904 getModule().setModuleInlineAsm(AsmString);
905 else
906 getModule().setModuleInlineAsm(S + '\n' + AsmString);
907 break;
908 }
909
910 default:
911 // Make sure we handled everything we should, every other kind is
912 // a non-top-level decl. FIXME: Would be nice to have an
913 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
914 // that easily.
915 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
916 }
917}
918