1f22ef01cSRoman Divacky //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This coordinates the per-module state used while generating code.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14f22ef01cSRoman Divacky #include "CodeGenModule.h"
15f22ef01cSRoman Divacky #include "CGDebugInfo.h"
16f22ef01cSRoman Divacky #include "CodeGenFunction.h"
17f22ef01cSRoman Divacky #include "CGCall.h"
18f22ef01cSRoman Divacky #include "CGObjCRuntime.h"
19f22ef01cSRoman Divacky #include "Mangle.h"
20f22ef01cSRoman Divacky #include "TargetInfo.h"
21ffd1746dSEd Schouten #include "clang/Frontend/CodeGenOptions.h"
22f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
23f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h"
24f22ef01cSRoman Divacky #include "clang/AST/DeclObjC.h"
25f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
26ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h"
27f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h"
28f22ef01cSRoman Divacky #include "clang/Basic/Builtins.h"
29f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h"
30f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h"
31f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h"
32f22ef01cSRoman Divacky #include "clang/Basic/ConvertUTF.h"
33f22ef01cSRoman Divacky #include "llvm/CallingConv.h"
34f22ef01cSRoman Divacky #include "llvm/Module.h"
35f22ef01cSRoman Divacky #include "llvm/Intrinsics.h"
36f22ef01cSRoman Divacky #include "llvm/LLVMContext.h"
37f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h"
38f22ef01cSRoman Divacky #include "llvm/Target/TargetData.h"
39f22ef01cSRoman Divacky #include "llvm/Support/CallSite.h"
40f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
41f22ef01cSRoman Divacky using namespace clang;
42f22ef01cSRoman Divacky using namespace CodeGen;
43f22ef01cSRoman Divacky 
44f22ef01cSRoman Divacky 
45f22ef01cSRoman Divacky CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
46f22ef01cSRoman Divacky                              llvm::Module &M, const llvm::TargetData &TD,
47f22ef01cSRoman Divacky                              Diagnostic &diags)
48f22ef01cSRoman Divacky   : BlockModule(C, M, TD, Types, *this), Context(C),
49f22ef01cSRoman Divacky     Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
50f22ef01cSRoman Divacky     TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
51f22ef01cSRoman Divacky     Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()),
52f22ef01cSRoman Divacky     VTables(*this), Runtime(0), ABI(0),
53f22ef01cSRoman Divacky     CFConstantStringClassRef(0),
54f22ef01cSRoman Divacky     NSConstantStringClassRef(0),
55f22ef01cSRoman Divacky     VMContext(M.getContext()) {
56f22ef01cSRoman Divacky 
57f22ef01cSRoman Divacky   if (!Features.ObjC1)
58f22ef01cSRoman Divacky     Runtime = 0;
59f22ef01cSRoman Divacky   else if (!Features.NeXTRuntime)
60f22ef01cSRoman Divacky     Runtime = CreateGNUObjCRuntime(*this);
61f22ef01cSRoman Divacky   else if (Features.ObjCNonFragileABI)
62f22ef01cSRoman Divacky     Runtime = CreateMacNonFragileABIObjCRuntime(*this);
63f22ef01cSRoman Divacky   else
64f22ef01cSRoman Divacky     Runtime = CreateMacObjCRuntime(*this);
65f22ef01cSRoman Divacky 
66f22ef01cSRoman Divacky   if (!Features.CPlusPlus)
67f22ef01cSRoman Divacky     ABI = 0;
68f22ef01cSRoman Divacky   else createCXXABI();
69f22ef01cSRoman Divacky 
70f22ef01cSRoman Divacky   // If debug info generation is enabled, create the CGDebugInfo object.
71f22ef01cSRoman Divacky   DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
72f22ef01cSRoman Divacky }
73f22ef01cSRoman Divacky 
74f22ef01cSRoman Divacky CodeGenModule::~CodeGenModule() {
75f22ef01cSRoman Divacky   delete Runtime;
76f22ef01cSRoman Divacky   delete ABI;
77f22ef01cSRoman Divacky   delete DebugInfo;
78f22ef01cSRoman Divacky }
79f22ef01cSRoman Divacky 
80f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() {
81f22ef01cSRoman Divacky   if (!Features.NeXTRuntime)
82f22ef01cSRoman Divacky     Runtime = CreateGNUObjCRuntime(*this);
83f22ef01cSRoman Divacky   else if (Features.ObjCNonFragileABI)
84f22ef01cSRoman Divacky     Runtime = CreateMacNonFragileABIObjCRuntime(*this);
85f22ef01cSRoman Divacky   else
86f22ef01cSRoman Divacky     Runtime = CreateMacObjCRuntime(*this);
87f22ef01cSRoman Divacky }
88f22ef01cSRoman Divacky 
89f22ef01cSRoman Divacky void CodeGenModule::createCXXABI() {
90ffd1746dSEd Schouten   if (Context.Target.getCXXABI() == "microsoft")
91ffd1746dSEd Schouten     ABI = CreateMicrosoftCXXABI(*this);
92ffd1746dSEd Schouten   else
93f22ef01cSRoman Divacky     ABI = CreateItaniumCXXABI(*this);
94f22ef01cSRoman Divacky }
95f22ef01cSRoman Divacky 
96f22ef01cSRoman Divacky void CodeGenModule::Release() {
97f22ef01cSRoman Divacky   EmitDeferred();
98f22ef01cSRoman Divacky   EmitCXXGlobalInitFunc();
99f22ef01cSRoman Divacky   EmitCXXGlobalDtorFunc();
100f22ef01cSRoman Divacky   if (Runtime)
101f22ef01cSRoman Divacky     if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
102f22ef01cSRoman Divacky       AddGlobalCtor(ObjCInitFunction);
103f22ef01cSRoman Divacky   EmitCtorList(GlobalCtors, "llvm.global_ctors");
104f22ef01cSRoman Divacky   EmitCtorList(GlobalDtors, "llvm.global_dtors");
105f22ef01cSRoman Divacky   EmitAnnotations();
106f22ef01cSRoman Divacky   EmitLLVMUsed();
107ffd1746dSEd Schouten 
108ffd1746dSEd Schouten   if (getCodeGenOpts().EmitDeclMetadata)
109ffd1746dSEd Schouten     EmitDeclMetadata();
110f22ef01cSRoman Divacky }
111f22ef01cSRoman Divacky 
112f22ef01cSRoman Divacky bool CodeGenModule::isTargetDarwin() const {
113f22ef01cSRoman Divacky   return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
114f22ef01cSRoman Divacky }
115f22ef01cSRoman Divacky 
116f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
117f22ef01cSRoman Divacky /// specified stmt yet.
118f22ef01cSRoman Divacky void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
119f22ef01cSRoman Divacky                                      bool OmitOnError) {
120f22ef01cSRoman Divacky   if (OmitOnError && getDiags().hasErrorOccurred())
121f22ef01cSRoman Divacky     return;
122f22ef01cSRoman Divacky   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
123f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
124f22ef01cSRoman Divacky   std::string Msg = Type;
125f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
126f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
127f22ef01cSRoman Divacky }
128f22ef01cSRoman Divacky 
129f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
130f22ef01cSRoman Divacky /// specified decl yet.
131f22ef01cSRoman Divacky void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
132f22ef01cSRoman Divacky                                      bool OmitOnError) {
133f22ef01cSRoman Divacky   if (OmitOnError && getDiags().hasErrorOccurred())
134f22ef01cSRoman Divacky     return;
135f22ef01cSRoman Divacky   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
136f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
137f22ef01cSRoman Divacky   std::string Msg = Type;
138f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
139f22ef01cSRoman Divacky }
140f22ef01cSRoman Divacky 
141f22ef01cSRoman Divacky LangOptions::VisibilityMode
142f22ef01cSRoman Divacky CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
143f22ef01cSRoman Divacky   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
144f22ef01cSRoman Divacky     if (VD->getStorageClass() == VarDecl::PrivateExtern)
145f22ef01cSRoman Divacky       return LangOptions::Hidden;
146f22ef01cSRoman Divacky 
147f22ef01cSRoman Divacky   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
148f22ef01cSRoman Divacky     switch (attr->getVisibility()) {
149f22ef01cSRoman Divacky     default: assert(0 && "Unknown visibility!");
150f22ef01cSRoman Divacky     case VisibilityAttr::DefaultVisibility:
151f22ef01cSRoman Divacky       return LangOptions::Default;
152f22ef01cSRoman Divacky     case VisibilityAttr::HiddenVisibility:
153f22ef01cSRoman Divacky       return LangOptions::Hidden;
154f22ef01cSRoman Divacky     case VisibilityAttr::ProtectedVisibility:
155f22ef01cSRoman Divacky       return LangOptions::Protected;
156f22ef01cSRoman Divacky     }
157f22ef01cSRoman Divacky   }
158f22ef01cSRoman Divacky 
159ffd1746dSEd Schouten   if (getLangOptions().CPlusPlus) {
160ffd1746dSEd Schouten     // Entities subject to an explicit instantiation declaration get default
161ffd1746dSEd Schouten     // visibility.
162ffd1746dSEd Schouten     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
163ffd1746dSEd Schouten       if (Function->getTemplateSpecializationKind()
164ffd1746dSEd Schouten                                         == TSK_ExplicitInstantiationDeclaration)
165ffd1746dSEd Schouten         return LangOptions::Default;
166ffd1746dSEd Schouten     } else if (const ClassTemplateSpecializationDecl *ClassSpec
167ffd1746dSEd Schouten                               = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
168ffd1746dSEd Schouten       if (ClassSpec->getSpecializationKind()
169ffd1746dSEd Schouten                                         == TSK_ExplicitInstantiationDeclaration)
170ffd1746dSEd Schouten         return LangOptions::Default;
171ffd1746dSEd Schouten     } else if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
172ffd1746dSEd Schouten       if (Record->getTemplateSpecializationKind()
173ffd1746dSEd Schouten                                         == TSK_ExplicitInstantiationDeclaration)
174ffd1746dSEd Schouten         return LangOptions::Default;
175ffd1746dSEd Schouten     } else if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
176ffd1746dSEd Schouten       if (Var->isStaticDataMember() &&
177ffd1746dSEd Schouten           (Var->getTemplateSpecializationKind()
178ffd1746dSEd Schouten                                       == TSK_ExplicitInstantiationDeclaration))
179ffd1746dSEd Schouten         return LangOptions::Default;
180ffd1746dSEd Schouten     }
181ffd1746dSEd Schouten 
182ffd1746dSEd Schouten     // If -fvisibility-inlines-hidden was provided, then inline C++ member
183ffd1746dSEd Schouten     // functions get "hidden" visibility by default.
184ffd1746dSEd Schouten     if (getLangOptions().InlineVisibilityHidden)
185ffd1746dSEd Schouten       if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
186ffd1746dSEd Schouten         if (Method->isInlined())
187ffd1746dSEd Schouten           return LangOptions::Hidden;
188ffd1746dSEd Schouten   }
189ffd1746dSEd Schouten 
190f22ef01cSRoman Divacky   // This decl should have the same visibility as its parent.
191f22ef01cSRoman Divacky   if (const DeclContext *DC = D->getDeclContext())
192f22ef01cSRoman Divacky     return getDeclVisibilityMode(cast<Decl>(DC));
193f22ef01cSRoman Divacky 
194f22ef01cSRoman Divacky   return getLangOptions().getVisibilityMode();
195f22ef01cSRoman Divacky }
196f22ef01cSRoman Divacky 
197f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
198f22ef01cSRoman Divacky                                         const Decl *D) const {
199f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
200f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
201f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
202f22ef01cSRoman Divacky     return;
203f22ef01cSRoman Divacky   }
204f22ef01cSRoman Divacky 
205f22ef01cSRoman Divacky   switch (getDeclVisibilityMode(D)) {
206f22ef01cSRoman Divacky   default: assert(0 && "Unknown visibility!");
207f22ef01cSRoman Divacky   case LangOptions::Default:
208f22ef01cSRoman Divacky     return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
209f22ef01cSRoman Divacky   case LangOptions::Hidden:
210f22ef01cSRoman Divacky     return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
211f22ef01cSRoman Divacky   case LangOptions::Protected:
212f22ef01cSRoman Divacky     return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
213f22ef01cSRoman Divacky   }
214f22ef01cSRoman Divacky }
215f22ef01cSRoman Divacky 
216ffd1746dSEd Schouten llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
217f22ef01cSRoman Divacky   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
218f22ef01cSRoman Divacky 
219ffd1746dSEd Schouten   llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
220ffd1746dSEd Schouten   if (!Str.empty())
221ffd1746dSEd Schouten     return Str;
222f22ef01cSRoman Divacky 
223f22ef01cSRoman Divacky   if (!getMangleContext().shouldMangleDeclName(ND)) {
224ffd1746dSEd Schouten     IdentifierInfo *II = ND->getIdentifier();
225ffd1746dSEd Schouten     assert(II && "Attempt to mangle unnamed decl.");
226ffd1746dSEd Schouten 
227ffd1746dSEd Schouten     Str = II->getName();
228ffd1746dSEd Schouten     return Str;
229f22ef01cSRoman Divacky   }
230f22ef01cSRoman Divacky 
231ffd1746dSEd Schouten   llvm::SmallString<256> Buffer;
232ffd1746dSEd Schouten   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
233ffd1746dSEd Schouten     getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer);
234ffd1746dSEd Schouten   else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
235ffd1746dSEd Schouten     getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer);
236ffd1746dSEd Schouten   else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
237ffd1746dSEd Schouten     getMangleContext().mangleBlock(GD, BD, Buffer);
238ffd1746dSEd Schouten   else
239ffd1746dSEd Schouten     getMangleContext().mangleName(ND, Buffer);
240ffd1746dSEd Schouten 
241ffd1746dSEd Schouten   // Allocate space for the mangled name.
242ffd1746dSEd Schouten   size_t Length = Buffer.size();
243ffd1746dSEd Schouten   char *Name = MangledNamesAllocator.Allocate<char>(Length);
244ffd1746dSEd Schouten   std::copy(Buffer.begin(), Buffer.end(), Name);
245ffd1746dSEd Schouten 
246ffd1746dSEd Schouten   Str = llvm::StringRef(Name, Length);
247ffd1746dSEd Schouten 
248ffd1746dSEd Schouten   return Str;
249ffd1746dSEd Schouten }
250ffd1746dSEd Schouten 
251ffd1746dSEd Schouten void CodeGenModule::getMangledName(GlobalDecl GD, MangleBuffer &Buffer,
252ffd1746dSEd Schouten                                    const BlockDecl *BD) {
253ffd1746dSEd Schouten   getMangleContext().mangleBlock(GD, BD, Buffer.getBuffer());
254f22ef01cSRoman Divacky }
255f22ef01cSRoman Divacky 
256f22ef01cSRoman Divacky llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
257f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
258f22ef01cSRoman Divacky }
259f22ef01cSRoman Divacky 
260f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
261f22ef01cSRoman Divacky /// main() runs.
262f22ef01cSRoman Divacky void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
263f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
264f22ef01cSRoman Divacky   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
265f22ef01cSRoman Divacky }
266f22ef01cSRoman Divacky 
267f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
268f22ef01cSRoman Divacky /// when the module is unloaded.
269f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
270f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
271f22ef01cSRoman Divacky   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
272f22ef01cSRoman Divacky }
273f22ef01cSRoman Divacky 
274f22ef01cSRoman Divacky void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
275f22ef01cSRoman Divacky   // Ctor function type is void()*.
276f22ef01cSRoman Divacky   llvm::FunctionType* CtorFTy =
277f22ef01cSRoman Divacky     llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
278f22ef01cSRoman Divacky                             std::vector<const llvm::Type*>(),
279f22ef01cSRoman Divacky                             false);
280f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
281f22ef01cSRoman Divacky 
282f22ef01cSRoman Divacky   // Get the type of a ctor entry, { i32, void ()* }.
283f22ef01cSRoman Divacky   llvm::StructType* CtorStructTy =
284f22ef01cSRoman Divacky     llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
285f22ef01cSRoman Divacky                           llvm::PointerType::getUnqual(CtorFTy), NULL);
286f22ef01cSRoman Divacky 
287f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
288f22ef01cSRoman Divacky   std::vector<llvm::Constant*> Ctors;
289f22ef01cSRoman Divacky   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
290f22ef01cSRoman Divacky     std::vector<llvm::Constant*> S;
291f22ef01cSRoman Divacky     S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
292f22ef01cSRoman Divacky                 I->second, false));
293f22ef01cSRoman Divacky     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
294f22ef01cSRoman Divacky     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
295f22ef01cSRoman Divacky   }
296f22ef01cSRoman Divacky 
297f22ef01cSRoman Divacky   if (!Ctors.empty()) {
298f22ef01cSRoman Divacky     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
299f22ef01cSRoman Divacky     new llvm::GlobalVariable(TheModule, AT, false,
300f22ef01cSRoman Divacky                              llvm::GlobalValue::AppendingLinkage,
301f22ef01cSRoman Divacky                              llvm::ConstantArray::get(AT, Ctors),
302f22ef01cSRoman Divacky                              GlobalName);
303f22ef01cSRoman Divacky   }
304f22ef01cSRoman Divacky }
305f22ef01cSRoman Divacky 
306f22ef01cSRoman Divacky void CodeGenModule::EmitAnnotations() {
307f22ef01cSRoman Divacky   if (Annotations.empty())
308f22ef01cSRoman Divacky     return;
309f22ef01cSRoman Divacky 
310f22ef01cSRoman Divacky   // Create a new global variable for the ConstantStruct in the Module.
311f22ef01cSRoman Divacky   llvm::Constant *Array =
312f22ef01cSRoman Divacky   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
313f22ef01cSRoman Divacky                                                 Annotations.size()),
314f22ef01cSRoman Divacky                            Annotations);
315f22ef01cSRoman Divacky   llvm::GlobalValue *gv =
316f22ef01cSRoman Divacky   new llvm::GlobalVariable(TheModule, Array->getType(), false,
317f22ef01cSRoman Divacky                            llvm::GlobalValue::AppendingLinkage, Array,
318f22ef01cSRoman Divacky                            "llvm.global.annotations");
319f22ef01cSRoman Divacky   gv->setSection("llvm.metadata");
320f22ef01cSRoman Divacky }
321f22ef01cSRoman Divacky 
322f22ef01cSRoman Divacky static CodeGenModule::GVALinkage
323f22ef01cSRoman Divacky GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
324f22ef01cSRoman Divacky                       const LangOptions &Features) {
325f22ef01cSRoman Divacky   CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
326f22ef01cSRoman Divacky 
327f22ef01cSRoman Divacky   Linkage L = FD->getLinkage();
328f22ef01cSRoman Divacky   if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
329f22ef01cSRoman Divacky       FD->getType()->getLinkage() == UniqueExternalLinkage)
330f22ef01cSRoman Divacky     L = UniqueExternalLinkage;
331f22ef01cSRoman Divacky 
332f22ef01cSRoman Divacky   switch (L) {
333f22ef01cSRoman Divacky   case NoLinkage:
334f22ef01cSRoman Divacky   case InternalLinkage:
335f22ef01cSRoman Divacky   case UniqueExternalLinkage:
336f22ef01cSRoman Divacky     return CodeGenModule::GVA_Internal;
337f22ef01cSRoman Divacky 
338f22ef01cSRoman Divacky   case ExternalLinkage:
339f22ef01cSRoman Divacky     switch (FD->getTemplateSpecializationKind()) {
340f22ef01cSRoman Divacky     case TSK_Undeclared:
341f22ef01cSRoman Divacky     case TSK_ExplicitSpecialization:
342f22ef01cSRoman Divacky       External = CodeGenModule::GVA_StrongExternal;
343f22ef01cSRoman Divacky       break;
344f22ef01cSRoman Divacky 
345f22ef01cSRoman Divacky     case TSK_ExplicitInstantiationDefinition:
346f22ef01cSRoman Divacky       return CodeGenModule::GVA_ExplicitTemplateInstantiation;
347f22ef01cSRoman Divacky 
348f22ef01cSRoman Divacky     case TSK_ExplicitInstantiationDeclaration:
349f22ef01cSRoman Divacky     case TSK_ImplicitInstantiation:
350f22ef01cSRoman Divacky       External = CodeGenModule::GVA_TemplateInstantiation;
351f22ef01cSRoman Divacky       break;
352f22ef01cSRoman Divacky     }
353f22ef01cSRoman Divacky   }
354f22ef01cSRoman Divacky 
355f22ef01cSRoman Divacky   if (!FD->isInlined())
356f22ef01cSRoman Divacky     return External;
357f22ef01cSRoman Divacky 
358f22ef01cSRoman Divacky   if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
359f22ef01cSRoman Divacky     // GNU or C99 inline semantics. Determine whether this symbol should be
360f22ef01cSRoman Divacky     // externally visible.
361f22ef01cSRoman Divacky     if (FD->isInlineDefinitionExternallyVisible())
362f22ef01cSRoman Divacky       return External;
363f22ef01cSRoman Divacky 
364f22ef01cSRoman Divacky     // C99 inline semantics, where the symbol is not externally visible.
365f22ef01cSRoman Divacky     return CodeGenModule::GVA_C99Inline;
366f22ef01cSRoman Divacky   }
367f22ef01cSRoman Divacky 
368f22ef01cSRoman Divacky   // C++0x [temp.explicit]p9:
369f22ef01cSRoman Divacky   //   [ Note: The intent is that an inline function that is the subject of
370f22ef01cSRoman Divacky   //   an explicit instantiation declaration will still be implicitly
371f22ef01cSRoman Divacky   //   instantiated when used so that the body can be considered for
372f22ef01cSRoman Divacky   //   inlining, but that no out-of-line copy of the inline function would be
373f22ef01cSRoman Divacky   //   generated in the translation unit. -- end note ]
374f22ef01cSRoman Divacky   if (FD->getTemplateSpecializationKind()
375f22ef01cSRoman Divacky                                        == TSK_ExplicitInstantiationDeclaration)
376f22ef01cSRoman Divacky     return CodeGenModule::GVA_C99Inline;
377f22ef01cSRoman Divacky 
378f22ef01cSRoman Divacky   return CodeGenModule::GVA_CXXInline;
379f22ef01cSRoman Divacky }
380f22ef01cSRoman Divacky 
381f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
382f22ef01cSRoman Divacky CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
383f22ef01cSRoman Divacky   GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
384f22ef01cSRoman Divacky 
385ffd1746dSEd Schouten   if (Linkage == GVA_Internal)
386f22ef01cSRoman Divacky     return llvm::Function::InternalLinkage;
387ffd1746dSEd Schouten 
388ffd1746dSEd Schouten   if (D->hasAttr<DLLExportAttr>())
389f22ef01cSRoman Divacky     return llvm::Function::DLLExportLinkage;
390ffd1746dSEd Schouten 
391ffd1746dSEd Schouten   if (D->hasAttr<WeakAttr>())
392f22ef01cSRoman Divacky     return llvm::Function::WeakAnyLinkage;
393ffd1746dSEd Schouten 
394f22ef01cSRoman Divacky   // In C99 mode, 'inline' functions are guaranteed to have a strong
395f22ef01cSRoman Divacky   // definition somewhere else, so we can use available_externally linkage.
396ffd1746dSEd Schouten   if (Linkage == GVA_C99Inline)
397f22ef01cSRoman Divacky     return llvm::Function::AvailableExternallyLinkage;
398ffd1746dSEd Schouten 
399f22ef01cSRoman Divacky   // In C++, the compiler has to emit a definition in every translation unit
400f22ef01cSRoman Divacky   // that references the function.  We should use linkonce_odr because
401f22ef01cSRoman Divacky   // a) if all references in this translation unit are optimized away, we
402f22ef01cSRoman Divacky   // don't need to codegen it.  b) if the function persists, it needs to be
403f22ef01cSRoman Divacky   // merged with other definitions. c) C++ has the ODR, so we know the
404f22ef01cSRoman Divacky   // definition is dependable.
405ffd1746dSEd Schouten   if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
406f22ef01cSRoman Divacky     return llvm::Function::LinkOnceODRLinkage;
407ffd1746dSEd Schouten 
408f22ef01cSRoman Divacky   // An explicit instantiation of a template has weak linkage, since
409f22ef01cSRoman Divacky   // explicit instantiations can occur in multiple translation units
410f22ef01cSRoman Divacky   // and must all be equivalent. However, we are not allowed to
411f22ef01cSRoman Divacky   // throw away these explicit instantiations.
412ffd1746dSEd Schouten   if (Linkage == GVA_ExplicitTemplateInstantiation)
413f22ef01cSRoman Divacky     return llvm::Function::WeakODRLinkage;
414ffd1746dSEd Schouten 
415f22ef01cSRoman Divacky   // Otherwise, we have strong external linkage.
416ffd1746dSEd Schouten   assert(Linkage == GVA_StrongExternal);
417f22ef01cSRoman Divacky   return llvm::Function::ExternalLinkage;
418f22ef01cSRoman Divacky }
419f22ef01cSRoman Divacky 
420f22ef01cSRoman Divacky 
421f22ef01cSRoman Divacky /// SetFunctionDefinitionAttributes - Set attributes for a global.
422f22ef01cSRoman Divacky ///
423f22ef01cSRoman Divacky /// FIXME: This is currently only done for aliases and functions, but not for
424f22ef01cSRoman Divacky /// variables (these details are set in EmitGlobalVarDefinition for variables).
425f22ef01cSRoman Divacky void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
426f22ef01cSRoman Divacky                                                     llvm::GlobalValue *GV) {
427f22ef01cSRoman Divacky   SetCommonAttributes(D, GV);
428f22ef01cSRoman Divacky }
429f22ef01cSRoman Divacky 
430f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
431f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
432f22ef01cSRoman Divacky                                               llvm::Function *F) {
433f22ef01cSRoman Divacky   unsigned CallingConv;
434f22ef01cSRoman Divacky   AttributeListType AttributeList;
435f22ef01cSRoman Divacky   ConstructAttributeList(Info, D, AttributeList, CallingConv);
436f22ef01cSRoman Divacky   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
437f22ef01cSRoman Divacky                                           AttributeList.size()));
438f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
439f22ef01cSRoman Divacky }
440f22ef01cSRoman Divacky 
441f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
442f22ef01cSRoman Divacky                                                            llvm::Function *F) {
443f22ef01cSRoman Divacky   if (!Features.Exceptions && !Features.ObjCNonFragileABI)
444f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::NoUnwind);
445f22ef01cSRoman Divacky 
446f22ef01cSRoman Divacky   if (D->hasAttr<AlwaysInlineAttr>())
447f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::AlwaysInline);
448f22ef01cSRoman Divacky 
449f22ef01cSRoman Divacky   if (D->hasAttr<NoInlineAttr>())
450f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::NoInline);
451f22ef01cSRoman Divacky 
452f22ef01cSRoman Divacky   if (Features.getStackProtectorMode() == LangOptions::SSPOn)
453f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::StackProtect);
454f22ef01cSRoman Divacky   else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
455f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::StackProtectReq);
456f22ef01cSRoman Divacky 
457f22ef01cSRoman Divacky   if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) {
458f22ef01cSRoman Divacky     unsigned width = Context.Target.getCharWidth();
459f22ef01cSRoman Divacky     F->setAlignment(AA->getAlignment() / width);
460f22ef01cSRoman Divacky     while ((AA = AA->getNext<AlignedAttr>()))
461f22ef01cSRoman Divacky       F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width));
462f22ef01cSRoman Divacky   }
463f22ef01cSRoman Divacky   // C++ ABI requires 2-byte alignment for member functions.
464f22ef01cSRoman Divacky   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
465f22ef01cSRoman Divacky     F->setAlignment(2);
466f22ef01cSRoman Divacky }
467f22ef01cSRoman Divacky 
468f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
469f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
470f22ef01cSRoman Divacky   setGlobalVisibility(GV, D);
471f22ef01cSRoman Divacky 
472f22ef01cSRoman Divacky   if (D->hasAttr<UsedAttr>())
473f22ef01cSRoman Divacky     AddUsedGlobal(GV);
474f22ef01cSRoman Divacky 
475f22ef01cSRoman Divacky   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
476f22ef01cSRoman Divacky     GV->setSection(SA->getName());
477f22ef01cSRoman Divacky 
478f22ef01cSRoman Divacky   getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
479f22ef01cSRoman Divacky }
480f22ef01cSRoman Divacky 
481f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
482f22ef01cSRoman Divacky                                                   llvm::Function *F,
483f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
484f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
485f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
486f22ef01cSRoman Divacky 
487f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
488f22ef01cSRoman Divacky 
489f22ef01cSRoman Divacky   SetCommonAttributes(D, F);
490f22ef01cSRoman Divacky }
491f22ef01cSRoman Divacky 
492f22ef01cSRoman Divacky void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
493f22ef01cSRoman Divacky                                           llvm::Function *F,
494f22ef01cSRoman Divacky                                           bool IsIncompleteFunction) {
495f22ef01cSRoman Divacky   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
496f22ef01cSRoman Divacky 
497f22ef01cSRoman Divacky   if (!IsIncompleteFunction)
498f22ef01cSRoman Divacky     SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
499f22ef01cSRoman Divacky 
500f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
501f22ef01cSRoman Divacky   // overridden by a definition.
502f22ef01cSRoman Divacky 
503f22ef01cSRoman Divacky   if (FD->hasAttr<DLLImportAttr>()) {
504f22ef01cSRoman Divacky     F->setLinkage(llvm::Function::DLLImportLinkage);
505f22ef01cSRoman Divacky   } else if (FD->hasAttr<WeakAttr>() ||
506f22ef01cSRoman Divacky              FD->hasAttr<WeakImportAttr>()) {
507f22ef01cSRoman Divacky     // "extern_weak" is overloaded in LLVM; we probably should have
508f22ef01cSRoman Divacky     // separate linkage types for this.
509f22ef01cSRoman Divacky     F->setLinkage(llvm::Function::ExternalWeakLinkage);
510f22ef01cSRoman Divacky   } else {
511f22ef01cSRoman Divacky     F->setLinkage(llvm::Function::ExternalLinkage);
512f22ef01cSRoman Divacky   }
513f22ef01cSRoman Divacky 
514f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
515f22ef01cSRoman Divacky     F->setSection(SA->getName());
516f22ef01cSRoman Divacky }
517f22ef01cSRoman Divacky 
518f22ef01cSRoman Divacky void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
519f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
520f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
521f22ef01cSRoman Divacky   LLVMUsed.push_back(GV);
522f22ef01cSRoman Divacky }
523f22ef01cSRoman Divacky 
524f22ef01cSRoman Divacky void CodeGenModule::EmitLLVMUsed() {
525f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
526f22ef01cSRoman Divacky   if (LLVMUsed.empty())
527f22ef01cSRoman Divacky     return;
528f22ef01cSRoman Divacky 
529f22ef01cSRoman Divacky   const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
530f22ef01cSRoman Divacky 
531f22ef01cSRoman Divacky   // Convert LLVMUsed to what ConstantArray needs.
532f22ef01cSRoman Divacky   std::vector<llvm::Constant*> UsedArray;
533f22ef01cSRoman Divacky   UsedArray.resize(LLVMUsed.size());
534f22ef01cSRoman Divacky   for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
535f22ef01cSRoman Divacky     UsedArray[i] =
536f22ef01cSRoman Divacky      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
537f22ef01cSRoman Divacky                                       i8PTy);
538f22ef01cSRoman Divacky   }
539f22ef01cSRoman Divacky 
540f22ef01cSRoman Divacky   if (UsedArray.empty())
541f22ef01cSRoman Divacky     return;
542f22ef01cSRoman Divacky   llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
543f22ef01cSRoman Divacky 
544f22ef01cSRoman Divacky   llvm::GlobalVariable *GV =
545f22ef01cSRoman Divacky     new llvm::GlobalVariable(getModule(), ATy, false,
546f22ef01cSRoman Divacky                              llvm::GlobalValue::AppendingLinkage,
547f22ef01cSRoman Divacky                              llvm::ConstantArray::get(ATy, UsedArray),
548f22ef01cSRoman Divacky                              "llvm.used");
549f22ef01cSRoman Divacky 
550f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
551f22ef01cSRoman Divacky }
552f22ef01cSRoman Divacky 
553f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
554f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
555f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
556f22ef01cSRoman Divacky   // for a static function, iterate until no  changes are made.
557f22ef01cSRoman Divacky 
558f22ef01cSRoman Divacky   while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
559f22ef01cSRoman Divacky     if (!DeferredVTables.empty()) {
560f22ef01cSRoman Divacky       const CXXRecordDecl *RD = DeferredVTables.back();
561f22ef01cSRoman Divacky       DeferredVTables.pop_back();
562f22ef01cSRoman Divacky       getVTables().GenerateClassData(getVTableLinkage(RD), RD);
563f22ef01cSRoman Divacky       continue;
564f22ef01cSRoman Divacky     }
565f22ef01cSRoman Divacky 
566f22ef01cSRoman Divacky     GlobalDecl D = DeferredDeclsToEmit.back();
567f22ef01cSRoman Divacky     DeferredDeclsToEmit.pop_back();
568f22ef01cSRoman Divacky 
569f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
570f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
571f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
572f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
573f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
574f22ef01cSRoman Divacky     // ignore these cases.
575f22ef01cSRoman Divacky     //
576f22ef01cSRoman Divacky     // TODO: That said, looking this up multiple times is very wasteful.
577ffd1746dSEd Schouten     llvm::StringRef Name = getMangledName(D);
578f22ef01cSRoman Divacky     llvm::GlobalValue *CGRef = GetGlobalValue(Name);
579f22ef01cSRoman Divacky     assert(CGRef && "Deferred decl wasn't referenced?");
580f22ef01cSRoman Divacky 
581f22ef01cSRoman Divacky     if (!CGRef->isDeclaration())
582f22ef01cSRoman Divacky       continue;
583f22ef01cSRoman Divacky 
584f22ef01cSRoman Divacky     // GlobalAlias::isDeclaration() defers to the aliasee, but for our
585f22ef01cSRoman Divacky     // purposes an alias counts as a definition.
586f22ef01cSRoman Divacky     if (isa<llvm::GlobalAlias>(CGRef))
587f22ef01cSRoman Divacky       continue;
588f22ef01cSRoman Divacky 
589f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
590f22ef01cSRoman Divacky     EmitGlobalDefinition(D);
591f22ef01cSRoman Divacky   }
592f22ef01cSRoman Divacky }
593f22ef01cSRoman Divacky 
594f22ef01cSRoman Divacky /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
595f22ef01cSRoman Divacky /// annotation information for a given GlobalValue.  The annotation struct is
596f22ef01cSRoman Divacky /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
597f22ef01cSRoman Divacky /// GlobalValue being annotated.  The second field is the constant string
598f22ef01cSRoman Divacky /// created from the AnnotateAttr's annotation.  The third field is a constant
599f22ef01cSRoman Divacky /// string containing the name of the translation unit.  The fourth field is
600f22ef01cSRoman Divacky /// the line number in the file of the annotated value declaration.
601f22ef01cSRoman Divacky ///
602f22ef01cSRoman Divacky /// FIXME: this does not unique the annotation string constants, as llvm-gcc
603f22ef01cSRoman Divacky ///        appears to.
604f22ef01cSRoman Divacky ///
605f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
606f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
607f22ef01cSRoman Divacky                                                 unsigned LineNo) {
608f22ef01cSRoman Divacky   llvm::Module *M = &getModule();
609f22ef01cSRoman Divacky 
610f22ef01cSRoman Divacky   // get [N x i8] constants for the annotation string, and the filename string
611f22ef01cSRoman Divacky   // which are the 2nd and 3rd elements of the global annotation structure.
612f22ef01cSRoman Divacky   const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
613f22ef01cSRoman Divacky   llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
614f22ef01cSRoman Divacky                                                   AA->getAnnotation(), true);
615f22ef01cSRoman Divacky   llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
616f22ef01cSRoman Divacky                                                   M->getModuleIdentifier(),
617f22ef01cSRoman Divacky                                                   true);
618f22ef01cSRoman Divacky 
619f22ef01cSRoman Divacky   // Get the two global values corresponding to the ConstantArrays we just
620f22ef01cSRoman Divacky   // created to hold the bytes of the strings.
621f22ef01cSRoman Divacky   llvm::GlobalValue *annoGV =
622f22ef01cSRoman Divacky     new llvm::GlobalVariable(*M, anno->getType(), false,
623f22ef01cSRoman Divacky                              llvm::GlobalValue::PrivateLinkage, anno,
624f22ef01cSRoman Divacky                              GV->getName());
625f22ef01cSRoman Divacky   // translation unit name string, emitted into the llvm.metadata section.
626f22ef01cSRoman Divacky   llvm::GlobalValue *unitGV =
627f22ef01cSRoman Divacky     new llvm::GlobalVariable(*M, unit->getType(), false,
628f22ef01cSRoman Divacky                              llvm::GlobalValue::PrivateLinkage, unit,
629f22ef01cSRoman Divacky                              ".str");
630f22ef01cSRoman Divacky 
631f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
632f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
633f22ef01cSRoman Divacky     llvm::ConstantExpr::getBitCast(GV, SBP),
634f22ef01cSRoman Divacky     llvm::ConstantExpr::getBitCast(annoGV, SBP),
635f22ef01cSRoman Divacky     llvm::ConstantExpr::getBitCast(unitGV, SBP),
636f22ef01cSRoman Divacky     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
637f22ef01cSRoman Divacky   };
638f22ef01cSRoman Divacky   return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
639f22ef01cSRoman Divacky }
640f22ef01cSRoman Divacky 
641ffd1746dSEd Schouten static CodeGenModule::GVALinkage
642ffd1746dSEd Schouten GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) {
643ffd1746dSEd Schouten   // If this is a static data member, compute the kind of template
644ffd1746dSEd Schouten   // specialization. Otherwise, this variable is not part of a
645ffd1746dSEd Schouten   // template.
646ffd1746dSEd Schouten   TemplateSpecializationKind TSK = TSK_Undeclared;
647ffd1746dSEd Schouten   if (VD->isStaticDataMember())
648ffd1746dSEd Schouten     TSK = VD->getTemplateSpecializationKind();
649ffd1746dSEd Schouten 
650ffd1746dSEd Schouten   Linkage L = VD->getLinkage();
651ffd1746dSEd Schouten   if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
652ffd1746dSEd Schouten       VD->getType()->getLinkage() == UniqueExternalLinkage)
653ffd1746dSEd Schouten     L = UniqueExternalLinkage;
654ffd1746dSEd Schouten 
655ffd1746dSEd Schouten   switch (L) {
656ffd1746dSEd Schouten   case NoLinkage:
657ffd1746dSEd Schouten   case InternalLinkage:
658ffd1746dSEd Schouten   case UniqueExternalLinkage:
659ffd1746dSEd Schouten     return CodeGenModule::GVA_Internal;
660ffd1746dSEd Schouten 
661ffd1746dSEd Schouten   case ExternalLinkage:
662ffd1746dSEd Schouten     switch (TSK) {
663ffd1746dSEd Schouten     case TSK_Undeclared:
664ffd1746dSEd Schouten     case TSK_ExplicitSpecialization:
665ffd1746dSEd Schouten       return CodeGenModule::GVA_StrongExternal;
666ffd1746dSEd Schouten 
667ffd1746dSEd Schouten     case TSK_ExplicitInstantiationDeclaration:
668ffd1746dSEd Schouten       llvm_unreachable("Variable should not be instantiated");
669ffd1746dSEd Schouten       // Fall through to treat this like any other instantiation.
670ffd1746dSEd Schouten 
671ffd1746dSEd Schouten     case TSK_ExplicitInstantiationDefinition:
672ffd1746dSEd Schouten       return CodeGenModule::GVA_ExplicitTemplateInstantiation;
673ffd1746dSEd Schouten 
674ffd1746dSEd Schouten     case TSK_ImplicitInstantiation:
675ffd1746dSEd Schouten       return CodeGenModule::GVA_TemplateInstantiation;
676ffd1746dSEd Schouten     }
677ffd1746dSEd Schouten   }
678ffd1746dSEd Schouten 
679ffd1746dSEd Schouten   return CodeGenModule::GVA_StrongExternal;
680ffd1746dSEd Schouten }
681ffd1746dSEd Schouten 
682f22ef01cSRoman Divacky bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
683f22ef01cSRoman Divacky   // Never defer when EmitAllDecls is specified or the decl has
684f22ef01cSRoman Divacky   // attribute used.
685f22ef01cSRoman Divacky   if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
686f22ef01cSRoman Divacky     return false;
687f22ef01cSRoman Divacky 
688f22ef01cSRoman Divacky   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
689f22ef01cSRoman Divacky     // Constructors and destructors should never be deferred.
690f22ef01cSRoman Divacky     if (FD->hasAttr<ConstructorAttr>() ||
691f22ef01cSRoman Divacky         FD->hasAttr<DestructorAttr>())
692f22ef01cSRoman Divacky       return false;
693f22ef01cSRoman Divacky 
694f22ef01cSRoman Divacky     // The key function for a class must never be deferred.
695f22ef01cSRoman Divacky     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Global)) {
696f22ef01cSRoman Divacky       const CXXRecordDecl *RD = MD->getParent();
697f22ef01cSRoman Divacky       if (MD->isOutOfLine() && RD->isDynamicClass()) {
698f22ef01cSRoman Divacky         const CXXMethodDecl *KeyFunction = getContext().getKeyFunction(RD);
699f22ef01cSRoman Divacky         if (KeyFunction &&
700f22ef01cSRoman Divacky             KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
701f22ef01cSRoman Divacky           return false;
702f22ef01cSRoman Divacky       }
703f22ef01cSRoman Divacky     }
704f22ef01cSRoman Divacky 
705f22ef01cSRoman Divacky     GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
706f22ef01cSRoman Divacky 
707f22ef01cSRoman Divacky     // static, static inline, always_inline, and extern inline functions can
708f22ef01cSRoman Divacky     // always be deferred.  Normal inline functions can be deferred in C99/C++.
709f22ef01cSRoman Divacky     // Implicit template instantiations can also be deferred in C++.
710f22ef01cSRoman Divacky     if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
711f22ef01cSRoman Divacky         Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
712f22ef01cSRoman Divacky       return true;
713f22ef01cSRoman Divacky     return false;
714f22ef01cSRoman Divacky   }
715f22ef01cSRoman Divacky 
716f22ef01cSRoman Divacky   const VarDecl *VD = cast<VarDecl>(Global);
717f22ef01cSRoman Divacky   assert(VD->isFileVarDecl() && "Invalid decl");
718f22ef01cSRoman Divacky 
719f22ef01cSRoman Divacky   // We never want to defer structs that have non-trivial constructors or
720f22ef01cSRoman Divacky   // destructors.
721f22ef01cSRoman Divacky 
722f22ef01cSRoman Divacky   // FIXME: Handle references.
723f22ef01cSRoman Divacky   if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
724f22ef01cSRoman Divacky     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
725f22ef01cSRoman Divacky       if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())
726f22ef01cSRoman Divacky         return false;
727f22ef01cSRoman Divacky     }
728f22ef01cSRoman Divacky   }
729f22ef01cSRoman Divacky 
730ffd1746dSEd Schouten   GVALinkage L = GetLinkageForVariable(getContext(), VD);
731ffd1746dSEd Schouten   if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
732ffd1746dSEd Schouten     if (!(VD->getInit() && VD->getInit()->HasSideEffects(Context)))
733ffd1746dSEd Schouten       return true;
734f22ef01cSRoman Divacky   }
735f22ef01cSRoman Divacky 
736f22ef01cSRoman Divacky   return false;
737f22ef01cSRoman Divacky }
738f22ef01cSRoman Divacky 
739f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
740f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
741f22ef01cSRoman Divacky   assert(AA && "No alias?");
742f22ef01cSRoman Divacky 
743f22ef01cSRoman Divacky   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
744f22ef01cSRoman Divacky 
745f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
746f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
747f22ef01cSRoman Divacky 
748f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
749f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
750f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
751f22ef01cSRoman Divacky   else
752f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
753f22ef01cSRoman Divacky                                     llvm::PointerType::getUnqual(DeclTy), 0);
754f22ef01cSRoman Divacky   if (!Entry) {
755f22ef01cSRoman Divacky     llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
756f22ef01cSRoman Divacky     F->setLinkage(llvm::Function::ExternalWeakLinkage);
757f22ef01cSRoman Divacky     WeakRefReferences.insert(F);
758f22ef01cSRoman Divacky   }
759f22ef01cSRoman Divacky 
760f22ef01cSRoman Divacky   return Aliasee;
761f22ef01cSRoman Divacky }
762f22ef01cSRoman Divacky 
763f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
764f22ef01cSRoman Divacky   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
765f22ef01cSRoman Divacky 
766f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
767f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
768f22ef01cSRoman Divacky     return;
769f22ef01cSRoman Divacky 
770f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
771f22ef01cSRoman Divacky   // emit it now.
772f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
773f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
774f22ef01cSRoman Divacky 
775f22ef01cSRoman Divacky   // Ignore declarations, they will be emitted on their first use.
776f22ef01cSRoman Divacky   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
777f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
778f22ef01cSRoman Divacky     if (!FD->isThisDeclarationADefinition())
779f22ef01cSRoman Divacky       return;
780f22ef01cSRoman Divacky   } else {
781f22ef01cSRoman Divacky     const VarDecl *VD = cast<VarDecl>(Global);
782f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
783f22ef01cSRoman Divacky 
784f22ef01cSRoman Divacky     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
785f22ef01cSRoman Divacky       return;
786f22ef01cSRoman Divacky   }
787f22ef01cSRoman Divacky 
788f22ef01cSRoman Divacky   // Defer code generation when possible if this is a static definition, inline
789f22ef01cSRoman Divacky   // function etc.  These we only want to emit if they are used.
790f22ef01cSRoman Divacky   if (!MayDeferGeneration(Global)) {
791f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
792f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
793f22ef01cSRoman Divacky     return;
794f22ef01cSRoman Divacky   }
795f22ef01cSRoman Divacky 
796f22ef01cSRoman Divacky   // If the value has already been used, add it directly to the
797f22ef01cSRoman Divacky   // DeferredDeclsToEmit list.
798ffd1746dSEd Schouten   llvm::StringRef MangledName = getMangledName(GD);
799f22ef01cSRoman Divacky   if (GetGlobalValue(MangledName))
800f22ef01cSRoman Divacky     DeferredDeclsToEmit.push_back(GD);
801f22ef01cSRoman Divacky   else {
802f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
803f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
804f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
805f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
806f22ef01cSRoman Divacky   }
807f22ef01cSRoman Divacky }
808f22ef01cSRoman Divacky 
809f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
810f22ef01cSRoman Divacky   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
811f22ef01cSRoman Divacky 
812f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
813f22ef01cSRoman Divacky                                  Context.getSourceManager(),
814f22ef01cSRoman Divacky                                  "Generating code for declaration");
815f22ef01cSRoman Divacky 
816ffd1746dSEd Schouten   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
817ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
818ffd1746dSEd Schouten     // linkage.
819ffd1746dSEd Schouten     if (CodeGenOpts.OptimizationLevel == 0 &&
820ffd1746dSEd Schouten         getFunctionLinkage(Function)
821ffd1746dSEd Schouten                                   == llvm::Function::AvailableExternallyLinkage)
822ffd1746dSEd Schouten       return;
823ffd1746dSEd Schouten 
824ffd1746dSEd Schouten     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
825f22ef01cSRoman Divacky       if (Method->isVirtual())
826f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
827f22ef01cSRoman Divacky 
828ffd1746dSEd Schouten       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
829f22ef01cSRoman Divacky         return EmitCXXConstructor(CD, GD.getCtorType());
830f22ef01cSRoman Divacky 
831ffd1746dSEd Schouten       if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
832f22ef01cSRoman Divacky         return EmitCXXDestructor(DD, GD.getDtorType());
833ffd1746dSEd Schouten     }
834f22ef01cSRoman Divacky 
835f22ef01cSRoman Divacky     return EmitGlobalFunctionDefinition(GD);
836ffd1746dSEd Schouten   }
837f22ef01cSRoman Divacky 
838f22ef01cSRoman Divacky   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
839f22ef01cSRoman Divacky     return EmitGlobalVarDefinition(VD);
840f22ef01cSRoman Divacky 
841f22ef01cSRoman Divacky   assert(0 && "Invalid argument to EmitGlobalDefinition()");
842f22ef01cSRoman Divacky }
843f22ef01cSRoman Divacky 
844f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
845f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
846f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
847f22ef01cSRoman Divacky /// bitcasted to the right type.
848f22ef01cSRoman Divacky ///
849f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
850f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
851f22ef01cSRoman Divacky llvm::Constant *
852f22ef01cSRoman Divacky CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
853f22ef01cSRoman Divacky                                        const llvm::Type *Ty,
854f22ef01cSRoman Divacky                                        GlobalDecl D) {
855f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
856f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
857f22ef01cSRoman Divacky   if (Entry) {
858f22ef01cSRoman Divacky     if (WeakRefReferences.count(Entry)) {
859f22ef01cSRoman Divacky       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
860f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
861f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
862f22ef01cSRoman Divacky 
863f22ef01cSRoman Divacky       WeakRefReferences.erase(Entry);
864f22ef01cSRoman Divacky     }
865f22ef01cSRoman Divacky 
866f22ef01cSRoman Divacky     if (Entry->getType()->getElementType() == Ty)
867f22ef01cSRoman Divacky       return Entry;
868f22ef01cSRoman Divacky 
869f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
870f22ef01cSRoman Divacky     const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
871f22ef01cSRoman Divacky     return llvm::ConstantExpr::getBitCast(Entry, PTy);
872f22ef01cSRoman Divacky   }
873f22ef01cSRoman Divacky 
874f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
875f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
876f22ef01cSRoman Divacky   // sure not to try to set attributes.
877f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
878f22ef01cSRoman Divacky 
879f22ef01cSRoman Divacky   const llvm::FunctionType *FTy;
880f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
881f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
882f22ef01cSRoman Divacky   } else {
883f22ef01cSRoman Divacky     FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
884f22ef01cSRoman Divacky                                   std::vector<const llvm::Type*>(), false);
885f22ef01cSRoman Divacky     IsIncompleteFunction = true;
886f22ef01cSRoman Divacky   }
887ffd1746dSEd Schouten 
888f22ef01cSRoman Divacky   llvm::Function *F = llvm::Function::Create(FTy,
889f22ef01cSRoman Divacky                                              llvm::Function::ExternalLinkage,
890f22ef01cSRoman Divacky                                              MangledName, &getModule());
891f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
892f22ef01cSRoman Divacky   if (D.getDecl())
893f22ef01cSRoman Divacky     SetFunctionAttributes(D, F, IsIncompleteFunction);
894f22ef01cSRoman Divacky 
895f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
896f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
897f22ef01cSRoman Divacky   // of the file.
898f22ef01cSRoman Divacky   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
899f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
900f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
901f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
902f22ef01cSRoman Divacky     DeferredDeclsToEmit.push_back(DDI->second);
903f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
904f22ef01cSRoman Divacky   } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
905f22ef01cSRoman Divacky     // If this the first reference to a C++ inline function in a class, queue up
906f22ef01cSRoman Divacky     // the deferred function body for emission.  These are not seen as
907f22ef01cSRoman Divacky     // top-level declarations.
908f22ef01cSRoman Divacky     if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
909f22ef01cSRoman Divacky       DeferredDeclsToEmit.push_back(D);
910f22ef01cSRoman Divacky     // A called constructor which has no definition or declaration need be
911f22ef01cSRoman Divacky     // synthesized.
912f22ef01cSRoman Divacky     else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
913f22ef01cSRoman Divacky       if (CD->isImplicit()) {
914f22ef01cSRoman Divacky         assert(CD->isUsed() && "Sema doesn't consider constructor as used.");
915f22ef01cSRoman Divacky         DeferredDeclsToEmit.push_back(D);
916f22ef01cSRoman Divacky       }
917f22ef01cSRoman Divacky     } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
918f22ef01cSRoman Divacky       if (DD->isImplicit()) {
919f22ef01cSRoman Divacky         assert(DD->isUsed() && "Sema doesn't consider destructor as used.");
920f22ef01cSRoman Divacky         DeferredDeclsToEmit.push_back(D);
921f22ef01cSRoman Divacky       }
922f22ef01cSRoman Divacky     } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
923f22ef01cSRoman Divacky       if (MD->isCopyAssignment() && MD->isImplicit()) {
924f22ef01cSRoman Divacky         assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used.");
925f22ef01cSRoman Divacky         DeferredDeclsToEmit.push_back(D);
926f22ef01cSRoman Divacky       }
927f22ef01cSRoman Divacky     }
928f22ef01cSRoman Divacky   }
929f22ef01cSRoman Divacky 
930f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
931f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
932f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
933f22ef01cSRoman Divacky     return F;
934f22ef01cSRoman Divacky   }
935f22ef01cSRoman Divacky 
936f22ef01cSRoman Divacky   const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
937f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
938f22ef01cSRoman Divacky }
939f22ef01cSRoman Divacky 
940f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
941f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
942f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
943f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
944f22ef01cSRoman Divacky                                                  const llvm::Type *Ty) {
945f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
946f22ef01cSRoman Divacky   if (!Ty)
947f22ef01cSRoman Divacky     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
948ffd1746dSEd Schouten 
949ffd1746dSEd Schouten   llvm::StringRef MangledName = getMangledName(GD);
950f22ef01cSRoman Divacky   return GetOrCreateLLVMFunction(MangledName, Ty, GD);
951f22ef01cSRoman Divacky }
952f22ef01cSRoman Divacky 
953f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
954f22ef01cSRoman Divacky /// type and name.
955f22ef01cSRoman Divacky llvm::Constant *
956f22ef01cSRoman Divacky CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
957f22ef01cSRoman Divacky                                      llvm::StringRef Name) {
958f22ef01cSRoman Divacky   return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
959f22ef01cSRoman Divacky }
960f22ef01cSRoman Divacky 
961f22ef01cSRoman Divacky static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
962f22ef01cSRoman Divacky   if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
963f22ef01cSRoman Divacky     return false;
964f22ef01cSRoman Divacky   if (Context.getLangOptions().CPlusPlus &&
965f22ef01cSRoman Divacky       Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
966f22ef01cSRoman Divacky     // FIXME: We should do something fancier here!
967f22ef01cSRoman Divacky     return false;
968f22ef01cSRoman Divacky   }
969f22ef01cSRoman Divacky   return true;
970f22ef01cSRoman Divacky }
971f22ef01cSRoman Divacky 
972f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
973f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
974f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
975f22ef01cSRoman Divacky /// bitcasted to the right type.
976f22ef01cSRoman Divacky ///
977f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
978f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
979f22ef01cSRoman Divacky llvm::Constant *
980f22ef01cSRoman Divacky CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
981f22ef01cSRoman Divacky                                      const llvm::PointerType *Ty,
982f22ef01cSRoman Divacky                                      const VarDecl *D) {
983f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
984f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
985f22ef01cSRoman Divacky   if (Entry) {
986f22ef01cSRoman Divacky     if (WeakRefReferences.count(Entry)) {
987f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
988f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
989f22ef01cSRoman Divacky 
990f22ef01cSRoman Divacky       WeakRefReferences.erase(Entry);
991f22ef01cSRoman Divacky     }
992f22ef01cSRoman Divacky 
993f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
994f22ef01cSRoman Divacky       return Entry;
995f22ef01cSRoman Divacky 
996f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
997f22ef01cSRoman Divacky     return llvm::ConstantExpr::getBitCast(Entry, Ty);
998f22ef01cSRoman Divacky   }
999f22ef01cSRoman Divacky 
1000f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
1001f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
1002f22ef01cSRoman Divacky   // of the file.
1003f22ef01cSRoman Divacky   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1004f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
1005f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1006f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
1007f22ef01cSRoman Divacky     DeferredDeclsToEmit.push_back(DDI->second);
1008f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
1009f22ef01cSRoman Divacky   }
1010f22ef01cSRoman Divacky 
1011f22ef01cSRoman Divacky   llvm::GlobalVariable *GV =
1012f22ef01cSRoman Divacky     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1013f22ef01cSRoman Divacky                              llvm::GlobalValue::ExternalLinkage,
1014f22ef01cSRoman Divacky                              0, MangledName, 0,
1015f22ef01cSRoman Divacky                              false, Ty->getAddressSpace());
1016f22ef01cSRoman Divacky 
1017f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
1018f22ef01cSRoman Divacky   if (D) {
1019f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
1020f22ef01cSRoman Divacky     // handling.
1021f22ef01cSRoman Divacky     GV->setConstant(DeclIsConstantGlobal(Context, D));
1022f22ef01cSRoman Divacky 
1023f22ef01cSRoman Divacky     // FIXME: Merge with other attribute handling code.
1024f22ef01cSRoman Divacky     if (D->getStorageClass() == VarDecl::PrivateExtern)
1025f22ef01cSRoman Divacky       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1026f22ef01cSRoman Divacky 
1027f22ef01cSRoman Divacky     if (D->hasAttr<WeakAttr>() ||
1028f22ef01cSRoman Divacky         D->hasAttr<WeakImportAttr>())
1029f22ef01cSRoman Divacky       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1030f22ef01cSRoman Divacky 
1031f22ef01cSRoman Divacky     GV->setThreadLocal(D->isThreadSpecified());
1032f22ef01cSRoman Divacky   }
1033f22ef01cSRoman Divacky 
1034f22ef01cSRoman Divacky   return GV;
1035f22ef01cSRoman Divacky }
1036f22ef01cSRoman Divacky 
1037f22ef01cSRoman Divacky 
1038f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1039f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
1040f22ef01cSRoman Divacky /// then it will be greated with the specified type instead of whatever the
1041f22ef01cSRoman Divacky /// normal requested type would be.
1042f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1043f22ef01cSRoman Divacky                                                   const llvm::Type *Ty) {
1044f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
1045f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
1046f22ef01cSRoman Divacky   if (Ty == 0)
1047f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
1048f22ef01cSRoman Divacky 
1049f22ef01cSRoman Divacky   const llvm::PointerType *PTy =
1050f22ef01cSRoman Divacky     llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
1051f22ef01cSRoman Divacky 
1052ffd1746dSEd Schouten   llvm::StringRef MangledName = getMangledName(D);
1053f22ef01cSRoman Divacky   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1054f22ef01cSRoman Divacky }
1055f22ef01cSRoman Divacky 
1056f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
1057f22ef01cSRoman Divacky /// specified type and name.
1058f22ef01cSRoman Divacky llvm::Constant *
1059f22ef01cSRoman Divacky CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
1060f22ef01cSRoman Divacky                                      llvm::StringRef Name) {
1061f22ef01cSRoman Divacky   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
1062f22ef01cSRoman Divacky }
1063f22ef01cSRoman Divacky 
1064f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1065f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
1066f22ef01cSRoman Divacky 
1067f22ef01cSRoman Divacky   if (MayDeferGeneration(D)) {
1068f22ef01cSRoman Divacky     // If we have not seen a reference to this variable yet, place it
1069f22ef01cSRoman Divacky     // into the deferred declarations table to be emitted if needed
1070f22ef01cSRoman Divacky     // later.
1071ffd1746dSEd Schouten     llvm::StringRef MangledName = getMangledName(D);
1072f22ef01cSRoman Divacky     if (!GetGlobalValue(MangledName)) {
1073f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
1074f22ef01cSRoman Divacky       return;
1075f22ef01cSRoman Divacky     }
1076f22ef01cSRoman Divacky   }
1077f22ef01cSRoman Divacky 
1078f22ef01cSRoman Divacky   // The tentative definition is the only definition.
1079f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
1080f22ef01cSRoman Divacky }
1081f22ef01cSRoman Divacky 
1082f22ef01cSRoman Divacky void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1083f22ef01cSRoman Divacky   if (DefinitionRequired)
1084f22ef01cSRoman Divacky     getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1085f22ef01cSRoman Divacky }
1086f22ef01cSRoman Divacky 
1087f22ef01cSRoman Divacky llvm::GlobalVariable::LinkageTypes
1088f22ef01cSRoman Divacky CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1089f22ef01cSRoman Divacky   if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1090f22ef01cSRoman Divacky     return llvm::GlobalVariable::InternalLinkage;
1091f22ef01cSRoman Divacky 
1092f22ef01cSRoman Divacky   if (const CXXMethodDecl *KeyFunction
1093f22ef01cSRoman Divacky                                     = RD->getASTContext().getKeyFunction(RD)) {
1094f22ef01cSRoman Divacky     // If this class has a key function, use that to determine the linkage of
1095f22ef01cSRoman Divacky     // the vtable.
1096f22ef01cSRoman Divacky     const FunctionDecl *Def = 0;
1097ffd1746dSEd Schouten     if (KeyFunction->hasBody(Def))
1098f22ef01cSRoman Divacky       KeyFunction = cast<CXXMethodDecl>(Def);
1099f22ef01cSRoman Divacky 
1100f22ef01cSRoman Divacky     switch (KeyFunction->getTemplateSpecializationKind()) {
1101f22ef01cSRoman Divacky       case TSK_Undeclared:
1102f22ef01cSRoman Divacky       case TSK_ExplicitSpecialization:
1103f22ef01cSRoman Divacky         if (KeyFunction->isInlined())
1104f22ef01cSRoman Divacky           return llvm::GlobalVariable::WeakODRLinkage;
1105f22ef01cSRoman Divacky 
1106f22ef01cSRoman Divacky         return llvm::GlobalVariable::ExternalLinkage;
1107f22ef01cSRoman Divacky 
1108f22ef01cSRoman Divacky       case TSK_ImplicitInstantiation:
1109f22ef01cSRoman Divacky       case TSK_ExplicitInstantiationDefinition:
1110f22ef01cSRoman Divacky         return llvm::GlobalVariable::WeakODRLinkage;
1111f22ef01cSRoman Divacky 
1112f22ef01cSRoman Divacky       case TSK_ExplicitInstantiationDeclaration:
1113f22ef01cSRoman Divacky         // FIXME: Use available_externally linkage. However, this currently
1114f22ef01cSRoman Divacky         // breaks LLVM's build due to undefined symbols.
1115f22ef01cSRoman Divacky         //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1116f22ef01cSRoman Divacky         return llvm::GlobalVariable::WeakODRLinkage;
1117f22ef01cSRoman Divacky     }
1118f22ef01cSRoman Divacky   }
1119f22ef01cSRoman Divacky 
1120f22ef01cSRoman Divacky   switch (RD->getTemplateSpecializationKind()) {
1121f22ef01cSRoman Divacky   case TSK_Undeclared:
1122f22ef01cSRoman Divacky   case TSK_ExplicitSpecialization:
1123f22ef01cSRoman Divacky   case TSK_ImplicitInstantiation:
1124f22ef01cSRoman Divacky   case TSK_ExplicitInstantiationDefinition:
1125f22ef01cSRoman Divacky     return llvm::GlobalVariable::WeakODRLinkage;
1126f22ef01cSRoman Divacky 
1127f22ef01cSRoman Divacky   case TSK_ExplicitInstantiationDeclaration:
1128f22ef01cSRoman Divacky     // FIXME: Use available_externally linkage. However, this currently
1129f22ef01cSRoman Divacky     // breaks LLVM's build due to undefined symbols.
1130f22ef01cSRoman Divacky     //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1131f22ef01cSRoman Divacky     return llvm::GlobalVariable::WeakODRLinkage;
1132f22ef01cSRoman Divacky   }
1133f22ef01cSRoman Divacky 
1134f22ef01cSRoman Divacky   // Silence GCC warning.
1135f22ef01cSRoman Divacky   return llvm::GlobalVariable::WeakODRLinkage;
1136f22ef01cSRoman Divacky }
1137f22ef01cSRoman Divacky 
1138f22ef01cSRoman Divacky CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1139f22ef01cSRoman Divacky     return CharUnits::fromQuantity(
1140f22ef01cSRoman Divacky       TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth());
1141f22ef01cSRoman Divacky }
1142f22ef01cSRoman Divacky 
1143f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1144f22ef01cSRoman Divacky   llvm::Constant *Init = 0;
1145f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
1146f22ef01cSRoman Divacky   bool NonConstInit = false;
1147f22ef01cSRoman Divacky 
1148f22ef01cSRoman Divacky   const Expr *InitExpr = D->getAnyInitializer();
1149f22ef01cSRoman Divacky 
1150f22ef01cSRoman Divacky   if (!InitExpr) {
1151f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
1152f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
1153f22ef01cSRoman Divacky     //
1154f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
1155f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
1156f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
1157f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
1158f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
1159f22ef01cSRoman Divacky     // to do a RAUW.
1160f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1161f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
1162f22ef01cSRoman Divacky   } else {
1163f22ef01cSRoman Divacky     Init = EmitConstantExpr(InitExpr, D->getType());
1164f22ef01cSRoman Divacky     if (!Init) {
1165f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
1166f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
1167f22ef01cSRoman Divacky         T = D->getType();
1168f22ef01cSRoman Divacky 
1169f22ef01cSRoman Divacky       if (getLangOptions().CPlusPlus) {
1170f22ef01cSRoman Divacky         EmitCXXGlobalVarDeclInitFunc(D);
1171f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
1172f22ef01cSRoman Divacky         NonConstInit = true;
1173f22ef01cSRoman Divacky       } else {
1174f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
1175f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1176f22ef01cSRoman Divacky       }
1177f22ef01cSRoman Divacky     }
1178f22ef01cSRoman Divacky   }
1179f22ef01cSRoman Divacky 
1180f22ef01cSRoman Divacky   const llvm::Type* InitType = Init->getType();
1181f22ef01cSRoman Divacky   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1182f22ef01cSRoman Divacky 
1183f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
1184f22ef01cSRoman Divacky   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1185f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1186f22ef01cSRoman Divacky            // all zero index gep.
1187f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1188f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
1189f22ef01cSRoman Divacky   }
1190f22ef01cSRoman Divacky 
1191f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
1192f22ef01cSRoman Divacky   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1193f22ef01cSRoman Divacky 
1194f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
1195f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
1196f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
1197f22ef01cSRoman Divacky   // (which will be a definition).
1198f22ef01cSRoman Divacky   //
1199f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
1200f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
1201f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
1202f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
1203f22ef01cSRoman Divacky   if (GV == 0 ||
1204f22ef01cSRoman Divacky       GV->getType()->getElementType() != InitType ||
1205f22ef01cSRoman Divacky       GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
1206f22ef01cSRoman Divacky 
1207f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
1208f22ef01cSRoman Divacky     Entry->setName(llvm::StringRef());
1209f22ef01cSRoman Divacky 
1210f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
1211f22ef01cSRoman Divacky     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1212f22ef01cSRoman Divacky 
1213f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
1214f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
1215f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1216f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1217f22ef01cSRoman Divacky 
1218f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
1219f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1220f22ef01cSRoman Divacky   }
1221f22ef01cSRoman Divacky 
1222f22ef01cSRoman Divacky   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1223f22ef01cSRoman Divacky     SourceManager &SM = Context.getSourceManager();
1224f22ef01cSRoman Divacky     AddAnnotation(EmitAnnotateAttr(GV, AA,
1225f22ef01cSRoman Divacky                               SM.getInstantiationLineNumber(D->getLocation())));
1226f22ef01cSRoman Divacky   }
1227f22ef01cSRoman Divacky 
1228f22ef01cSRoman Divacky   GV->setInitializer(Init);
1229f22ef01cSRoman Divacky 
1230f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
1231f22ef01cSRoman Divacky   GV->setConstant(false);
1232f22ef01cSRoman Divacky   if (!NonConstInit && DeclIsConstantGlobal(Context, D))
1233f22ef01cSRoman Divacky     GV->setConstant(true);
1234f22ef01cSRoman Divacky 
1235f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1236f22ef01cSRoman Divacky 
1237f22ef01cSRoman Divacky   // Set the llvm linkage type as appropriate.
1238f22ef01cSRoman Divacky   GVALinkage Linkage = GetLinkageForVariable(getContext(), D);
1239f22ef01cSRoman Divacky   if (Linkage == GVA_Internal)
1240f22ef01cSRoman Divacky     GV->setLinkage(llvm::Function::InternalLinkage);
1241f22ef01cSRoman Divacky   else if (D->hasAttr<DLLImportAttr>())
1242f22ef01cSRoman Divacky     GV->setLinkage(llvm::Function::DLLImportLinkage);
1243f22ef01cSRoman Divacky   else if (D->hasAttr<DLLExportAttr>())
1244f22ef01cSRoman Divacky     GV->setLinkage(llvm::Function::DLLExportLinkage);
1245f22ef01cSRoman Divacky   else if (D->hasAttr<WeakAttr>()) {
1246f22ef01cSRoman Divacky     if (GV->isConstant())
1247f22ef01cSRoman Divacky       GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage);
1248f22ef01cSRoman Divacky     else
1249f22ef01cSRoman Divacky       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1250f22ef01cSRoman Divacky   } else if (Linkage == GVA_TemplateInstantiation ||
1251f22ef01cSRoman Divacky              Linkage == GVA_ExplicitTemplateInstantiation)
1252f22ef01cSRoman Divacky     // FIXME: It seems like we can provide more specific linkage here
1253f22ef01cSRoman Divacky     // (LinkOnceODR, WeakODR).
1254f22ef01cSRoman Divacky     GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1255f22ef01cSRoman Divacky   else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon &&
1256f22ef01cSRoman Divacky            !D->hasExternalStorage() && !D->getInit() &&
1257f22ef01cSRoman Divacky            !D->getAttr<SectionAttr>()) {
1258f22ef01cSRoman Divacky     GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
1259f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
1260f22ef01cSRoman Divacky     GV->setConstant(false);
1261f22ef01cSRoman Divacky   } else
1262f22ef01cSRoman Divacky     GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
1263f22ef01cSRoman Divacky 
1264f22ef01cSRoman Divacky   SetCommonAttributes(D, GV);
1265f22ef01cSRoman Divacky 
1266f22ef01cSRoman Divacky   // Emit global variable debug information.
1267f22ef01cSRoman Divacky   if (CGDebugInfo *DI = getDebugInfo()) {
1268f22ef01cSRoman Divacky     DI->setLocation(D->getLocation());
1269f22ef01cSRoman Divacky     DI->EmitGlobalVariable(GV, D);
1270f22ef01cSRoman Divacky   }
1271f22ef01cSRoman Divacky }
1272f22ef01cSRoman Divacky 
1273f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1274f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
1275f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
1276f22ef01cSRoman Divacky /// call the new function directly.
1277f22ef01cSRoman Divacky ///
1278f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
1279f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
1280f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
1281f22ef01cSRoman Divacky /// run at -O0.
1282f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1283f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
1284f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
1285f22ef01cSRoman Divacky   llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1286f22ef01cSRoman Divacky   if (OldFn == 0) return;
1287f22ef01cSRoman Divacky 
1288f22ef01cSRoman Divacky   const llvm::Type *NewRetTy = NewFn->getReturnType();
1289f22ef01cSRoman Divacky   llvm::SmallVector<llvm::Value*, 4> ArgList;
1290f22ef01cSRoman Divacky 
1291f22ef01cSRoman Divacky   for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1292f22ef01cSRoman Divacky        UI != E; ) {
1293f22ef01cSRoman Divacky     // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1294f22ef01cSRoman Divacky     llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1295f22ef01cSRoman Divacky     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1296f22ef01cSRoman Divacky     llvm::CallSite CS(CI);
1297f22ef01cSRoman Divacky     if (!CI || !CS.isCallee(I)) continue;
1298f22ef01cSRoman Divacky 
1299f22ef01cSRoman Divacky     // If the return types don't match exactly, and if the call isn't dead, then
1300f22ef01cSRoman Divacky     // we can't transform this call.
1301f22ef01cSRoman Divacky     if (CI->getType() != NewRetTy && !CI->use_empty())
1302f22ef01cSRoman Divacky       continue;
1303f22ef01cSRoman Divacky 
1304f22ef01cSRoman Divacky     // If the function was passed too few arguments, don't transform.  If extra
1305f22ef01cSRoman Divacky     // arguments were passed, we silently drop them.  If any of the types
1306f22ef01cSRoman Divacky     // mismatch, we don't transform.
1307f22ef01cSRoman Divacky     unsigned ArgNo = 0;
1308f22ef01cSRoman Divacky     bool DontTransform = false;
1309f22ef01cSRoman Divacky     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1310f22ef01cSRoman Divacky          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1311f22ef01cSRoman Divacky       if (CS.arg_size() == ArgNo ||
1312f22ef01cSRoman Divacky           CS.getArgument(ArgNo)->getType() != AI->getType()) {
1313f22ef01cSRoman Divacky         DontTransform = true;
1314f22ef01cSRoman Divacky         break;
1315f22ef01cSRoman Divacky       }
1316f22ef01cSRoman Divacky     }
1317f22ef01cSRoman Divacky     if (DontTransform)
1318f22ef01cSRoman Divacky       continue;
1319f22ef01cSRoman Divacky 
1320f22ef01cSRoman Divacky     // Okay, we can transform this.  Create the new call instruction and copy
1321f22ef01cSRoman Divacky     // over the required information.
1322f22ef01cSRoman Divacky     ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1323f22ef01cSRoman Divacky     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1324f22ef01cSRoman Divacky                                                      ArgList.end(), "", CI);
1325f22ef01cSRoman Divacky     ArgList.clear();
1326f22ef01cSRoman Divacky     if (!NewCall->getType()->isVoidTy())
1327f22ef01cSRoman Divacky       NewCall->takeName(CI);
1328f22ef01cSRoman Divacky     NewCall->setAttributes(CI->getAttributes());
1329f22ef01cSRoman Divacky     NewCall->setCallingConv(CI->getCallingConv());
1330f22ef01cSRoman Divacky 
1331f22ef01cSRoman Divacky     // Finally, remove the old call, replacing any uses with the new one.
1332f22ef01cSRoman Divacky     if (!CI->use_empty())
1333f22ef01cSRoman Divacky       CI->replaceAllUsesWith(NewCall);
1334f22ef01cSRoman Divacky 
1335f22ef01cSRoman Divacky     // Copy debug location attached to CI.
1336f22ef01cSRoman Divacky     if (!CI->getDebugLoc().isUnknown())
1337f22ef01cSRoman Divacky       NewCall->setDebugLoc(CI->getDebugLoc());
1338f22ef01cSRoman Divacky     CI->eraseFromParent();
1339f22ef01cSRoman Divacky   }
1340f22ef01cSRoman Divacky }
1341f22ef01cSRoman Divacky 
1342f22ef01cSRoman Divacky 
1343f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1344f22ef01cSRoman Divacky   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1345f22ef01cSRoman Divacky   const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
1346f22ef01cSRoman Divacky   getMangleContext().mangleInitDiscriminator();
1347f22ef01cSRoman Divacky   // Get or create the prototype for the function.
1348f22ef01cSRoman Divacky   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1349f22ef01cSRoman Divacky 
1350f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
1351f22ef01cSRoman Divacky   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1352f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast);
1353f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
1354f22ef01cSRoman Divacky   }
1355f22ef01cSRoman Divacky 
1356f22ef01cSRoman Divacky 
1357f22ef01cSRoman Divacky   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1358f22ef01cSRoman Divacky     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1359f22ef01cSRoman Divacky 
1360f22ef01cSRoman Divacky     // If the types mismatch then we have to rewrite the definition.
1361f22ef01cSRoman Divacky     assert(OldFn->isDeclaration() &&
1362f22ef01cSRoman Divacky            "Shouldn't replace non-declaration");
1363f22ef01cSRoman Divacky 
1364f22ef01cSRoman Divacky     // F is the Function* for the one with the wrong type, we must make a new
1365f22ef01cSRoman Divacky     // Function* and update everything that used F (a declaration) with the new
1366f22ef01cSRoman Divacky     // Function* (which will be a definition).
1367f22ef01cSRoman Divacky     //
1368f22ef01cSRoman Divacky     // This happens if there is a prototype for a function
1369f22ef01cSRoman Divacky     // (e.g. "int f()") and then a definition of a different type
1370f22ef01cSRoman Divacky     // (e.g. "int f(int x)").  Move the old function aside so that it
1371f22ef01cSRoman Divacky     // doesn't interfere with GetAddrOfFunction.
1372f22ef01cSRoman Divacky     OldFn->setName(llvm::StringRef());
1373f22ef01cSRoman Divacky     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1374f22ef01cSRoman Divacky 
1375f22ef01cSRoman Divacky     // If this is an implementation of a function without a prototype, try to
1376f22ef01cSRoman Divacky     // replace any existing uses of the function (which may be calls) with uses
1377f22ef01cSRoman Divacky     // of the new function
1378f22ef01cSRoman Divacky     if (D->getType()->isFunctionNoProtoType()) {
1379f22ef01cSRoman Divacky       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1380f22ef01cSRoman Divacky       OldFn->removeDeadConstantUsers();
1381f22ef01cSRoman Divacky     }
1382f22ef01cSRoman Divacky 
1383f22ef01cSRoman Divacky     // Replace uses of F with the Function we will endow with a body.
1384f22ef01cSRoman Divacky     if (!Entry->use_empty()) {
1385f22ef01cSRoman Divacky       llvm::Constant *NewPtrForOldDecl =
1386f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1387f22ef01cSRoman Divacky       Entry->replaceAllUsesWith(NewPtrForOldDecl);
1388f22ef01cSRoman Divacky     }
1389f22ef01cSRoman Divacky 
1390f22ef01cSRoman Divacky     // Ok, delete the old function now, which is dead.
1391f22ef01cSRoman Divacky     OldFn->eraseFromParent();
1392f22ef01cSRoman Divacky 
1393f22ef01cSRoman Divacky     Entry = NewFn;
1394f22ef01cSRoman Divacky   }
1395f22ef01cSRoman Divacky 
1396f22ef01cSRoman Divacky   llvm::Function *Fn = cast<llvm::Function>(Entry);
1397f22ef01cSRoman Divacky   setFunctionLinkage(D, Fn);
1398f22ef01cSRoman Divacky 
1399f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateCode(D, Fn);
1400f22ef01cSRoman Divacky 
1401f22ef01cSRoman Divacky   SetFunctionDefinitionAttributes(D, Fn);
1402f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
1403f22ef01cSRoman Divacky 
1404f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1405f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
1406f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1407f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
1408f22ef01cSRoman Divacky }
1409f22ef01cSRoman Divacky 
1410f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1411f22ef01cSRoman Divacky   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1412f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
1413f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
1414f22ef01cSRoman Divacky 
1415ffd1746dSEd Schouten   llvm::StringRef MangledName = getMangledName(GD);
1416f22ef01cSRoman Divacky 
1417f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
1418f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
1419f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1420f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
1421f22ef01cSRoman Divacky     return;
1422f22ef01cSRoman Divacky 
1423f22ef01cSRoman Divacky   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1424f22ef01cSRoman Divacky 
1425f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
1426f22ef01cSRoman Divacky   // if a deferred decl.
1427f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1428f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
1429f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
1430f22ef01cSRoman Divacky   else
1431f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1432f22ef01cSRoman Divacky                                     llvm::PointerType::getUnqual(DeclTy), 0);
1433f22ef01cSRoman Divacky 
1434f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
1435f22ef01cSRoman Divacky   llvm::GlobalValue *GA =
1436f22ef01cSRoman Divacky     new llvm::GlobalAlias(Aliasee->getType(),
1437f22ef01cSRoman Divacky                           llvm::Function::ExternalLinkage,
1438f22ef01cSRoman Divacky                           "", Aliasee, &getModule());
1439f22ef01cSRoman Divacky 
1440f22ef01cSRoman Divacky   if (Entry) {
1441f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
1442f22ef01cSRoman Divacky 
1443f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
1444f22ef01cSRoman Divacky     // by the alias, as in:
1445f22ef01cSRoman Divacky     //   extern int test6();
1446f22ef01cSRoman Divacky     //   ...
1447f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
1448f22ef01cSRoman Divacky     //
1449f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
1450f22ef01cSRoman Divacky     GA->takeName(Entry);
1451f22ef01cSRoman Divacky 
1452f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1453f22ef01cSRoman Divacky                                                           Entry->getType()));
1454f22ef01cSRoman Divacky     Entry->eraseFromParent();
1455f22ef01cSRoman Divacky   } else {
1456ffd1746dSEd Schouten     GA->setName(MangledName);
1457f22ef01cSRoman Divacky   }
1458f22ef01cSRoman Divacky 
1459f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
1460f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
1461f22ef01cSRoman Divacky   // variable/function.
1462f22ef01cSRoman Divacky   if (D->hasAttr<DLLExportAttr>()) {
1463f22ef01cSRoman Divacky     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1464f22ef01cSRoman Divacky       // The dllexport attribute is ignored for undefined symbols.
1465ffd1746dSEd Schouten       if (FD->hasBody())
1466f22ef01cSRoman Divacky         GA->setLinkage(llvm::Function::DLLExportLinkage);
1467f22ef01cSRoman Divacky     } else {
1468f22ef01cSRoman Divacky       GA->setLinkage(llvm::Function::DLLExportLinkage);
1469f22ef01cSRoman Divacky     }
1470f22ef01cSRoman Divacky   } else if (D->hasAttr<WeakAttr>() ||
1471f22ef01cSRoman Divacky              D->hasAttr<WeakRefAttr>() ||
1472f22ef01cSRoman Divacky              D->hasAttr<WeakImportAttr>()) {
1473f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
1474f22ef01cSRoman Divacky   }
1475f22ef01cSRoman Divacky 
1476f22ef01cSRoman Divacky   SetCommonAttributes(D, GA);
1477f22ef01cSRoman Divacky }
1478f22ef01cSRoman Divacky 
1479f22ef01cSRoman Divacky /// getBuiltinLibFunction - Given a builtin id for a function like
1480f22ef01cSRoman Divacky /// "__builtin_fabsf", return a Function* for "fabsf".
1481f22ef01cSRoman Divacky llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1482f22ef01cSRoman Divacky                                                   unsigned BuiltinID) {
1483f22ef01cSRoman Divacky   assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1484f22ef01cSRoman Divacky           Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1485f22ef01cSRoman Divacky          "isn't a lib fn");
1486f22ef01cSRoman Divacky 
1487f22ef01cSRoman Divacky   // Get the name, skip over the __builtin_ prefix (if necessary).
1488f22ef01cSRoman Divacky   const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1489f22ef01cSRoman Divacky   if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1490f22ef01cSRoman Divacky     Name += 10;
1491f22ef01cSRoman Divacky 
1492f22ef01cSRoman Divacky   const llvm::FunctionType *Ty =
1493f22ef01cSRoman Divacky     cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1494f22ef01cSRoman Divacky 
1495f22ef01cSRoman Divacky   return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
1496f22ef01cSRoman Divacky }
1497f22ef01cSRoman Divacky 
1498f22ef01cSRoman Divacky llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1499f22ef01cSRoman Divacky                                             unsigned NumTys) {
1500f22ef01cSRoman Divacky   return llvm::Intrinsic::getDeclaration(&getModule(),
1501f22ef01cSRoman Divacky                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
1502f22ef01cSRoman Divacky }
1503f22ef01cSRoman Divacky 
1504f22ef01cSRoman Divacky 
1505f22ef01cSRoman Divacky llvm::Function *CodeGenModule::getMemCpyFn(const llvm::Type *DestType,
1506f22ef01cSRoman Divacky                                            const llvm::Type *SrcType,
1507f22ef01cSRoman Divacky                                            const llvm::Type *SizeType) {
1508f22ef01cSRoman Divacky   const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1509f22ef01cSRoman Divacky   return getIntrinsic(llvm::Intrinsic::memcpy, ArgTypes, 3);
1510f22ef01cSRoman Divacky }
1511f22ef01cSRoman Divacky 
1512f22ef01cSRoman Divacky llvm::Function *CodeGenModule::getMemMoveFn(const llvm::Type *DestType,
1513f22ef01cSRoman Divacky                                             const llvm::Type *SrcType,
1514f22ef01cSRoman Divacky                                             const llvm::Type *SizeType) {
1515f22ef01cSRoman Divacky   const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1516f22ef01cSRoman Divacky   return getIntrinsic(llvm::Intrinsic::memmove, ArgTypes, 3);
1517f22ef01cSRoman Divacky }
1518f22ef01cSRoman Divacky 
1519f22ef01cSRoman Divacky llvm::Function *CodeGenModule::getMemSetFn(const llvm::Type *DestType,
1520f22ef01cSRoman Divacky                                            const llvm::Type *SizeType) {
1521f22ef01cSRoman Divacky   const llvm::Type *ArgTypes[2] = { DestType, SizeType };
1522f22ef01cSRoman Divacky   return getIntrinsic(llvm::Intrinsic::memset, ArgTypes, 2);
1523f22ef01cSRoman Divacky }
1524f22ef01cSRoman Divacky 
1525f22ef01cSRoman Divacky static llvm::StringMapEntry<llvm::Constant*> &
1526f22ef01cSRoman Divacky GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1527f22ef01cSRoman Divacky                          const StringLiteral *Literal,
1528f22ef01cSRoman Divacky                          bool TargetIsLSB,
1529f22ef01cSRoman Divacky                          bool &IsUTF16,
1530f22ef01cSRoman Divacky                          unsigned &StringLength) {
1531f22ef01cSRoman Divacky   unsigned NumBytes = Literal->getByteLength();
1532f22ef01cSRoman Divacky 
1533f22ef01cSRoman Divacky   // Check for simple case.
1534f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
1535f22ef01cSRoman Divacky     StringLength = NumBytes;
1536f22ef01cSRoman Divacky     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1537f22ef01cSRoman Divacky                                                 StringLength));
1538f22ef01cSRoman Divacky   }
1539f22ef01cSRoman Divacky 
1540f22ef01cSRoman Divacky   // Otherwise, convert the UTF8 literals into a byte string.
1541f22ef01cSRoman Divacky   llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1542f22ef01cSRoman Divacky   const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1543f22ef01cSRoman Divacky   UTF16 *ToPtr = &ToBuf[0];
1544f22ef01cSRoman Divacky 
1545f22ef01cSRoman Divacky   ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1546f22ef01cSRoman Divacky                                                &ToPtr, ToPtr + NumBytes,
1547f22ef01cSRoman Divacky                                                strictConversion);
1548f22ef01cSRoman Divacky 
1549f22ef01cSRoman Divacky   // Check for conversion failure.
1550f22ef01cSRoman Divacky   if (Result != conversionOK) {
1551f22ef01cSRoman Divacky     // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove
1552f22ef01cSRoman Divacky     // this duplicate code.
1553f22ef01cSRoman Divacky     assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed");
1554f22ef01cSRoman Divacky     StringLength = NumBytes;
1555f22ef01cSRoman Divacky     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1556f22ef01cSRoman Divacky                                                 StringLength));
1557f22ef01cSRoman Divacky   }
1558f22ef01cSRoman Divacky 
1559f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
1560f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
1561f22ef01cSRoman Divacky 
1562f22ef01cSRoman Divacky   // Render the UTF-16 string into a byte array and convert to the target byte
1563f22ef01cSRoman Divacky   // order.
1564f22ef01cSRoman Divacky   //
1565f22ef01cSRoman Divacky   // FIXME: This isn't something we should need to do here.
1566f22ef01cSRoman Divacky   llvm::SmallString<128> AsBytes;
1567f22ef01cSRoman Divacky   AsBytes.reserve(StringLength * 2);
1568f22ef01cSRoman Divacky   for (unsigned i = 0; i != StringLength; ++i) {
1569f22ef01cSRoman Divacky     unsigned short Val = ToBuf[i];
1570f22ef01cSRoman Divacky     if (TargetIsLSB) {
1571f22ef01cSRoman Divacky       AsBytes.push_back(Val & 0xFF);
1572f22ef01cSRoman Divacky       AsBytes.push_back(Val >> 8);
1573f22ef01cSRoman Divacky     } else {
1574f22ef01cSRoman Divacky       AsBytes.push_back(Val >> 8);
1575f22ef01cSRoman Divacky       AsBytes.push_back(Val & 0xFF);
1576f22ef01cSRoman Divacky     }
1577f22ef01cSRoman Divacky   }
1578f22ef01cSRoman Divacky   // Append one extra null character, the second is automatically added by our
1579f22ef01cSRoman Divacky   // caller.
1580f22ef01cSRoman Divacky   AsBytes.push_back(0);
1581f22ef01cSRoman Divacky 
1582f22ef01cSRoman Divacky   IsUTF16 = true;
1583f22ef01cSRoman Divacky   return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1584f22ef01cSRoman Divacky }
1585f22ef01cSRoman Divacky 
1586f22ef01cSRoman Divacky llvm::Constant *
1587f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1588f22ef01cSRoman Divacky   unsigned StringLength = 0;
1589f22ef01cSRoman Divacky   bool isUTF16 = false;
1590f22ef01cSRoman Divacky   llvm::StringMapEntry<llvm::Constant*> &Entry =
1591f22ef01cSRoman Divacky     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1592f22ef01cSRoman Divacky                              getTargetData().isLittleEndian(),
1593f22ef01cSRoman Divacky                              isUTF16, StringLength);
1594f22ef01cSRoman Divacky 
1595f22ef01cSRoman Divacky   if (llvm::Constant *C = Entry.getValue())
1596f22ef01cSRoman Divacky     return C;
1597f22ef01cSRoman Divacky 
1598f22ef01cSRoman Divacky   llvm::Constant *Zero =
1599f22ef01cSRoman Divacky       llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1600f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
1601f22ef01cSRoman Divacky 
1602f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
1603f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
1604f22ef01cSRoman Divacky     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1605f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
1606f22ef01cSRoman Divacky     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1607f22ef01cSRoman Divacky                                            "__CFConstantStringClassReference");
1608f22ef01cSRoman Divacky     // Decay array -> ptr
1609f22ef01cSRoman Divacky     CFConstantStringClassRef =
1610f22ef01cSRoman Divacky       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1611f22ef01cSRoman Divacky   }
1612f22ef01cSRoman Divacky 
1613f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
1614f22ef01cSRoman Divacky 
1615f22ef01cSRoman Divacky   const llvm::StructType *STy =
1616f22ef01cSRoman Divacky     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1617f22ef01cSRoman Divacky 
1618f22ef01cSRoman Divacky   std::vector<llvm::Constant*> Fields(4);
1619f22ef01cSRoman Divacky 
1620f22ef01cSRoman Divacky   // Class pointer.
1621f22ef01cSRoman Divacky   Fields[0] = CFConstantStringClassRef;
1622f22ef01cSRoman Divacky 
1623f22ef01cSRoman Divacky   // Flags.
1624f22ef01cSRoman Divacky   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1625f22ef01cSRoman Divacky   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1626f22ef01cSRoman Divacky     llvm::ConstantInt::get(Ty, 0x07C8);
1627f22ef01cSRoman Divacky 
1628f22ef01cSRoman Divacky   // String pointer.
1629f22ef01cSRoman Divacky   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1630f22ef01cSRoman Divacky 
1631f22ef01cSRoman Divacky   llvm::GlobalValue::LinkageTypes Linkage;
1632f22ef01cSRoman Divacky   bool isConstant;
1633f22ef01cSRoman Divacky   if (isUTF16) {
1634f22ef01cSRoman Divacky     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1635f22ef01cSRoman Divacky     Linkage = llvm::GlobalValue::InternalLinkage;
1636f22ef01cSRoman Divacky     // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1637f22ef01cSRoman Divacky     // does make plain ascii ones writable.
1638f22ef01cSRoman Divacky     isConstant = true;
1639f22ef01cSRoman Divacky   } else {
1640f22ef01cSRoman Divacky     Linkage = llvm::GlobalValue::PrivateLinkage;
1641f22ef01cSRoman Divacky     isConstant = !Features.WritableStrings;
1642f22ef01cSRoman Divacky   }
1643f22ef01cSRoman Divacky 
1644f22ef01cSRoman Divacky   llvm::GlobalVariable *GV =
1645f22ef01cSRoman Divacky     new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1646f22ef01cSRoman Divacky                              ".str");
1647f22ef01cSRoman Divacky   if (isUTF16) {
1648f22ef01cSRoman Divacky     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1649f22ef01cSRoman Divacky     GV->setAlignment(Align.getQuantity());
1650f22ef01cSRoman Divacky   }
1651f22ef01cSRoman Divacky   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1652f22ef01cSRoman Divacky 
1653f22ef01cSRoman Divacky   // String length.
1654f22ef01cSRoman Divacky   Ty = getTypes().ConvertType(getContext().LongTy);
1655f22ef01cSRoman Divacky   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1656f22ef01cSRoman Divacky 
1657f22ef01cSRoman Divacky   // The struct.
1658f22ef01cSRoman Divacky   C = llvm::ConstantStruct::get(STy, Fields);
1659f22ef01cSRoman Divacky   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1660f22ef01cSRoman Divacky                                 llvm::GlobalVariable::PrivateLinkage, C,
1661f22ef01cSRoman Divacky                                 "_unnamed_cfstring_");
1662f22ef01cSRoman Divacky   if (const char *Sect = getContext().Target.getCFStringSection())
1663f22ef01cSRoman Divacky     GV->setSection(Sect);
1664f22ef01cSRoman Divacky   Entry.setValue(GV);
1665f22ef01cSRoman Divacky 
1666f22ef01cSRoman Divacky   return GV;
1667f22ef01cSRoman Divacky }
1668f22ef01cSRoman Divacky 
1669f22ef01cSRoman Divacky llvm::Constant *
1670f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantNSString(const StringLiteral *Literal) {
1671f22ef01cSRoman Divacky   unsigned StringLength = 0;
1672f22ef01cSRoman Divacky   bool isUTF16 = false;
1673f22ef01cSRoman Divacky   llvm::StringMapEntry<llvm::Constant*> &Entry =
1674f22ef01cSRoman Divacky     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1675f22ef01cSRoman Divacky                              getTargetData().isLittleEndian(),
1676f22ef01cSRoman Divacky                              isUTF16, StringLength);
1677f22ef01cSRoman Divacky 
1678f22ef01cSRoman Divacky   if (llvm::Constant *C = Entry.getValue())
1679f22ef01cSRoman Divacky     return C;
1680f22ef01cSRoman Divacky 
1681f22ef01cSRoman Divacky   llvm::Constant *Zero =
1682f22ef01cSRoman Divacky   llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1683f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
1684f22ef01cSRoman Divacky 
1685f22ef01cSRoman Divacky   // If we don't already have it, get _NSConstantStringClassReference.
1686f22ef01cSRoman Divacky   if (!NSConstantStringClassRef) {
1687f22ef01cSRoman Divacky     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1688f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
1689f22ef01cSRoman Divacky     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1690f22ef01cSRoman Divacky                                         Features.ObjCNonFragileABI ?
1691f22ef01cSRoman Divacky                                         "OBJC_CLASS_$_NSConstantString" :
1692f22ef01cSRoman Divacky                                         "_NSConstantStringClassReference");
1693f22ef01cSRoman Divacky     // Decay array -> ptr
1694f22ef01cSRoman Divacky     NSConstantStringClassRef =
1695f22ef01cSRoman Divacky       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1696f22ef01cSRoman Divacky   }
1697f22ef01cSRoman Divacky 
1698f22ef01cSRoman Divacky   QualType NSTy = getContext().getNSConstantStringType();
1699f22ef01cSRoman Divacky 
1700f22ef01cSRoman Divacky   const llvm::StructType *STy =
1701f22ef01cSRoman Divacky   cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1702f22ef01cSRoman Divacky 
1703f22ef01cSRoman Divacky   std::vector<llvm::Constant*> Fields(3);
1704f22ef01cSRoman Divacky 
1705f22ef01cSRoman Divacky   // Class pointer.
1706f22ef01cSRoman Divacky   Fields[0] = NSConstantStringClassRef;
1707f22ef01cSRoman Divacky 
1708f22ef01cSRoman Divacky   // String pointer.
1709f22ef01cSRoman Divacky   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1710f22ef01cSRoman Divacky 
1711f22ef01cSRoman Divacky   llvm::GlobalValue::LinkageTypes Linkage;
1712f22ef01cSRoman Divacky   bool isConstant;
1713f22ef01cSRoman Divacky   if (isUTF16) {
1714f22ef01cSRoman Divacky     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1715f22ef01cSRoman Divacky     Linkage = llvm::GlobalValue::InternalLinkage;
1716f22ef01cSRoman Divacky     // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1717f22ef01cSRoman Divacky     // does make plain ascii ones writable.
1718f22ef01cSRoman Divacky     isConstant = true;
1719f22ef01cSRoman Divacky   } else {
1720f22ef01cSRoman Divacky     Linkage = llvm::GlobalValue::PrivateLinkage;
1721f22ef01cSRoman Divacky     isConstant = !Features.WritableStrings;
1722f22ef01cSRoman Divacky   }
1723f22ef01cSRoman Divacky 
1724f22ef01cSRoman Divacky   llvm::GlobalVariable *GV =
1725f22ef01cSRoman Divacky   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1726f22ef01cSRoman Divacky                            ".str");
1727f22ef01cSRoman Divacky   if (isUTF16) {
1728f22ef01cSRoman Divacky     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1729f22ef01cSRoman Divacky     GV->setAlignment(Align.getQuantity());
1730f22ef01cSRoman Divacky   }
1731f22ef01cSRoman Divacky   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1732f22ef01cSRoman Divacky 
1733f22ef01cSRoman Divacky   // String length.
1734f22ef01cSRoman Divacky   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1735f22ef01cSRoman Divacky   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1736f22ef01cSRoman Divacky 
1737f22ef01cSRoman Divacky   // The struct.
1738f22ef01cSRoman Divacky   C = llvm::ConstantStruct::get(STy, Fields);
1739f22ef01cSRoman Divacky   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1740f22ef01cSRoman Divacky                                 llvm::GlobalVariable::PrivateLinkage, C,
1741f22ef01cSRoman Divacky                                 "_unnamed_nsstring_");
1742f22ef01cSRoman Divacky   // FIXME. Fix section.
1743f22ef01cSRoman Divacky   if (const char *Sect =
1744f22ef01cSRoman Divacky         Features.ObjCNonFragileABI
1745f22ef01cSRoman Divacky           ? getContext().Target.getNSStringNonFragileABISection()
1746f22ef01cSRoman Divacky           : getContext().Target.getNSStringSection())
1747f22ef01cSRoman Divacky     GV->setSection(Sect);
1748f22ef01cSRoman Divacky   Entry.setValue(GV);
1749f22ef01cSRoman Divacky 
1750f22ef01cSRoman Divacky   return GV;
1751f22ef01cSRoman Divacky }
1752f22ef01cSRoman Divacky 
1753f22ef01cSRoman Divacky /// GetStringForStringLiteral - Return the appropriate bytes for a
1754f22ef01cSRoman Divacky /// string literal, properly padded to match the literal type.
1755f22ef01cSRoman Divacky std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1756f22ef01cSRoman Divacky   const char *StrData = E->getStrData();
1757f22ef01cSRoman Divacky   unsigned Len = E->getByteLength();
1758f22ef01cSRoman Divacky 
1759f22ef01cSRoman Divacky   const ConstantArrayType *CAT =
1760f22ef01cSRoman Divacky     getContext().getAsConstantArrayType(E->getType());
1761f22ef01cSRoman Divacky   assert(CAT && "String isn't pointer or array!");
1762f22ef01cSRoman Divacky 
1763f22ef01cSRoman Divacky   // Resize the string to the right size.
1764f22ef01cSRoman Divacky   std::string Str(StrData, StrData+Len);
1765f22ef01cSRoman Divacky   uint64_t RealLen = CAT->getSize().getZExtValue();
1766f22ef01cSRoman Divacky 
1767f22ef01cSRoman Divacky   if (E->isWide())
1768f22ef01cSRoman Divacky     RealLen *= getContext().Target.getWCharWidth()/8;
1769f22ef01cSRoman Divacky 
1770f22ef01cSRoman Divacky   Str.resize(RealLen, '\0');
1771f22ef01cSRoman Divacky 
1772f22ef01cSRoman Divacky   return Str;
1773f22ef01cSRoman Divacky }
1774f22ef01cSRoman Divacky 
1775f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1776f22ef01cSRoman Divacky /// constant array for the given string literal.
1777f22ef01cSRoman Divacky llvm::Constant *
1778f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1779f22ef01cSRoman Divacky   // FIXME: This can be more efficient.
1780f22ef01cSRoman Divacky   // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1781f22ef01cSRoman Divacky   llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1782f22ef01cSRoman Divacky   if (S->isWide()) {
1783f22ef01cSRoman Divacky     llvm::Type *DestTy =
1784f22ef01cSRoman Divacky         llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1785f22ef01cSRoman Divacky     C = llvm::ConstantExpr::getBitCast(C, DestTy);
1786f22ef01cSRoman Divacky   }
1787f22ef01cSRoman Divacky   return C;
1788f22ef01cSRoman Divacky }
1789f22ef01cSRoman Divacky 
1790f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1791f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
1792f22ef01cSRoman Divacky llvm::Constant *
1793f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1794f22ef01cSRoman Divacky   std::string Str;
1795f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1796f22ef01cSRoman Divacky 
1797f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
1798f22ef01cSRoman Divacky }
1799f22ef01cSRoman Divacky 
1800f22ef01cSRoman Divacky 
1801f22ef01cSRoman Divacky /// GenerateWritableString -- Creates storage for a string literal.
1802f22ef01cSRoman Divacky static llvm::Constant *GenerateStringLiteral(const std::string &str,
1803f22ef01cSRoman Divacky                                              bool constant,
1804f22ef01cSRoman Divacky                                              CodeGenModule &CGM,
1805f22ef01cSRoman Divacky                                              const char *GlobalName) {
1806f22ef01cSRoman Divacky   // Create Constant for this string literal. Don't add a '\0'.
1807f22ef01cSRoman Divacky   llvm::Constant *C =
1808f22ef01cSRoman Divacky       llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1809f22ef01cSRoman Divacky 
1810f22ef01cSRoman Divacky   // Create a global variable for this string
1811f22ef01cSRoman Divacky   return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1812f22ef01cSRoman Divacky                                   llvm::GlobalValue::PrivateLinkage,
1813f22ef01cSRoman Divacky                                   C, GlobalName);
1814f22ef01cSRoman Divacky }
1815f22ef01cSRoman Divacky 
1816f22ef01cSRoman Divacky /// GetAddrOfConstantString - Returns a pointer to a character array
1817f22ef01cSRoman Divacky /// containing the literal. This contents are exactly that of the
1818f22ef01cSRoman Divacky /// given string, i.e. it will not be null terminated automatically;
1819f22ef01cSRoman Divacky /// see GetAddrOfConstantCString. Note that whether the result is
1820f22ef01cSRoman Divacky /// actually a pointer to an LLVM constant depends on
1821f22ef01cSRoman Divacky /// Feature.WriteableStrings.
1822f22ef01cSRoman Divacky ///
1823f22ef01cSRoman Divacky /// The result has pointer to array type.
1824f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1825f22ef01cSRoman Divacky                                                        const char *GlobalName) {
1826f22ef01cSRoman Divacky   bool IsConstant = !Features.WritableStrings;
1827f22ef01cSRoman Divacky 
1828f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
1829f22ef01cSRoman Divacky   if (!GlobalName)
1830f22ef01cSRoman Divacky     GlobalName = ".str";
1831f22ef01cSRoman Divacky 
1832f22ef01cSRoman Divacky   // Don't share any string literals if strings aren't constant.
1833f22ef01cSRoman Divacky   if (!IsConstant)
1834f22ef01cSRoman Divacky     return GenerateStringLiteral(str, false, *this, GlobalName);
1835f22ef01cSRoman Divacky 
1836f22ef01cSRoman Divacky   llvm::StringMapEntry<llvm::Constant *> &Entry =
1837f22ef01cSRoman Divacky     ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1838f22ef01cSRoman Divacky 
1839f22ef01cSRoman Divacky   if (Entry.getValue())
1840f22ef01cSRoman Divacky     return Entry.getValue();
1841f22ef01cSRoman Divacky 
1842f22ef01cSRoman Divacky   // Create a global variable for this.
1843f22ef01cSRoman Divacky   llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1844f22ef01cSRoman Divacky   Entry.setValue(C);
1845f22ef01cSRoman Divacky   return C;
1846f22ef01cSRoman Divacky }
1847f22ef01cSRoman Divacky 
1848f22ef01cSRoman Divacky /// GetAddrOfConstantCString - Returns a pointer to a character
1849f22ef01cSRoman Divacky /// array containing the literal and a terminating '\-'
1850f22ef01cSRoman Divacky /// character. The result has pointer to array type.
1851f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1852f22ef01cSRoman Divacky                                                         const char *GlobalName){
1853f22ef01cSRoman Divacky   return GetAddrOfConstantString(str + '\0', GlobalName);
1854f22ef01cSRoman Divacky }
1855f22ef01cSRoman Divacky 
1856f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
1857f22ef01cSRoman Divacky /// properties for an implementation.
1858f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
1859f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
1860f22ef01cSRoman Divacky   for (ObjCImplementationDecl::propimpl_iterator
1861f22ef01cSRoman Divacky          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1862f22ef01cSRoman Divacky     ObjCPropertyImplDecl *PID = *i;
1863f22ef01cSRoman Divacky 
1864f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
1865f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1866f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
1867f22ef01cSRoman Divacky 
1868f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
1869f22ef01cSRoman Divacky       // been overridden. Note that ::isSynthesized is not the method
1870f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
1871f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
1872f22ef01cSRoman Divacky       // this implementation.
1873f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
1874f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
1875f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
1876f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
1877f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
1878f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
1879f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
1880f22ef01cSRoman Divacky     }
1881f22ef01cSRoman Divacky   }
1882f22ef01cSRoman Divacky }
1883f22ef01cSRoman Divacky 
1884f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
1885f22ef01cSRoman Divacky /// for an implementation.
1886f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1887f22ef01cSRoman Divacky   if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1888f22ef01cSRoman Divacky     return;
1889f22ef01cSRoman Divacky   DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1890f22ef01cSRoman Divacky   assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1891f22ef01cSRoman Divacky   IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1892f22ef01cSRoman Divacky   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1893f22ef01cSRoman Divacky   ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1894f22ef01cSRoman Divacky                                                   D->getLocation(),
1895f22ef01cSRoman Divacky                                                   D->getLocation(), cxxSelector,
1896f22ef01cSRoman Divacky                                                   getContext().VoidTy, 0,
1897f22ef01cSRoman Divacky                                                   DC, true, false, true,
1898f22ef01cSRoman Divacky                                                   ObjCMethodDecl::Required);
1899f22ef01cSRoman Divacky   D->addInstanceMethod(DTORMethod);
1900f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1901f22ef01cSRoman Divacky 
1902f22ef01cSRoman Divacky   II = &getContext().Idents.get(".cxx_construct");
1903f22ef01cSRoman Divacky   cxxSelector = getContext().Selectors.getSelector(0, &II);
1904f22ef01cSRoman Divacky   // The constructor returns 'self'.
1905f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1906f22ef01cSRoman Divacky                                                 D->getLocation(),
1907f22ef01cSRoman Divacky                                                 D->getLocation(), cxxSelector,
1908f22ef01cSRoman Divacky                                                 getContext().getObjCIdType(), 0,
1909f22ef01cSRoman Divacky                                                 DC, true, false, true,
1910f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
1911f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
1912f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1913f22ef01cSRoman Divacky 
1914f22ef01cSRoman Divacky 
1915f22ef01cSRoman Divacky }
1916f22ef01cSRoman Divacky 
1917f22ef01cSRoman Divacky /// EmitNamespace - Emit all declarations in a namespace.
1918f22ef01cSRoman Divacky void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1919f22ef01cSRoman Divacky   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1920f22ef01cSRoman Divacky        I != E; ++I)
1921f22ef01cSRoman Divacky     EmitTopLevelDecl(*I);
1922f22ef01cSRoman Divacky }
1923f22ef01cSRoman Divacky 
1924f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
1925f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1926f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1927f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
1928f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
1929f22ef01cSRoman Divacky     return;
1930f22ef01cSRoman Divacky   }
1931f22ef01cSRoman Divacky 
1932f22ef01cSRoman Divacky   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1933f22ef01cSRoman Divacky        I != E; ++I)
1934f22ef01cSRoman Divacky     EmitTopLevelDecl(*I);
1935f22ef01cSRoman Divacky }
1936f22ef01cSRoman Divacky 
1937f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
1938f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1939f22ef01cSRoman Divacky   // If an error has occurred, stop code generation, but continue
1940f22ef01cSRoman Divacky   // parsing and semantic analysis (to ensure all warnings and errors
1941f22ef01cSRoman Divacky   // are emitted).
1942f22ef01cSRoman Divacky   if (Diags.hasErrorOccurred())
1943f22ef01cSRoman Divacky     return;
1944f22ef01cSRoman Divacky 
1945f22ef01cSRoman Divacky   // Ignore dependent declarations.
1946f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1947f22ef01cSRoman Divacky     return;
1948f22ef01cSRoman Divacky 
1949f22ef01cSRoman Divacky   switch (D->getKind()) {
1950f22ef01cSRoman Divacky   case Decl::CXXConversion:
1951f22ef01cSRoman Divacky   case Decl::CXXMethod:
1952f22ef01cSRoman Divacky   case Decl::Function:
1953f22ef01cSRoman Divacky     // Skip function templates
1954f22ef01cSRoman Divacky     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1955f22ef01cSRoman Divacky       return;
1956f22ef01cSRoman Divacky 
1957f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
1958f22ef01cSRoman Divacky     break;
1959f22ef01cSRoman Divacky 
1960f22ef01cSRoman Divacky   case Decl::Var:
1961f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
1962f22ef01cSRoman Divacky     break;
1963f22ef01cSRoman Divacky 
1964f22ef01cSRoman Divacky   // C++ Decls
1965f22ef01cSRoman Divacky   case Decl::Namespace:
1966f22ef01cSRoman Divacky     EmitNamespace(cast<NamespaceDecl>(D));
1967f22ef01cSRoman Divacky     break;
1968f22ef01cSRoman Divacky     // No code generation needed.
1969f22ef01cSRoman Divacky   case Decl::UsingShadow:
1970f22ef01cSRoman Divacky   case Decl::Using:
1971f22ef01cSRoman Divacky   case Decl::UsingDirective:
1972f22ef01cSRoman Divacky   case Decl::ClassTemplate:
1973f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
1974f22ef01cSRoman Divacky   case Decl::NamespaceAlias:
1975f22ef01cSRoman Divacky     break;
1976f22ef01cSRoman Divacky   case Decl::CXXConstructor:
1977f22ef01cSRoman Divacky     // Skip function templates
1978f22ef01cSRoman Divacky     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1979f22ef01cSRoman Divacky       return;
1980f22ef01cSRoman Divacky 
1981f22ef01cSRoman Divacky     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1982f22ef01cSRoman Divacky     break;
1983f22ef01cSRoman Divacky   case Decl::CXXDestructor:
1984f22ef01cSRoman Divacky     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1985f22ef01cSRoman Divacky     break;
1986f22ef01cSRoman Divacky 
1987f22ef01cSRoman Divacky   case Decl::StaticAssert:
1988f22ef01cSRoman Divacky     // Nothing to do.
1989f22ef01cSRoman Divacky     break;
1990f22ef01cSRoman Divacky 
1991f22ef01cSRoman Divacky   // Objective-C Decls
1992f22ef01cSRoman Divacky 
1993f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
1994f22ef01cSRoman Divacky   case Decl::ObjCClass:
1995f22ef01cSRoman Divacky   case Decl::ObjCForwardProtocol:
1996f22ef01cSRoman Divacky   case Decl::ObjCCategory:
1997f22ef01cSRoman Divacky   case Decl::ObjCInterface:
1998f22ef01cSRoman Divacky     break;
1999f22ef01cSRoman Divacky 
2000f22ef01cSRoman Divacky   case Decl::ObjCProtocol:
2001f22ef01cSRoman Divacky     Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
2002f22ef01cSRoman Divacky     break;
2003f22ef01cSRoman Divacky 
2004f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
2005f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
2006f22ef01cSRoman Divacky     // can ignore them here.
2007f22ef01cSRoman Divacky     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2008f22ef01cSRoman Divacky     break;
2009f22ef01cSRoman Divacky 
2010f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
2011f22ef01cSRoman Divacky     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2012f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
2013f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
2014f22ef01cSRoman Divacky     Runtime->GenerateClass(OMD);
2015f22ef01cSRoman Divacky     break;
2016f22ef01cSRoman Divacky   }
2017f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
2018f22ef01cSRoman Divacky     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2019f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
2020f22ef01cSRoman Divacky     if (OMD->getBody())
2021f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
2022f22ef01cSRoman Divacky     break;
2023f22ef01cSRoman Divacky   }
2024f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
2025f22ef01cSRoman Divacky     // compatibility-alias is a directive and has no code gen.
2026f22ef01cSRoman Divacky     break;
2027f22ef01cSRoman Divacky 
2028f22ef01cSRoman Divacky   case Decl::LinkageSpec:
2029f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2030f22ef01cSRoman Divacky     break;
2031f22ef01cSRoman Divacky 
2032f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
2033f22ef01cSRoman Divacky     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2034f22ef01cSRoman Divacky     llvm::StringRef AsmString = AD->getAsmString()->getString();
2035f22ef01cSRoman Divacky 
2036f22ef01cSRoman Divacky     const std::string &S = getModule().getModuleInlineAsm();
2037f22ef01cSRoman Divacky     if (S.empty())
2038f22ef01cSRoman Divacky       getModule().setModuleInlineAsm(AsmString);
2039f22ef01cSRoman Divacky     else
2040f22ef01cSRoman Divacky       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2041f22ef01cSRoman Divacky     break;
2042f22ef01cSRoman Divacky   }
2043f22ef01cSRoman Divacky 
2044f22ef01cSRoman Divacky   default:
2045f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
2046f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2047f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
2048f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2049f22ef01cSRoman Divacky   }
2050f22ef01cSRoman Divacky }
2051ffd1746dSEd Schouten 
2052ffd1746dSEd Schouten /// Turns the given pointer into a constant.
2053ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2054ffd1746dSEd Schouten                                           const void *Ptr) {
2055ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2056ffd1746dSEd Schouten   const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2057ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
2058ffd1746dSEd Schouten }
2059ffd1746dSEd Schouten 
2060ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2061ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
2062ffd1746dSEd Schouten                                    GlobalDecl D,
2063ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
2064ffd1746dSEd Schouten   if (!GlobalMetadata)
2065ffd1746dSEd Schouten     GlobalMetadata =
2066ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2067ffd1746dSEd Schouten 
2068ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
2069ffd1746dSEd Schouten   llvm::Value *Ops[] = {
2070ffd1746dSEd Schouten     Addr,
2071ffd1746dSEd Schouten     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2072ffd1746dSEd Schouten   };
2073ffd1746dSEd Schouten   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2074ffd1746dSEd Schouten }
2075ffd1746dSEd Schouten 
2076ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
2077ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
2078ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
2079ffd1746dSEd Schouten ///
2080ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
2081ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
2082ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
2083ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
2084ffd1746dSEd Schouten   llvm::NamedMDNode *GlobalMetadata = 0;
2085ffd1746dSEd Schouten 
2086ffd1746dSEd Schouten   // StaticLocalDeclMap
2087ffd1746dSEd Schouten   for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2088ffd1746dSEd Schouten          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2089ffd1746dSEd Schouten        I != E; ++I) {
2090ffd1746dSEd Schouten     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2091ffd1746dSEd Schouten     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2092ffd1746dSEd Schouten   }
2093ffd1746dSEd Schouten }
2094ffd1746dSEd Schouten 
2095ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
2096ffd1746dSEd Schouten /// function.
2097ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
2098ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
2099ffd1746dSEd Schouten 
2100ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
2101ffd1746dSEd Schouten 
2102ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
2103ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2104ffd1746dSEd Schouten 
2105ffd1746dSEd Schouten   llvm::NamedMDNode *GlobalMetadata = 0;
2106ffd1746dSEd Schouten 
2107ffd1746dSEd Schouten   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2108ffd1746dSEd Schouten          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2109ffd1746dSEd Schouten     const Decl *D = I->first;
2110ffd1746dSEd Schouten     llvm::Value *Addr = I->second;
2111ffd1746dSEd Schouten 
2112ffd1746dSEd Schouten     if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2113ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2114ffd1746dSEd Schouten       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2115ffd1746dSEd Schouten     } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2116ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2117ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2118ffd1746dSEd Schouten     }
2119ffd1746dSEd Schouten   }
2120ffd1746dSEd Schouten }
2121