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"
172754fe60SDimitry Andric #include "CodeGenTBAA.h"
18f22ef01cSRoman Divacky #include "CGCall.h"
196122f3e6SDimitry Andric #include "CGCUDARuntime.h"
20e580952dSDimitry Andric #include "CGCXXABI.h"
21f22ef01cSRoman Divacky #include "CGObjCRuntime.h"
226122f3e6SDimitry Andric #include "CGOpenCLRuntime.h"
23f22ef01cSRoman Divacky #include "TargetInfo.h"
24ffd1746dSEd Schouten #include "clang/Frontend/CodeGenOptions.h"
25f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
26f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h"
27f22ef01cSRoman Divacky #include "clang/AST/DeclObjC.h"
28f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
29ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h"
302754fe60SDimitry Andric #include "clang/AST/Mangle.h"
31f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h"
32f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h"
33f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h"
34f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h"
35f22ef01cSRoman Divacky #include "clang/Basic/ConvertUTF.h"
36f22ef01cSRoman Divacky #include "llvm/CallingConv.h"
37f22ef01cSRoman Divacky #include "llvm/Module.h"
38f22ef01cSRoman Divacky #include "llvm/Intrinsics.h"
39f22ef01cSRoman Divacky #include "llvm/LLVMContext.h"
40f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h"
412754fe60SDimitry Andric #include "llvm/Target/Mangler.h"
42f22ef01cSRoman Divacky #include "llvm/Target/TargetData.h"
43f22ef01cSRoman Divacky #include "llvm/Support/CallSite.h"
44f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
45f22ef01cSRoman Divacky using namespace clang;
46f22ef01cSRoman Divacky using namespace CodeGen;
47f22ef01cSRoman Divacky 
486122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
496122f3e6SDimitry Andric 
50e580952dSDimitry Andric static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
516122f3e6SDimitry Andric   switch (CGM.getContext().getTargetInfo().getCXXABI()) {
52e580952dSDimitry Andric   case CXXABI_ARM: return *CreateARMCXXABI(CGM);
53e580952dSDimitry Andric   case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
54e580952dSDimitry Andric   case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
55e580952dSDimitry Andric   }
56e580952dSDimitry Andric 
57e580952dSDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
58e580952dSDimitry Andric   return *CreateItaniumCXXABI(CGM);
59e580952dSDimitry Andric }
60e580952dSDimitry Andric 
61f22ef01cSRoman Divacky 
62f22ef01cSRoman Divacky CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
63f22ef01cSRoman Divacky                              llvm::Module &M, const llvm::TargetData &TD,
646122f3e6SDimitry Andric                              DiagnosticsEngine &diags)
652754fe60SDimitry Andric   : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
66f22ef01cSRoman Divacky     TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
67e580952dSDimitry Andric     ABI(createCXXABI(*this)),
6817a519f9SDimitry Andric     Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI, CGO),
692754fe60SDimitry Andric     TBAA(0),
706122f3e6SDimitry Andric     VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
716122f3e6SDimitry Andric     DebugInfo(0), ARCData(0), RRData(0), CFConstantStringClassRef(0),
726122f3e6SDimitry Andric     ConstantStringClassRef(0), NSConstantStringType(0),
73e580952dSDimitry Andric     VMContext(M.getContext()),
74e580952dSDimitry Andric     NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
752754fe60SDimitry Andric     BlockObjectAssign(0), BlockObjectDispose(0),
762754fe60SDimitry Andric     BlockDescriptorType(0), GenericBlockLiteralType(0) {
773b0f4066SDimitry Andric   if (Features.ObjC1)
783b0f4066SDimitry Andric     createObjCRuntime();
796122f3e6SDimitry Andric   if (Features.OpenCL)
806122f3e6SDimitry Andric     createOpenCLRuntime();
816122f3e6SDimitry Andric   if (Features.CUDA)
826122f3e6SDimitry Andric     createCUDARuntime();
83f22ef01cSRoman Divacky 
842754fe60SDimitry Andric   // Enable TBAA unless it's suppressed.
852754fe60SDimitry Andric   if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
862754fe60SDimitry Andric     TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
872754fe60SDimitry Andric                            ABI.getMangleContext());
882754fe60SDimitry Andric 
893b0f4066SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
903b0f4066SDimitry Andric   // object.
913b0f4066SDimitry Andric   if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
923b0f4066SDimitry Andric       CodeGenOpts.EmitGcovNotes)
933b0f4066SDimitry Andric     DebugInfo = new CGDebugInfo(*this);
942754fe60SDimitry Andric 
952754fe60SDimitry Andric   Block.GlobalUniqueCount = 0;
962754fe60SDimitry Andric 
9717a519f9SDimitry Andric   if (C.getLangOptions().ObjCAutoRefCount)
9817a519f9SDimitry Andric     ARCData = new ARCEntrypoints();
9917a519f9SDimitry Andric   RRData = new RREntrypoints();
10017a519f9SDimitry Andric 
1012754fe60SDimitry Andric   // Initialize the type cache.
1022754fe60SDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
103bd5abe19SDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
1042754fe60SDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
1052754fe60SDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
1062754fe60SDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
1076122f3e6SDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
108dd6029ffSDimitry Andric   PointerAlignInBytes =
1096122f3e6SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
1106122f3e6SDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
1112754fe60SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
1122754fe60SDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
1132754fe60SDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
114f22ef01cSRoman Divacky }
115f22ef01cSRoman Divacky 
116f22ef01cSRoman Divacky CodeGenModule::~CodeGenModule() {
1176122f3e6SDimitry Andric   delete ObjCRuntime;
1186122f3e6SDimitry Andric   delete OpenCLRuntime;
1196122f3e6SDimitry Andric   delete CUDARuntime;
1206122f3e6SDimitry Andric   delete TheTargetCodeGenInfo;
121e580952dSDimitry Andric   delete &ABI;
1222754fe60SDimitry Andric   delete TBAA;
123f22ef01cSRoman Divacky   delete DebugInfo;
12417a519f9SDimitry Andric   delete ARCData;
12517a519f9SDimitry Andric   delete RRData;
126f22ef01cSRoman Divacky }
127f22ef01cSRoman Divacky 
128f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() {
129f22ef01cSRoman Divacky   if (!Features.NeXTRuntime)
1306122f3e6SDimitry Andric     ObjCRuntime = CreateGNUObjCRuntime(*this);
131f22ef01cSRoman Divacky   else
1326122f3e6SDimitry Andric     ObjCRuntime = CreateMacObjCRuntime(*this);
1336122f3e6SDimitry Andric }
1346122f3e6SDimitry Andric 
1356122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
1366122f3e6SDimitry Andric   OpenCLRuntime = new CGOpenCLRuntime(*this);
1376122f3e6SDimitry Andric }
1386122f3e6SDimitry Andric 
1396122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() {
1406122f3e6SDimitry Andric   CUDARuntime = CreateNVCUDARuntime(*this);
141f22ef01cSRoman Divacky }
142f22ef01cSRoman Divacky 
143f22ef01cSRoman Divacky void CodeGenModule::Release() {
144f22ef01cSRoman Divacky   EmitDeferred();
145f22ef01cSRoman Divacky   EmitCXXGlobalInitFunc();
146f22ef01cSRoman Divacky   EmitCXXGlobalDtorFunc();
1476122f3e6SDimitry Andric   if (ObjCRuntime)
1486122f3e6SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
149f22ef01cSRoman Divacky       AddGlobalCtor(ObjCInitFunction);
150f22ef01cSRoman Divacky   EmitCtorList(GlobalCtors, "llvm.global_ctors");
151f22ef01cSRoman Divacky   EmitCtorList(GlobalDtors, "llvm.global_dtors");
1526122f3e6SDimitry Andric   EmitGlobalAnnotations();
153f22ef01cSRoman Divacky   EmitLLVMUsed();
154ffd1746dSEd Schouten 
1552754fe60SDimitry Andric   SimplifyPersonality();
1562754fe60SDimitry Andric 
157ffd1746dSEd Schouten   if (getCodeGenOpts().EmitDeclMetadata)
158ffd1746dSEd Schouten     EmitDeclMetadata();
159bd5abe19SDimitry Andric 
160bd5abe19SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
161bd5abe19SDimitry Andric     EmitCoverageFile();
1626122f3e6SDimitry Andric 
1636122f3e6SDimitry Andric   if (DebugInfo)
1646122f3e6SDimitry Andric     DebugInfo->finalize();
165f22ef01cSRoman Divacky }
166f22ef01cSRoman Divacky 
1673b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
1683b0f4066SDimitry Andric   // Make sure that this type is translated.
1693b0f4066SDimitry Andric   Types.UpdateCompletedType(TD);
1703b0f4066SDimitry Andric   if (DebugInfo)
1713b0f4066SDimitry Andric     DebugInfo->UpdateCompletedType(TD);
1723b0f4066SDimitry Andric }
1733b0f4066SDimitry Andric 
1742754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
1752754fe60SDimitry Andric   if (!TBAA)
1762754fe60SDimitry Andric     return 0;
1772754fe60SDimitry Andric   return TBAA->getTBAAInfo(QTy);
1782754fe60SDimitry Andric }
1792754fe60SDimitry Andric 
1802754fe60SDimitry Andric void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
1812754fe60SDimitry Andric                                         llvm::MDNode *TBAAInfo) {
1822754fe60SDimitry Andric   Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
1832754fe60SDimitry Andric }
1842754fe60SDimitry Andric 
185f22ef01cSRoman Divacky bool CodeGenModule::isTargetDarwin() const {
1866122f3e6SDimitry Andric   return getContext().getTargetInfo().getTriple().isOSDarwin();
1873b0f4066SDimitry Andric }
1883b0f4066SDimitry Andric 
1896122f3e6SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef error) {
1906122f3e6SDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
1913b0f4066SDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID);
192f22ef01cSRoman Divacky }
193f22ef01cSRoman Divacky 
194f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
195f22ef01cSRoman Divacky /// specified stmt yet.
196f22ef01cSRoman Divacky void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
197f22ef01cSRoman Divacky                                      bool OmitOnError) {
198f22ef01cSRoman Divacky   if (OmitOnError && getDiags().hasErrorOccurred())
199f22ef01cSRoman Divacky     return;
2006122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
201f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
202f22ef01cSRoman Divacky   std::string Msg = Type;
203f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
204f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
205f22ef01cSRoman Divacky }
206f22ef01cSRoman Divacky 
207f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
208f22ef01cSRoman Divacky /// specified decl yet.
209f22ef01cSRoman Divacky void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
210f22ef01cSRoman Divacky                                      bool OmitOnError) {
211f22ef01cSRoman Divacky   if (OmitOnError && getDiags().hasErrorOccurred())
212f22ef01cSRoman Divacky     return;
2136122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
214f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
215f22ef01cSRoman Divacky   std::string Msg = Type;
216f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
217f22ef01cSRoman Divacky }
218f22ef01cSRoman Divacky 
21917a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
22017a519f9SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
22117a519f9SDimitry Andric }
22217a519f9SDimitry Andric 
223f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
2242754fe60SDimitry Andric                                         const NamedDecl *D) const {
225f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
226f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
227f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
228f22ef01cSRoman Divacky     return;
229f22ef01cSRoman Divacky   }
230f22ef01cSRoman Divacky 
2312754fe60SDimitry Andric   // Set visibility for definitions.
2322754fe60SDimitry Andric   NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
2332754fe60SDimitry Andric   if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
2342754fe60SDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.visibility()));
235f22ef01cSRoman Divacky }
236f22ef01cSRoman Divacky 
237e580952dSDimitry Andric /// Set the symbol visibility of type information (vtable and RTTI)
238e580952dSDimitry Andric /// associated with the given type.
239e580952dSDimitry Andric void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
240e580952dSDimitry Andric                                       const CXXRecordDecl *RD,
2412754fe60SDimitry Andric                                       TypeVisibilityKind TVK) const {
242e580952dSDimitry Andric   setGlobalVisibility(GV, RD);
243e580952dSDimitry Andric 
244e580952dSDimitry Andric   if (!CodeGenOpts.HiddenWeakVTables)
245e580952dSDimitry Andric     return;
246e580952dSDimitry Andric 
2472754fe60SDimitry Andric   // We never want to drop the visibility for RTTI names.
2482754fe60SDimitry Andric   if (TVK == TVK_ForRTTIName)
2492754fe60SDimitry Andric     return;
2502754fe60SDimitry Andric 
251e580952dSDimitry Andric   // We want to drop the visibility to hidden for weak type symbols.
252e580952dSDimitry Andric   // This isn't possible if there might be unresolved references
253e580952dSDimitry Andric   // elsewhere that rely on this symbol being visible.
254e580952dSDimitry Andric 
255e580952dSDimitry Andric   // This should be kept roughly in sync with setThunkVisibility
256e580952dSDimitry Andric   // in CGVTables.cpp.
257e580952dSDimitry Andric 
258e580952dSDimitry Andric   // Preconditions.
2592754fe60SDimitry Andric   if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
260e580952dSDimitry Andric       GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
261e580952dSDimitry Andric     return;
262e580952dSDimitry Andric 
263e580952dSDimitry Andric   // Don't override an explicit visibility attribute.
2643b0f4066SDimitry Andric   if (RD->getExplicitVisibility())
265e580952dSDimitry Andric     return;
266e580952dSDimitry Andric 
267e580952dSDimitry Andric   switch (RD->getTemplateSpecializationKind()) {
268e580952dSDimitry Andric   // We have to disable the optimization if this is an EI definition
269e580952dSDimitry Andric   // because there might be EI declarations in other shared objects.
270e580952dSDimitry Andric   case TSK_ExplicitInstantiationDefinition:
271e580952dSDimitry Andric   case TSK_ExplicitInstantiationDeclaration:
272e580952dSDimitry Andric     return;
273e580952dSDimitry Andric 
274e580952dSDimitry Andric   // Every use of a non-template class's type information has to emit it.
275e580952dSDimitry Andric   case TSK_Undeclared:
276e580952dSDimitry Andric     break;
277e580952dSDimitry Andric 
278e580952dSDimitry Andric   // In theory, implicit instantiations can ignore the possibility of
279e580952dSDimitry Andric   // an explicit instantiation declaration because there necessarily
280e580952dSDimitry Andric   // must be an EI definition somewhere with default visibility.  In
281e580952dSDimitry Andric   // practice, it's possible to have an explicit instantiation for
282e580952dSDimitry Andric   // an arbitrary template class, and linkers aren't necessarily able
283e580952dSDimitry Andric   // to deal with mixed-visibility symbols.
284e580952dSDimitry Andric   case TSK_ExplicitSpecialization:
285e580952dSDimitry Andric   case TSK_ImplicitInstantiation:
286e580952dSDimitry Andric     if (!CodeGenOpts.HiddenWeakTemplateVTables)
287e580952dSDimitry Andric       return;
288e580952dSDimitry Andric     break;
289e580952dSDimitry Andric   }
290e580952dSDimitry Andric 
291e580952dSDimitry Andric   // If there's a key function, there may be translation units
292e580952dSDimitry Andric   // that don't have the key function's definition.  But ignore
293e580952dSDimitry Andric   // this if we're emitting RTTI under -fno-rtti.
2942754fe60SDimitry Andric   if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
295e580952dSDimitry Andric     if (Context.getKeyFunction(RD))
296e580952dSDimitry Andric       return;
2972754fe60SDimitry Andric   }
298e580952dSDimitry Andric 
299e580952dSDimitry Andric   // Otherwise, drop the visibility to hidden.
300e580952dSDimitry Andric   GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3012754fe60SDimitry Andric   GV->setUnnamedAddr(true);
302e580952dSDimitry Andric }
303e580952dSDimitry Andric 
3046122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
305f22ef01cSRoman Divacky   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
306f22ef01cSRoman Divacky 
3076122f3e6SDimitry Andric   StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
308ffd1746dSEd Schouten   if (!Str.empty())
309ffd1746dSEd Schouten     return Str;
310f22ef01cSRoman Divacky 
311e580952dSDimitry Andric   if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
312ffd1746dSEd Schouten     IdentifierInfo *II = ND->getIdentifier();
313ffd1746dSEd Schouten     assert(II && "Attempt to mangle unnamed decl.");
314ffd1746dSEd Schouten 
315ffd1746dSEd Schouten     Str = II->getName();
316ffd1746dSEd Schouten     return Str;
317f22ef01cSRoman Divacky   }
318f22ef01cSRoman Divacky 
319ffd1746dSEd Schouten   llvm::SmallString<256> Buffer;
3202754fe60SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
321ffd1746dSEd Schouten   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
3222754fe60SDimitry Andric     getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
323ffd1746dSEd Schouten   else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
3242754fe60SDimitry Andric     getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
325ffd1746dSEd Schouten   else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
3262754fe60SDimitry Andric     getCXXABI().getMangleContext().mangleBlock(BD, Out);
327ffd1746dSEd Schouten   else
3282754fe60SDimitry Andric     getCXXABI().getMangleContext().mangleName(ND, Out);
329ffd1746dSEd Schouten 
330ffd1746dSEd Schouten   // Allocate space for the mangled name.
3312754fe60SDimitry Andric   Out.flush();
332ffd1746dSEd Schouten   size_t Length = Buffer.size();
333ffd1746dSEd Schouten   char *Name = MangledNamesAllocator.Allocate<char>(Length);
334ffd1746dSEd Schouten   std::copy(Buffer.begin(), Buffer.end(), Name);
335ffd1746dSEd Schouten 
3366122f3e6SDimitry Andric   Str = StringRef(Name, Length);
337ffd1746dSEd Schouten 
338ffd1746dSEd Schouten   return Str;
339ffd1746dSEd Schouten }
340ffd1746dSEd Schouten 
3412754fe60SDimitry Andric void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
342ffd1746dSEd Schouten                                         const BlockDecl *BD) {
3432754fe60SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
3442754fe60SDimitry Andric   const Decl *D = GD.getDecl();
3452754fe60SDimitry Andric   llvm::raw_svector_ostream Out(Buffer.getBuffer());
3462754fe60SDimitry Andric   if (D == 0)
3472754fe60SDimitry Andric     MangleCtx.mangleGlobalBlock(BD, Out);
3482754fe60SDimitry Andric   else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
3492754fe60SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
3502754fe60SDimitry Andric   else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
3512754fe60SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
3522754fe60SDimitry Andric   else
3532754fe60SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
354f22ef01cSRoman Divacky }
355f22ef01cSRoman Divacky 
3566122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
357f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
358f22ef01cSRoman Divacky }
359f22ef01cSRoman Divacky 
360f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
361f22ef01cSRoman Divacky /// main() runs.
362f22ef01cSRoman Divacky void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
363f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
364f22ef01cSRoman Divacky   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
365f22ef01cSRoman Divacky }
366f22ef01cSRoman Divacky 
367f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
368f22ef01cSRoman Divacky /// when the module is unloaded.
369f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
370f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
371f22ef01cSRoman Divacky   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
372f22ef01cSRoman Divacky }
373f22ef01cSRoman Divacky 
374f22ef01cSRoman Divacky void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
375f22ef01cSRoman Divacky   // Ctor function type is void()*.
376bd5abe19SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
377f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
378f22ef01cSRoman Divacky 
379f22ef01cSRoman Divacky   // Get the type of a ctor entry, { i32, void ()* }.
380f22ef01cSRoman Divacky   llvm::StructType *CtorStructTy =
38117a519f9SDimitry Andric     llvm::StructType::get(llvm::Type::getInt32Ty(VMContext),
382f22ef01cSRoman Divacky                           llvm::PointerType::getUnqual(CtorFTy), NULL);
383f22ef01cSRoman Divacky 
384f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
385f22ef01cSRoman Divacky   std::vector<llvm::Constant*> Ctors;
386f22ef01cSRoman Divacky   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
387f22ef01cSRoman Divacky     std::vector<llvm::Constant*> S;
388f22ef01cSRoman Divacky     S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
389f22ef01cSRoman Divacky                 I->second, false));
390f22ef01cSRoman Divacky     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
391f22ef01cSRoman Divacky     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
392f22ef01cSRoman Divacky   }
393f22ef01cSRoman Divacky 
394f22ef01cSRoman Divacky   if (!Ctors.empty()) {
395f22ef01cSRoman Divacky     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
396f22ef01cSRoman Divacky     new llvm::GlobalVariable(TheModule, AT, false,
397f22ef01cSRoman Divacky                              llvm::GlobalValue::AppendingLinkage,
398f22ef01cSRoman Divacky                              llvm::ConstantArray::get(AT, Ctors),
399f22ef01cSRoman Divacky                              GlobalName);
400f22ef01cSRoman Divacky   }
401f22ef01cSRoman Divacky }
402f22ef01cSRoman Divacky 
403f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
404f22ef01cSRoman Divacky CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
405e580952dSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
406f22ef01cSRoman Divacky 
407ffd1746dSEd Schouten   if (Linkage == GVA_Internal)
408f22ef01cSRoman Divacky     return llvm::Function::InternalLinkage;
409ffd1746dSEd Schouten 
410ffd1746dSEd Schouten   if (D->hasAttr<DLLExportAttr>())
411f22ef01cSRoman Divacky     return llvm::Function::DLLExportLinkage;
412ffd1746dSEd Schouten 
413ffd1746dSEd Schouten   if (D->hasAttr<WeakAttr>())
414f22ef01cSRoman Divacky     return llvm::Function::WeakAnyLinkage;
415ffd1746dSEd Schouten 
416f22ef01cSRoman Divacky   // In C99 mode, 'inline' functions are guaranteed to have a strong
417f22ef01cSRoman Divacky   // definition somewhere else, so we can use available_externally linkage.
418ffd1746dSEd Schouten   if (Linkage == GVA_C99Inline)
419f22ef01cSRoman Divacky     return llvm::Function::AvailableExternallyLinkage;
420ffd1746dSEd Schouten 
4216122f3e6SDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
4226122f3e6SDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
4236122f3e6SDimitry Andric   // Normally, this means we just map to internal, but for explicit
4246122f3e6SDimitry Andric   // instantiations we'll map to external.
4256122f3e6SDimitry Andric 
426f22ef01cSRoman Divacky   // In C++, the compiler has to emit a definition in every translation unit
427f22ef01cSRoman Divacky   // that references the function.  We should use linkonce_odr because
428f22ef01cSRoman Divacky   // a) if all references in this translation unit are optimized away, we
429f22ef01cSRoman Divacky   // don't need to codegen it.  b) if the function persists, it needs to be
430f22ef01cSRoman Divacky   // merged with other definitions. c) C++ has the ODR, so we know the
431f22ef01cSRoman Divacky   // definition is dependable.
432ffd1746dSEd Schouten   if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
4332754fe60SDimitry Andric     return !Context.getLangOptions().AppleKext
4342754fe60SDimitry Andric              ? llvm::Function::LinkOnceODRLinkage
4352754fe60SDimitry Andric              : llvm::Function::InternalLinkage;
436ffd1746dSEd Schouten 
437f22ef01cSRoman Divacky   // An explicit instantiation of a template has weak linkage, since
438f22ef01cSRoman Divacky   // explicit instantiations can occur in multiple translation units
439f22ef01cSRoman Divacky   // and must all be equivalent. However, we are not allowed to
440f22ef01cSRoman Divacky   // throw away these explicit instantiations.
441ffd1746dSEd Schouten   if (Linkage == GVA_ExplicitTemplateInstantiation)
4422754fe60SDimitry Andric     return !Context.getLangOptions().AppleKext
4432754fe60SDimitry Andric              ? llvm::Function::WeakODRLinkage
4446122f3e6SDimitry Andric              : llvm::Function::ExternalLinkage;
445ffd1746dSEd Schouten 
446f22ef01cSRoman Divacky   // Otherwise, we have strong external linkage.
447ffd1746dSEd Schouten   assert(Linkage == GVA_StrongExternal);
448f22ef01cSRoman Divacky   return llvm::Function::ExternalLinkage;
449f22ef01cSRoman Divacky }
450f22ef01cSRoman Divacky 
451f22ef01cSRoman Divacky 
452f22ef01cSRoman Divacky /// SetFunctionDefinitionAttributes - Set attributes for a global.
453f22ef01cSRoman Divacky ///
454f22ef01cSRoman Divacky /// FIXME: This is currently only done for aliases and functions, but not for
455f22ef01cSRoman Divacky /// variables (these details are set in EmitGlobalVarDefinition for variables).
456f22ef01cSRoman Divacky void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
457f22ef01cSRoman Divacky                                                     llvm::GlobalValue *GV) {
458f22ef01cSRoman Divacky   SetCommonAttributes(D, GV);
459f22ef01cSRoman Divacky }
460f22ef01cSRoman Divacky 
461f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
462f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
463f22ef01cSRoman Divacky                                               llvm::Function *F) {
464f22ef01cSRoman Divacky   unsigned CallingConv;
465f22ef01cSRoman Divacky   AttributeListType AttributeList;
466f22ef01cSRoman Divacky   ConstructAttributeList(Info, D, AttributeList, CallingConv);
467f22ef01cSRoman Divacky   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
468f22ef01cSRoman Divacky                                           AttributeList.size()));
469f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
470f22ef01cSRoman Divacky }
471f22ef01cSRoman Divacky 
4726122f3e6SDimitry Andric /// Determines whether the language options require us to model
4736122f3e6SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
4746122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
4756122f3e6SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
4766122f3e6SDimitry Andric /// enables this.
4776122f3e6SDimitry Andric static bool hasUnwindExceptions(const LangOptions &Features) {
4786122f3e6SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
4796122f3e6SDimitry Andric   if (!Features.Exceptions) return false;
4806122f3e6SDimitry Andric 
4816122f3e6SDimitry Andric   // If C++ exceptions are enabled, this is true.
4826122f3e6SDimitry Andric   if (Features.CXXExceptions) return true;
4836122f3e6SDimitry Andric 
4846122f3e6SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
4856122f3e6SDimitry Andric   if (Features.ObjCExceptions) {
4866122f3e6SDimitry Andric     if (!Features.ObjCNonFragileABI) return false;
4876122f3e6SDimitry Andric   }
4886122f3e6SDimitry Andric 
4896122f3e6SDimitry Andric   return true;
4906122f3e6SDimitry Andric }
4916122f3e6SDimitry Andric 
492f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
493f22ef01cSRoman Divacky                                                            llvm::Function *F) {
494bd5abe19SDimitry Andric   if (CodeGenOpts.UnwindTables)
495bd5abe19SDimitry Andric     F->setHasUWTable();
496bd5abe19SDimitry Andric 
4976122f3e6SDimitry Andric   if (!hasUnwindExceptions(Features))
498f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::NoUnwind);
499f22ef01cSRoman Divacky 
5006122f3e6SDimitry Andric   if (D->hasAttr<NakedAttr>()) {
5016122f3e6SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
5022754fe60SDimitry Andric     F->addFnAttr(llvm::Attribute::Naked);
5036122f3e6SDimitry Andric     F->addFnAttr(llvm::Attribute::NoInline);
5046122f3e6SDimitry Andric   }
5052754fe60SDimitry Andric 
506f22ef01cSRoman Divacky   if (D->hasAttr<NoInlineAttr>())
507f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::NoInline);
508f22ef01cSRoman Divacky 
5096122f3e6SDimitry Andric   // (noinline wins over always_inline, and we can't specify both in IR)
5106122f3e6SDimitry Andric   if (D->hasAttr<AlwaysInlineAttr>() &&
5116122f3e6SDimitry Andric       !F->hasFnAttr(llvm::Attribute::NoInline))
5126122f3e6SDimitry Andric     F->addFnAttr(llvm::Attribute::AlwaysInline);
5136122f3e6SDimitry Andric 
5142754fe60SDimitry Andric   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
5152754fe60SDimitry Andric     F->setUnnamedAddr(true);
5162754fe60SDimitry Andric 
5176122f3e6SDimitry Andric   if (Features.getStackProtector() == LangOptions::SSPOn)
518f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::StackProtect);
5196122f3e6SDimitry Andric   else if (Features.getStackProtector() == LangOptions::SSPReq)
520f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::StackProtectReq);
521f22ef01cSRoman Divacky 
522e580952dSDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
523e580952dSDimitry Andric   if (alignment)
524e580952dSDimitry Andric     F->setAlignment(alignment);
525e580952dSDimitry Andric 
526f22ef01cSRoman Divacky   // C++ ABI requires 2-byte alignment for member functions.
527f22ef01cSRoman Divacky   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
528f22ef01cSRoman Divacky     F->setAlignment(2);
529f22ef01cSRoman Divacky }
530f22ef01cSRoman Divacky 
531f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
532f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
5332754fe60SDimitry Andric   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
5342754fe60SDimitry Andric     setGlobalVisibility(GV, ND);
5352754fe60SDimitry Andric   else
5362754fe60SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
537f22ef01cSRoman Divacky 
538f22ef01cSRoman Divacky   if (D->hasAttr<UsedAttr>())
539f22ef01cSRoman Divacky     AddUsedGlobal(GV);
540f22ef01cSRoman Divacky 
541f22ef01cSRoman Divacky   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
542f22ef01cSRoman Divacky     GV->setSection(SA->getName());
543f22ef01cSRoman Divacky 
544f22ef01cSRoman Divacky   getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
545f22ef01cSRoman Divacky }
546f22ef01cSRoman Divacky 
547f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
548f22ef01cSRoman Divacky                                                   llvm::Function *F,
549f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
550f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
551f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
552f22ef01cSRoman Divacky 
553f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
554f22ef01cSRoman Divacky 
555f22ef01cSRoman Divacky   SetCommonAttributes(D, F);
556f22ef01cSRoman Divacky }
557f22ef01cSRoman Divacky 
558f22ef01cSRoman Divacky void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
559f22ef01cSRoman Divacky                                           llvm::Function *F,
560f22ef01cSRoman Divacky                                           bool IsIncompleteFunction) {
5613b0f4066SDimitry Andric   if (unsigned IID = F->getIntrinsicID()) {
5623b0f4066SDimitry Andric     // If this is an intrinsic function, set the function's attributes
5633b0f4066SDimitry Andric     // to the intrinsic's attributes.
5643b0f4066SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
5653b0f4066SDimitry Andric     return;
5663b0f4066SDimitry Andric   }
5673b0f4066SDimitry Andric 
568f22ef01cSRoman Divacky   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
569f22ef01cSRoman Divacky 
570f22ef01cSRoman Divacky   if (!IsIncompleteFunction)
571f22ef01cSRoman Divacky     SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
572f22ef01cSRoman Divacky 
573f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
574f22ef01cSRoman Divacky   // overridden by a definition.
575f22ef01cSRoman Divacky 
576f22ef01cSRoman Divacky   if (FD->hasAttr<DLLImportAttr>()) {
577f22ef01cSRoman Divacky     F->setLinkage(llvm::Function::DLLImportLinkage);
578f22ef01cSRoman Divacky   } else if (FD->hasAttr<WeakAttr>() ||
5793b0f4066SDimitry Andric              FD->isWeakImported()) {
580f22ef01cSRoman Divacky     // "extern_weak" is overloaded in LLVM; we probably should have
581f22ef01cSRoman Divacky     // separate linkage types for this.
582f22ef01cSRoman Divacky     F->setLinkage(llvm::Function::ExternalWeakLinkage);
583f22ef01cSRoman Divacky   } else {
584f22ef01cSRoman Divacky     F->setLinkage(llvm::Function::ExternalLinkage);
5852754fe60SDimitry Andric 
5862754fe60SDimitry Andric     NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
5872754fe60SDimitry Andric     if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
5882754fe60SDimitry Andric       F->setVisibility(GetLLVMVisibility(LV.visibility()));
5892754fe60SDimitry Andric     }
590f22ef01cSRoman Divacky   }
591f22ef01cSRoman Divacky 
592f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
593f22ef01cSRoman Divacky     F->setSection(SA->getName());
594f22ef01cSRoman Divacky }
595f22ef01cSRoman Divacky 
596f22ef01cSRoman Divacky void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
597f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
598f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
599f22ef01cSRoman Divacky   LLVMUsed.push_back(GV);
600f22ef01cSRoman Divacky }
601f22ef01cSRoman Divacky 
602f22ef01cSRoman Divacky void CodeGenModule::EmitLLVMUsed() {
603f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
604f22ef01cSRoman Divacky   if (LLVMUsed.empty())
605f22ef01cSRoman Divacky     return;
606f22ef01cSRoman Divacky 
6076122f3e6SDimitry Andric   llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
608f22ef01cSRoman Divacky 
609f22ef01cSRoman Divacky   // Convert LLVMUsed to what ConstantArray needs.
610f22ef01cSRoman Divacky   std::vector<llvm::Constant*> UsedArray;
611f22ef01cSRoman Divacky   UsedArray.resize(LLVMUsed.size());
612f22ef01cSRoman Divacky   for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
613f22ef01cSRoman Divacky     UsedArray[i] =
614f22ef01cSRoman Divacky      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
615f22ef01cSRoman Divacky                                       i8PTy);
616f22ef01cSRoman Divacky   }
617f22ef01cSRoman Divacky 
618f22ef01cSRoman Divacky   if (UsedArray.empty())
619f22ef01cSRoman Divacky     return;
620f22ef01cSRoman Divacky   llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
621f22ef01cSRoman Divacky 
622f22ef01cSRoman Divacky   llvm::GlobalVariable *GV =
623f22ef01cSRoman Divacky     new llvm::GlobalVariable(getModule(), ATy, false,
624f22ef01cSRoman Divacky                              llvm::GlobalValue::AppendingLinkage,
625f22ef01cSRoman Divacky                              llvm::ConstantArray::get(ATy, UsedArray),
626f22ef01cSRoman Divacky                              "llvm.used");
627f22ef01cSRoman Divacky 
628f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
629f22ef01cSRoman Divacky }
630f22ef01cSRoman Divacky 
631f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
632f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
633f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
634f22ef01cSRoman Divacky   // for a static function, iterate until no changes are made.
635f22ef01cSRoman Divacky 
636f22ef01cSRoman Divacky   while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
637f22ef01cSRoman Divacky     if (!DeferredVTables.empty()) {
638f22ef01cSRoman Divacky       const CXXRecordDecl *RD = DeferredVTables.back();
639f22ef01cSRoman Divacky       DeferredVTables.pop_back();
640f22ef01cSRoman Divacky       getVTables().GenerateClassData(getVTableLinkage(RD), RD);
641f22ef01cSRoman Divacky       continue;
642f22ef01cSRoman Divacky     }
643f22ef01cSRoman Divacky 
644f22ef01cSRoman Divacky     GlobalDecl D = DeferredDeclsToEmit.back();
645f22ef01cSRoman Divacky     DeferredDeclsToEmit.pop_back();
646f22ef01cSRoman Divacky 
647f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
648f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
649f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
650f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
651f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
652f22ef01cSRoman Divacky     // ignore these cases.
653f22ef01cSRoman Divacky     //
654f22ef01cSRoman Divacky     // TODO: That said, looking this up multiple times is very wasteful.
6556122f3e6SDimitry Andric     StringRef Name = getMangledName(D);
656f22ef01cSRoman Divacky     llvm::GlobalValue *CGRef = GetGlobalValue(Name);
657f22ef01cSRoman Divacky     assert(CGRef && "Deferred decl wasn't referenced?");
658f22ef01cSRoman Divacky 
659f22ef01cSRoman Divacky     if (!CGRef->isDeclaration())
660f22ef01cSRoman Divacky       continue;
661f22ef01cSRoman Divacky 
662f22ef01cSRoman Divacky     // GlobalAlias::isDeclaration() defers to the aliasee, but for our
663f22ef01cSRoman Divacky     // purposes an alias counts as a definition.
664f22ef01cSRoman Divacky     if (isa<llvm::GlobalAlias>(CGRef))
665f22ef01cSRoman Divacky       continue;
666f22ef01cSRoman Divacky 
667f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
668f22ef01cSRoman Divacky     EmitGlobalDefinition(D);
669f22ef01cSRoman Divacky   }
670f22ef01cSRoman Divacky }
671f22ef01cSRoman Divacky 
6726122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
6736122f3e6SDimitry Andric   if (Annotations.empty())
6746122f3e6SDimitry Andric     return;
6756122f3e6SDimitry Andric 
6766122f3e6SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
6776122f3e6SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
6786122f3e6SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
6796122f3e6SDimitry Andric   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
6806122f3e6SDimitry Andric     Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
6816122f3e6SDimitry Andric     "llvm.global.annotations");
6826122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
6836122f3e6SDimitry Andric }
6846122f3e6SDimitry Andric 
6856122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
6866122f3e6SDimitry Andric   llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
6876122f3e6SDimitry Andric   if (i != AnnotationStrings.end())
6886122f3e6SDimitry Andric     return i->second;
6896122f3e6SDimitry Andric 
6906122f3e6SDimitry Andric   // Not found yet, create a new global.
6916122f3e6SDimitry Andric   llvm::Constant *s = llvm::ConstantArray::get(getLLVMContext(), Str, true);
6926122f3e6SDimitry Andric   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
6936122f3e6SDimitry Andric     true, llvm::GlobalValue::PrivateLinkage, s, ".str");
6946122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
6956122f3e6SDimitry Andric   gv->setUnnamedAddr(true);
6966122f3e6SDimitry Andric   AnnotationStrings[Str] = gv;
6976122f3e6SDimitry Andric   return gv;
6986122f3e6SDimitry Andric }
6996122f3e6SDimitry Andric 
7006122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
7016122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
7026122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
7036122f3e6SDimitry Andric   if (PLoc.isValid())
7046122f3e6SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
7056122f3e6SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
7066122f3e6SDimitry Andric }
7076122f3e6SDimitry Andric 
7086122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
7096122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
7106122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
7116122f3e6SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
7126122f3e6SDimitry Andric     SM.getExpansionLineNumber(L);
7136122f3e6SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
7146122f3e6SDimitry Andric }
7156122f3e6SDimitry Andric 
716f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
717f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
7186122f3e6SDimitry Andric                                                 SourceLocation L) {
7196122f3e6SDimitry Andric   // Get the globals for file name, annotation, and the line number.
7206122f3e6SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
7216122f3e6SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
7226122f3e6SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
723f22ef01cSRoman Divacky 
724f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
725f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
7266122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
7276122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
7286122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
7296122f3e6SDimitry Andric     LineNoCst
730f22ef01cSRoman Divacky   };
73117a519f9SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
732f22ef01cSRoman Divacky }
733f22ef01cSRoman Divacky 
7346122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
7356122f3e6SDimitry Andric                                          llvm::GlobalValue *GV) {
7366122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
7376122f3e6SDimitry Andric   // Get the struct elements for these annotations.
7386122f3e6SDimitry Andric   for (specific_attr_iterator<AnnotateAttr>
7396122f3e6SDimitry Andric        ai = D->specific_attr_begin<AnnotateAttr>(),
7406122f3e6SDimitry Andric        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
7416122f3e6SDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
7426122f3e6SDimitry Andric }
7436122f3e6SDimitry Andric 
744f22ef01cSRoman Divacky bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
745e580952dSDimitry Andric   // Never defer when EmitAllDecls is specified.
746e580952dSDimitry Andric   if (Features.EmitAllDecls)
747f22ef01cSRoman Divacky     return false;
748f22ef01cSRoman Divacky 
749e580952dSDimitry Andric   return !getContext().DeclMustBeEmitted(Global);
750f22ef01cSRoman Divacky }
751f22ef01cSRoman Divacky 
752f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
753f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
754f22ef01cSRoman Divacky   assert(AA && "No alias?");
755f22ef01cSRoman Divacky 
7566122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
757f22ef01cSRoman Divacky 
758f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
759f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
760f22ef01cSRoman Divacky 
761f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
762f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
7632754fe60SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
7642754fe60SDimitry Andric                                       /*ForVTable=*/false);
765f22ef01cSRoman Divacky   else
766f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
767f22ef01cSRoman Divacky                                     llvm::PointerType::getUnqual(DeclTy), 0);
768f22ef01cSRoman Divacky   if (!Entry) {
769f22ef01cSRoman Divacky     llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
770f22ef01cSRoman Divacky     F->setLinkage(llvm::Function::ExternalWeakLinkage);
771f22ef01cSRoman Divacky     WeakRefReferences.insert(F);
772f22ef01cSRoman Divacky   }
773f22ef01cSRoman Divacky 
774f22ef01cSRoman Divacky   return Aliasee;
775f22ef01cSRoman Divacky }
776f22ef01cSRoman Divacky 
777f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
778f22ef01cSRoman Divacky   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
779f22ef01cSRoman Divacky 
780f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
781f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
782f22ef01cSRoman Divacky     return;
783f22ef01cSRoman Divacky 
784f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
785f22ef01cSRoman Divacky   // emit it now.
786f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
787f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
788f22ef01cSRoman Divacky 
7896122f3e6SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
7906122f3e6SDimitry Andric   if (Features.CUDA) {
7916122f3e6SDimitry Andric     if (CodeGenOpts.CUDAIsDevice) {
7926122f3e6SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
7936122f3e6SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
7946122f3e6SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
7956122f3e6SDimitry Andric           !Global->hasAttr<CUDASharedAttr>())
7966122f3e6SDimitry Andric         return;
7976122f3e6SDimitry Andric     } else {
7986122f3e6SDimitry Andric       if (!Global->hasAttr<CUDAHostAttr>() && (
7996122f3e6SDimitry Andric             Global->hasAttr<CUDADeviceAttr>() ||
8006122f3e6SDimitry Andric             Global->hasAttr<CUDAConstantAttr>() ||
8016122f3e6SDimitry Andric             Global->hasAttr<CUDASharedAttr>()))
8026122f3e6SDimitry Andric         return;
803e580952dSDimitry Andric     }
804e580952dSDimitry Andric   }
805e580952dSDimitry Andric 
8066122f3e6SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
8076122f3e6SDimitry Andric   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
808f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
8096122f3e6SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
8106122f3e6SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
811f22ef01cSRoman Divacky         return;
8126122f3e6SDimitry Andric 
8136122f3e6SDimitry Andric       const FunctionDecl *InlineDefinition = 0;
8146122f3e6SDimitry Andric       FD->getBody(InlineDefinition);
8156122f3e6SDimitry Andric 
8166122f3e6SDimitry Andric       StringRef MangledName = getMangledName(GD);
8176122f3e6SDimitry Andric       llvm::StringMap<GlobalDecl>::iterator DDI =
8186122f3e6SDimitry Andric           DeferredDecls.find(MangledName);
8196122f3e6SDimitry Andric       if (DDI != DeferredDecls.end())
8206122f3e6SDimitry Andric         DeferredDecls.erase(DDI);
8216122f3e6SDimitry Andric       EmitGlobalDefinition(InlineDefinition);
8226122f3e6SDimitry Andric       return;
8236122f3e6SDimitry Andric     }
824f22ef01cSRoman Divacky   } else {
825f22ef01cSRoman Divacky     const VarDecl *VD = cast<VarDecl>(Global);
826f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
827f22ef01cSRoman Divacky 
828f22ef01cSRoman Divacky     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
829f22ef01cSRoman Divacky       return;
830f22ef01cSRoman Divacky   }
831f22ef01cSRoman Divacky 
832f22ef01cSRoman Divacky   // Defer code generation when possible if this is a static definition, inline
833f22ef01cSRoman Divacky   // function etc.  These we only want to emit if they are used.
834f22ef01cSRoman Divacky   if (!MayDeferGeneration(Global)) {
835f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
836f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
837f22ef01cSRoman Divacky     return;
838f22ef01cSRoman Divacky   }
839f22ef01cSRoman Divacky 
840e580952dSDimitry Andric   // If we're deferring emission of a C++ variable with an
841e580952dSDimitry Andric   // initializer, remember the order in which it appeared in the file.
842e580952dSDimitry Andric   if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
843e580952dSDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
844e580952dSDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
845e580952dSDimitry Andric     CXXGlobalInits.push_back(0);
846e580952dSDimitry Andric   }
847e580952dSDimitry Andric 
848f22ef01cSRoman Divacky   // If the value has already been used, add it directly to the
849f22ef01cSRoman Divacky   // DeferredDeclsToEmit list.
8506122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
851f22ef01cSRoman Divacky   if (GetGlobalValue(MangledName))
852f22ef01cSRoman Divacky     DeferredDeclsToEmit.push_back(GD);
853f22ef01cSRoman Divacky   else {
854f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
855f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
856f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
857f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
858f22ef01cSRoman Divacky   }
859f22ef01cSRoman Divacky }
860f22ef01cSRoman Divacky 
861f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
862f22ef01cSRoman Divacky   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
863f22ef01cSRoman Divacky 
864f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
865f22ef01cSRoman Divacky                                  Context.getSourceManager(),
866f22ef01cSRoman Divacky                                  "Generating code for declaration");
867f22ef01cSRoman Divacky 
868ffd1746dSEd Schouten   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
869ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
870ffd1746dSEd Schouten     // linkage.
871ffd1746dSEd Schouten     if (CodeGenOpts.OptimizationLevel == 0 &&
872e580952dSDimitry Andric         !Function->hasAttr<AlwaysInlineAttr>() &&
873ffd1746dSEd Schouten         getFunctionLinkage(Function)
874ffd1746dSEd Schouten                                   == llvm::Function::AvailableExternallyLinkage)
875ffd1746dSEd Schouten       return;
876ffd1746dSEd Schouten 
877ffd1746dSEd Schouten     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
878bd5abe19SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
879bd5abe19SDimitry Andric       // This is necessary for the generation of certain thunks.
880bd5abe19SDimitry Andric       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
881bd5abe19SDimitry Andric         EmitCXXConstructor(CD, GD.getCtorType());
882bd5abe19SDimitry Andric       else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
883bd5abe19SDimitry Andric         EmitCXXDestructor(DD, GD.getDtorType());
884bd5abe19SDimitry Andric       else
885bd5abe19SDimitry Andric         EmitGlobalFunctionDefinition(GD);
886bd5abe19SDimitry Andric 
887f22ef01cSRoman Divacky       if (Method->isVirtual())
888f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
889f22ef01cSRoman Divacky 
890bd5abe19SDimitry Andric       return;
891ffd1746dSEd Schouten     }
892f22ef01cSRoman Divacky 
893f22ef01cSRoman Divacky     return EmitGlobalFunctionDefinition(GD);
894ffd1746dSEd Schouten   }
895f22ef01cSRoman Divacky 
896f22ef01cSRoman Divacky   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
897f22ef01cSRoman Divacky     return EmitGlobalVarDefinition(VD);
898f22ef01cSRoman Divacky 
8996122f3e6SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
900f22ef01cSRoman Divacky }
901f22ef01cSRoman Divacky 
902f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
903f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
904f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
905f22ef01cSRoman Divacky /// bitcasted to the right type.
906f22ef01cSRoman Divacky ///
907f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
908f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
909f22ef01cSRoman Divacky llvm::Constant *
9106122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
9116122f3e6SDimitry Andric                                        llvm::Type *Ty,
91217a519f9SDimitry Andric                                        GlobalDecl D, bool ForVTable,
91317a519f9SDimitry Andric                                        llvm::Attributes ExtraAttrs) {
914f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
915f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
916f22ef01cSRoman Divacky   if (Entry) {
917f22ef01cSRoman Divacky     if (WeakRefReferences.count(Entry)) {
918f22ef01cSRoman Divacky       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
919f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
920f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
921f22ef01cSRoman Divacky 
922f22ef01cSRoman Divacky       WeakRefReferences.erase(Entry);
923f22ef01cSRoman Divacky     }
924f22ef01cSRoman Divacky 
925f22ef01cSRoman Divacky     if (Entry->getType()->getElementType() == Ty)
926f22ef01cSRoman Divacky       return Entry;
927f22ef01cSRoman Divacky 
928f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
92917a519f9SDimitry Andric     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
930f22ef01cSRoman Divacky   }
931f22ef01cSRoman Divacky 
932f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
933f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
934f22ef01cSRoman Divacky   // sure not to try to set attributes.
935f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
936f22ef01cSRoman Divacky 
9376122f3e6SDimitry Andric   llvm::FunctionType *FTy;
938f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
939f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
940f22ef01cSRoman Divacky   } else {
941bd5abe19SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
942f22ef01cSRoman Divacky     IsIncompleteFunction = true;
943f22ef01cSRoman Divacky   }
944ffd1746dSEd Schouten 
945f22ef01cSRoman Divacky   llvm::Function *F = llvm::Function::Create(FTy,
946f22ef01cSRoman Divacky                                              llvm::Function::ExternalLinkage,
947f22ef01cSRoman Divacky                                              MangledName, &getModule());
948f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
949f22ef01cSRoman Divacky   if (D.getDecl())
950f22ef01cSRoman Divacky     SetFunctionAttributes(D, F, IsIncompleteFunction);
95117a519f9SDimitry Andric   if (ExtraAttrs != llvm::Attribute::None)
95217a519f9SDimitry Andric     F->addFnAttr(ExtraAttrs);
953f22ef01cSRoman Divacky 
954f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
955f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
956f22ef01cSRoman Divacky   // of the file.
957f22ef01cSRoman Divacky   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
958f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
959f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
960f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
961f22ef01cSRoman Divacky     DeferredDeclsToEmit.push_back(DDI->second);
962f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
9632754fe60SDimitry Andric 
9642754fe60SDimitry Andric   // Otherwise, there are cases we have to worry about where we're
9652754fe60SDimitry Andric   // using a declaration for which we must emit a definition but where
9662754fe60SDimitry Andric   // we might not find a top-level definition:
9672754fe60SDimitry Andric   //   - member functions defined inline in their classes
9682754fe60SDimitry Andric   //   - friend functions defined inline in some class
9692754fe60SDimitry Andric   //   - special member functions with implicit definitions
9702754fe60SDimitry Andric   // If we ever change our AST traversal to walk into class methods,
9712754fe60SDimitry Andric   // this will be unnecessary.
9722754fe60SDimitry Andric   //
9732754fe60SDimitry Andric   // We also don't emit a definition for a function if it's going to be an entry
9742754fe60SDimitry Andric   // in a vtable, unless it's already marked as used.
9752754fe60SDimitry Andric   } else if (getLangOptions().CPlusPlus && D.getDecl()) {
9762754fe60SDimitry Andric     // Look for a declaration that's lexically in a record.
9772754fe60SDimitry Andric     const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
9782754fe60SDimitry Andric     do {
9792754fe60SDimitry Andric       if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9802754fe60SDimitry Andric         if (FD->isImplicit() && !ForVTable) {
9812754fe60SDimitry Andric           assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
9822754fe60SDimitry Andric           DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
9832754fe60SDimitry Andric           break;
984bd5abe19SDimitry Andric         } else if (FD->doesThisDeclarationHaveABody()) {
9852754fe60SDimitry Andric           DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
9862754fe60SDimitry Andric           break;
987f22ef01cSRoman Divacky         }
988f22ef01cSRoman Divacky       }
9892754fe60SDimitry Andric       FD = FD->getPreviousDeclaration();
9902754fe60SDimitry Andric     } while (FD);
991f22ef01cSRoman Divacky   }
992f22ef01cSRoman Divacky 
993f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
994f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
995f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
996f22ef01cSRoman Divacky     return F;
997f22ef01cSRoman Divacky   }
998f22ef01cSRoman Divacky 
99917a519f9SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1000f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
1001f22ef01cSRoman Divacky }
1002f22ef01cSRoman Divacky 
1003f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1004f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
1005f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
1006f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
10076122f3e6SDimitry Andric                                                  llvm::Type *Ty,
10082754fe60SDimitry Andric                                                  bool ForVTable) {
1009f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
1010f22ef01cSRoman Divacky   if (!Ty)
1011f22ef01cSRoman Divacky     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1012ffd1746dSEd Schouten 
10136122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
10142754fe60SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
1015f22ef01cSRoman Divacky }
1016f22ef01cSRoman Divacky 
1017f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
1018f22ef01cSRoman Divacky /// type and name.
1019f22ef01cSRoman Divacky llvm::Constant *
10206122f3e6SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
10216122f3e6SDimitry Andric                                      StringRef Name,
102217a519f9SDimitry Andric                                      llvm::Attributes ExtraAttrs) {
102317a519f9SDimitry Andric   return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
102417a519f9SDimitry Andric                                  ExtraAttrs);
1025f22ef01cSRoman Divacky }
1026f22ef01cSRoman Divacky 
1027bd5abe19SDimitry Andric static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D,
1028bd5abe19SDimitry Andric                                  bool ConstantInit) {
1029f22ef01cSRoman Divacky   if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
1030f22ef01cSRoman Divacky     return false;
1031bd5abe19SDimitry Andric 
1032bd5abe19SDimitry Andric   if (Context.getLangOptions().CPlusPlus) {
1033bd5abe19SDimitry Andric     if (const RecordType *Record
1034bd5abe19SDimitry Andric           = Context.getBaseElementType(D->getType())->getAs<RecordType>())
1035bd5abe19SDimitry Andric       return ConstantInit &&
1036bd5abe19SDimitry Andric              cast<CXXRecordDecl>(Record->getDecl())->isPOD() &&
1037bd5abe19SDimitry Andric              !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields();
1038f22ef01cSRoman Divacky   }
1039bd5abe19SDimitry Andric 
1040f22ef01cSRoman Divacky   return true;
1041f22ef01cSRoman Divacky }
1042f22ef01cSRoman Divacky 
1043f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1044f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
1045f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
1046f22ef01cSRoman Divacky /// bitcasted to the right type.
1047f22ef01cSRoman Divacky ///
1048f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
1049f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
1050f22ef01cSRoman Divacky llvm::Constant *
10516122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
10526122f3e6SDimitry Andric                                      llvm::PointerType *Ty,
10532754fe60SDimitry Andric                                      const VarDecl *D,
10542754fe60SDimitry Andric                                      bool UnnamedAddr) {
1055f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
1056f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1057f22ef01cSRoman Divacky   if (Entry) {
1058f22ef01cSRoman Divacky     if (WeakRefReferences.count(Entry)) {
1059f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
1060f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
1061f22ef01cSRoman Divacky 
1062f22ef01cSRoman Divacky       WeakRefReferences.erase(Entry);
1063f22ef01cSRoman Divacky     }
1064f22ef01cSRoman Divacky 
10652754fe60SDimitry Andric     if (UnnamedAddr)
10662754fe60SDimitry Andric       Entry->setUnnamedAddr(true);
10672754fe60SDimitry Andric 
1068f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
1069f22ef01cSRoman Divacky       return Entry;
1070f22ef01cSRoman Divacky 
1071f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
1072f22ef01cSRoman Divacky     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1073f22ef01cSRoman Divacky   }
1074f22ef01cSRoman Divacky 
1075f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
1076f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
1077f22ef01cSRoman Divacky   // of the file.
1078f22ef01cSRoman Divacky   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1079f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
1080f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1081f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
1082f22ef01cSRoman Divacky     DeferredDeclsToEmit.push_back(DDI->second);
1083f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
1084f22ef01cSRoman Divacky   }
1085f22ef01cSRoman Divacky 
1086f22ef01cSRoman Divacky   llvm::GlobalVariable *GV =
1087f22ef01cSRoman Divacky     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1088f22ef01cSRoman Divacky                              llvm::GlobalValue::ExternalLinkage,
1089f22ef01cSRoman Divacky                              0, MangledName, 0,
1090f22ef01cSRoman Divacky                              false, Ty->getAddressSpace());
1091f22ef01cSRoman Divacky 
1092f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
1093f22ef01cSRoman Divacky   if (D) {
1094f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
1095f22ef01cSRoman Divacky     // handling.
1096bd5abe19SDimitry Andric     GV->setConstant(DeclIsConstantGlobal(Context, D, false));
1097f22ef01cSRoman Divacky 
10982754fe60SDimitry Andric     // Set linkage and visibility in case we never see a definition.
10992754fe60SDimitry Andric     NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
11002754fe60SDimitry Andric     if (LV.linkage() != ExternalLinkage) {
11012754fe60SDimitry Andric       // Don't set internal linkage on declarations.
11022754fe60SDimitry Andric     } else {
11032754fe60SDimitry Andric       if (D->hasAttr<DLLImportAttr>())
11042754fe60SDimitry Andric         GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
11053b0f4066SDimitry Andric       else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1106f22ef01cSRoman Divacky         GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1107f22ef01cSRoman Divacky 
11082754fe60SDimitry Andric       // Set visibility on a declaration only if it's explicit.
11092754fe60SDimitry Andric       if (LV.visibilityExplicit())
11102754fe60SDimitry Andric         GV->setVisibility(GetLLVMVisibility(LV.visibility()));
11112754fe60SDimitry Andric     }
11122754fe60SDimitry Andric 
1113f22ef01cSRoman Divacky     GV->setThreadLocal(D->isThreadSpecified());
1114f22ef01cSRoman Divacky   }
1115f22ef01cSRoman Divacky 
1116f22ef01cSRoman Divacky   return GV;
1117f22ef01cSRoman Divacky }
1118f22ef01cSRoman Divacky 
1119f22ef01cSRoman Divacky 
11202754fe60SDimitry Andric llvm::GlobalVariable *
11216122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
11226122f3e6SDimitry Andric                                       llvm::Type *Ty,
11232754fe60SDimitry Andric                                       llvm::GlobalValue::LinkageTypes Linkage) {
11242754fe60SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
11252754fe60SDimitry Andric   llvm::GlobalVariable *OldGV = 0;
11262754fe60SDimitry Andric 
11272754fe60SDimitry Andric 
11282754fe60SDimitry Andric   if (GV) {
11292754fe60SDimitry Andric     // Check if the variable has the right type.
11302754fe60SDimitry Andric     if (GV->getType()->getElementType() == Ty)
11312754fe60SDimitry Andric       return GV;
11322754fe60SDimitry Andric 
11332754fe60SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
11342754fe60SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
11352754fe60SDimitry Andric       assert(GV->isDeclaration() && "Declaration has wrong type!");
11362754fe60SDimitry Andric     OldGV = GV;
11372754fe60SDimitry Andric   }
11382754fe60SDimitry Andric 
11392754fe60SDimitry Andric   // Create a new variable.
11402754fe60SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
11412754fe60SDimitry Andric                                 Linkage, 0, Name);
11422754fe60SDimitry Andric 
11432754fe60SDimitry Andric   if (OldGV) {
11442754fe60SDimitry Andric     // Replace occurrences of the old variable if needed.
11452754fe60SDimitry Andric     GV->takeName(OldGV);
11462754fe60SDimitry Andric 
11472754fe60SDimitry Andric     if (!OldGV->use_empty()) {
11482754fe60SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
11492754fe60SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
11502754fe60SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
11512754fe60SDimitry Andric     }
11522754fe60SDimitry Andric 
11532754fe60SDimitry Andric     OldGV->eraseFromParent();
11542754fe60SDimitry Andric   }
11552754fe60SDimitry Andric 
11562754fe60SDimitry Andric   return GV;
11572754fe60SDimitry Andric }
11582754fe60SDimitry Andric 
1159f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1160f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
1161f22ef01cSRoman Divacky /// then it will be greated with the specified type instead of whatever the
1162f22ef01cSRoman Divacky /// normal requested type would be.
1163f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
11646122f3e6SDimitry Andric                                                   llvm::Type *Ty) {
1165f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
1166f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
1167f22ef01cSRoman Divacky   if (Ty == 0)
1168f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
1169f22ef01cSRoman Divacky 
11706122f3e6SDimitry Andric   llvm::PointerType *PTy =
11713b0f4066SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1172f22ef01cSRoman Divacky 
11736122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
1174f22ef01cSRoman Divacky   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1175f22ef01cSRoman Divacky }
1176f22ef01cSRoman Divacky 
1177f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
1178f22ef01cSRoman Divacky /// specified type and name.
1179f22ef01cSRoman Divacky llvm::Constant *
11806122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
11816122f3e6SDimitry Andric                                      StringRef Name) {
11822754fe60SDimitry Andric   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
11832754fe60SDimitry Andric                                true);
1184f22ef01cSRoman Divacky }
1185f22ef01cSRoman Divacky 
1186f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1187f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
1188f22ef01cSRoman Divacky 
1189f22ef01cSRoman Divacky   if (MayDeferGeneration(D)) {
1190f22ef01cSRoman Divacky     // If we have not seen a reference to this variable yet, place it
1191f22ef01cSRoman Divacky     // into the deferred declarations table to be emitted if needed
1192f22ef01cSRoman Divacky     // later.
11936122f3e6SDimitry Andric     StringRef MangledName = getMangledName(D);
1194f22ef01cSRoman Divacky     if (!GetGlobalValue(MangledName)) {
1195f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
1196f22ef01cSRoman Divacky       return;
1197f22ef01cSRoman Divacky     }
1198f22ef01cSRoman Divacky   }
1199f22ef01cSRoman Divacky 
1200f22ef01cSRoman Divacky   // The tentative definition is the only definition.
1201f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
1202f22ef01cSRoman Divacky }
1203f22ef01cSRoman Divacky 
1204f22ef01cSRoman Divacky void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1205f22ef01cSRoman Divacky   if (DefinitionRequired)
1206f22ef01cSRoman Divacky     getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1207f22ef01cSRoman Divacky }
1208f22ef01cSRoman Divacky 
1209f22ef01cSRoman Divacky llvm::GlobalVariable::LinkageTypes
1210f22ef01cSRoman Divacky CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1211bd5abe19SDimitry Andric   if (RD->getLinkage() != ExternalLinkage)
1212f22ef01cSRoman Divacky     return llvm::GlobalVariable::InternalLinkage;
1213f22ef01cSRoman Divacky 
1214f22ef01cSRoman Divacky   if (const CXXMethodDecl *KeyFunction
1215f22ef01cSRoman Divacky                                     = RD->getASTContext().getKeyFunction(RD)) {
1216f22ef01cSRoman Divacky     // If this class has a key function, use that to determine the linkage of
1217f22ef01cSRoman Divacky     // the vtable.
1218f22ef01cSRoman Divacky     const FunctionDecl *Def = 0;
1219ffd1746dSEd Schouten     if (KeyFunction->hasBody(Def))
1220f22ef01cSRoman Divacky       KeyFunction = cast<CXXMethodDecl>(Def);
1221f22ef01cSRoman Divacky 
1222f22ef01cSRoman Divacky     switch (KeyFunction->getTemplateSpecializationKind()) {
1223f22ef01cSRoman Divacky       case TSK_Undeclared:
1224f22ef01cSRoman Divacky       case TSK_ExplicitSpecialization:
12252754fe60SDimitry Andric         // When compiling with optimizations turned on, we emit all vtables,
12262754fe60SDimitry Andric         // even if the key function is not defined in the current translation
12272754fe60SDimitry Andric         // unit. If this is the case, use available_externally linkage.
12282754fe60SDimitry Andric         if (!Def && CodeGenOpts.OptimizationLevel)
12292754fe60SDimitry Andric           return llvm::GlobalVariable::AvailableExternallyLinkage;
12302754fe60SDimitry Andric 
1231f22ef01cSRoman Divacky         if (KeyFunction->isInlined())
12322754fe60SDimitry Andric           return !Context.getLangOptions().AppleKext ?
12332754fe60SDimitry Andric                    llvm::GlobalVariable::LinkOnceODRLinkage :
12342754fe60SDimitry Andric                    llvm::Function::InternalLinkage;
1235f22ef01cSRoman Divacky 
1236f22ef01cSRoman Divacky         return llvm::GlobalVariable::ExternalLinkage;
1237f22ef01cSRoman Divacky 
1238f22ef01cSRoman Divacky       case TSK_ImplicitInstantiation:
12392754fe60SDimitry Andric         return !Context.getLangOptions().AppleKext ?
12402754fe60SDimitry Andric                  llvm::GlobalVariable::LinkOnceODRLinkage :
12412754fe60SDimitry Andric                  llvm::Function::InternalLinkage;
12422754fe60SDimitry Andric 
1243f22ef01cSRoman Divacky       case TSK_ExplicitInstantiationDefinition:
12442754fe60SDimitry Andric         return !Context.getLangOptions().AppleKext ?
12452754fe60SDimitry Andric                  llvm::GlobalVariable::WeakODRLinkage :
12462754fe60SDimitry Andric                  llvm::Function::InternalLinkage;
1247f22ef01cSRoman Divacky 
1248f22ef01cSRoman Divacky       case TSK_ExplicitInstantiationDeclaration:
1249f22ef01cSRoman Divacky         // FIXME: Use available_externally linkage. However, this currently
1250f22ef01cSRoman Divacky         // breaks LLVM's build due to undefined symbols.
1251f22ef01cSRoman Divacky         //      return llvm::GlobalVariable::AvailableExternallyLinkage;
12522754fe60SDimitry Andric         return !Context.getLangOptions().AppleKext ?
12532754fe60SDimitry Andric                  llvm::GlobalVariable::LinkOnceODRLinkage :
12542754fe60SDimitry Andric                  llvm::Function::InternalLinkage;
1255f22ef01cSRoman Divacky     }
1256f22ef01cSRoman Divacky   }
1257f22ef01cSRoman Divacky 
12582754fe60SDimitry Andric   if (Context.getLangOptions().AppleKext)
12592754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
12602754fe60SDimitry Andric 
1261f22ef01cSRoman Divacky   switch (RD->getTemplateSpecializationKind()) {
1262f22ef01cSRoman Divacky   case TSK_Undeclared:
1263f22ef01cSRoman Divacky   case TSK_ExplicitSpecialization:
1264f22ef01cSRoman Divacky   case TSK_ImplicitInstantiation:
1265f22ef01cSRoman Divacky     // FIXME: Use available_externally linkage. However, this currently
1266f22ef01cSRoman Divacky     // breaks LLVM's build due to undefined symbols.
1267f22ef01cSRoman Divacky     //   return llvm::GlobalVariable::AvailableExternallyLinkage;
12682754fe60SDimitry Andric   case TSK_ExplicitInstantiationDeclaration:
12692754fe60SDimitry Andric     return llvm::GlobalVariable::LinkOnceODRLinkage;
12702754fe60SDimitry Andric 
12712754fe60SDimitry Andric   case TSK_ExplicitInstantiationDefinition:
1272f22ef01cSRoman Divacky       return llvm::GlobalVariable::WeakODRLinkage;
1273f22ef01cSRoman Divacky   }
1274f22ef01cSRoman Divacky 
1275f22ef01cSRoman Divacky   // Silence GCC warning.
12762754fe60SDimitry Andric   return llvm::GlobalVariable::LinkOnceODRLinkage;
1277f22ef01cSRoman Divacky }
1278f22ef01cSRoman Divacky 
12796122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
12802754fe60SDimitry Andric     return Context.toCharUnitsFromBits(
12812754fe60SDimitry Andric       TheTargetData.getTypeStoreSizeInBits(Ty));
1282f22ef01cSRoman Divacky }
1283f22ef01cSRoman Divacky 
1284f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1285f22ef01cSRoman Divacky   llvm::Constant *Init = 0;
1286f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
1287f22ef01cSRoman Divacky   bool NonConstInit = false;
1288f22ef01cSRoman Divacky 
1289f22ef01cSRoman Divacky   const Expr *InitExpr = D->getAnyInitializer();
1290f22ef01cSRoman Divacky 
1291f22ef01cSRoman Divacky   if (!InitExpr) {
1292f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
1293f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
1294f22ef01cSRoman Divacky     //
1295f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
1296f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
1297f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
1298f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
1299f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
1300f22ef01cSRoman Divacky     // to do a RAUW.
1301f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1302f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
1303f22ef01cSRoman Divacky   } else {
1304f22ef01cSRoman Divacky     Init = EmitConstantExpr(InitExpr, D->getType());
1305f22ef01cSRoman Divacky     if (!Init) {
1306f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
1307f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
1308f22ef01cSRoman Divacky         T = D->getType();
1309f22ef01cSRoman Divacky 
1310f22ef01cSRoman Divacky       if (getLangOptions().CPlusPlus) {
1311f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
1312f22ef01cSRoman Divacky         NonConstInit = true;
1313f22ef01cSRoman Divacky       } else {
1314f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
1315f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1316f22ef01cSRoman Divacky       }
1317e580952dSDimitry Andric     } else {
1318e580952dSDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
1319e580952dSDimitry Andric       // initializer position (just in case this entry was delayed).
1320e580952dSDimitry Andric       if (getLangOptions().CPlusPlus)
1321e580952dSDimitry Andric         DelayedCXXInitPosition.erase(D);
1322f22ef01cSRoman Divacky     }
1323f22ef01cSRoman Divacky   }
1324f22ef01cSRoman Divacky 
13256122f3e6SDimitry Andric   llvm::Type* InitType = Init->getType();
1326f22ef01cSRoman Divacky   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1327f22ef01cSRoman Divacky 
1328f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
1329f22ef01cSRoman Divacky   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1330f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1331f22ef01cSRoman Divacky            // all zero index gep.
1332f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1333f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
1334f22ef01cSRoman Divacky   }
1335f22ef01cSRoman Divacky 
1336f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
1337f22ef01cSRoman Divacky   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1338f22ef01cSRoman Divacky 
1339f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
1340f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
1341f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
1342f22ef01cSRoman Divacky   // (which will be a definition).
1343f22ef01cSRoman Divacky   //
1344f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
1345f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
1346f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
1347f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
1348f22ef01cSRoman Divacky   if (GV == 0 ||
1349f22ef01cSRoman Divacky       GV->getType()->getElementType() != InitType ||
13503b0f4066SDimitry Andric       GV->getType()->getAddressSpace() !=
13513b0f4066SDimitry Andric         getContext().getTargetAddressSpace(ASTTy)) {
1352f22ef01cSRoman Divacky 
1353f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
13546122f3e6SDimitry Andric     Entry->setName(StringRef());
1355f22ef01cSRoman Divacky 
1356f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
1357f22ef01cSRoman Divacky     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1358f22ef01cSRoman Divacky 
1359f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
1360f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
1361f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1362f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1363f22ef01cSRoman Divacky 
1364f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
1365f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1366f22ef01cSRoman Divacky   }
1367f22ef01cSRoman Divacky 
13686122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
13696122f3e6SDimitry Andric     AddGlobalAnnotations(D, GV);
1370f22ef01cSRoman Divacky 
1371f22ef01cSRoman Divacky   GV->setInitializer(Init);
1372f22ef01cSRoman Divacky 
1373f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
1374f22ef01cSRoman Divacky   GV->setConstant(false);
1375bd5abe19SDimitry Andric   if (!NonConstInit && DeclIsConstantGlobal(Context, D, true))
1376f22ef01cSRoman Divacky     GV->setConstant(true);
1377f22ef01cSRoman Divacky 
1378f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1379f22ef01cSRoman Divacky 
1380f22ef01cSRoman Divacky   // Set the llvm linkage type as appropriate.
13812754fe60SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
13822754fe60SDimitry Andric     GetLLVMLinkageVarDefinition(D, GV);
13832754fe60SDimitry Andric   GV->setLinkage(Linkage);
13842754fe60SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage)
1385f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
1386f22ef01cSRoman Divacky     GV->setConstant(false);
1387f22ef01cSRoman Divacky 
1388f22ef01cSRoman Divacky   SetCommonAttributes(D, GV);
1389f22ef01cSRoman Divacky 
13902754fe60SDimitry Andric   // Emit the initializer function if necessary.
13912754fe60SDimitry Andric   if (NonConstInit)
13922754fe60SDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV);
13932754fe60SDimitry Andric 
1394f22ef01cSRoman Divacky   // Emit global variable debug information.
13956122f3e6SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
1396f22ef01cSRoman Divacky     DI->EmitGlobalVariable(GV, D);
1397f22ef01cSRoman Divacky }
1398f22ef01cSRoman Divacky 
13992754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes
14002754fe60SDimitry Andric CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
14012754fe60SDimitry Andric                                            llvm::GlobalVariable *GV) {
14022754fe60SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
14032754fe60SDimitry Andric   if (Linkage == GVA_Internal)
14042754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
14052754fe60SDimitry Andric   else if (D->hasAttr<DLLImportAttr>())
14062754fe60SDimitry Andric     return llvm::Function::DLLImportLinkage;
14072754fe60SDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
14082754fe60SDimitry Andric     return llvm::Function::DLLExportLinkage;
14092754fe60SDimitry Andric   else if (D->hasAttr<WeakAttr>()) {
14102754fe60SDimitry Andric     if (GV->isConstant())
14112754fe60SDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
14122754fe60SDimitry Andric     else
14132754fe60SDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
14142754fe60SDimitry Andric   } else if (Linkage == GVA_TemplateInstantiation ||
14152754fe60SDimitry Andric              Linkage == GVA_ExplicitTemplateInstantiation)
14163b0f4066SDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
14172754fe60SDimitry Andric   else if (!getLangOptions().CPlusPlus &&
14182754fe60SDimitry Andric            ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
14192754fe60SDimitry Andric              D->getAttr<CommonAttr>()) &&
14202754fe60SDimitry Andric            !D->hasExternalStorage() && !D->getInit() &&
142117a519f9SDimitry Andric            !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
142217a519f9SDimitry Andric            !D->getAttr<WeakImportAttr>()) {
14232754fe60SDimitry Andric     // Thread local vars aren't considered common linkage.
14242754fe60SDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
14252754fe60SDimitry Andric   }
14262754fe60SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
14272754fe60SDimitry Andric }
14282754fe60SDimitry Andric 
1429f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1430f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
1431f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
1432f22ef01cSRoman Divacky /// call the new function directly.
1433f22ef01cSRoman Divacky ///
1434f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
1435f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
1436f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
1437f22ef01cSRoman Divacky /// run at -O0.
1438f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1439f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
1440f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
1441f22ef01cSRoman Divacky   llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1442f22ef01cSRoman Divacky   if (OldFn == 0) return;
1443f22ef01cSRoman Divacky 
14446122f3e6SDimitry Andric   llvm::Type *NewRetTy = NewFn->getReturnType();
14456122f3e6SDimitry Andric   SmallVector<llvm::Value*, 4> ArgList;
1446f22ef01cSRoman Divacky 
1447f22ef01cSRoman Divacky   for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1448f22ef01cSRoman Divacky        UI != E; ) {
1449f22ef01cSRoman Divacky     // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1450f22ef01cSRoman Divacky     llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1451f22ef01cSRoman Divacky     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1452e580952dSDimitry Andric     if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1453f22ef01cSRoman Divacky     llvm::CallSite CS(CI);
1454f22ef01cSRoman Divacky     if (!CI || !CS.isCallee(I)) continue;
1455f22ef01cSRoman Divacky 
1456f22ef01cSRoman Divacky     // If the return types don't match exactly, and if the call isn't dead, then
1457f22ef01cSRoman Divacky     // we can't transform this call.
1458f22ef01cSRoman Divacky     if (CI->getType() != NewRetTy && !CI->use_empty())
1459f22ef01cSRoman Divacky       continue;
1460f22ef01cSRoman Divacky 
14616122f3e6SDimitry Andric     // Get the attribute list.
14626122f3e6SDimitry Andric     llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
14636122f3e6SDimitry Andric     llvm::AttrListPtr AttrList = CI->getAttributes();
14646122f3e6SDimitry Andric 
14656122f3e6SDimitry Andric     // Get any return attributes.
14666122f3e6SDimitry Andric     llvm::Attributes RAttrs = AttrList.getRetAttributes();
14676122f3e6SDimitry Andric 
14686122f3e6SDimitry Andric     // Add the return attributes.
14696122f3e6SDimitry Andric     if (RAttrs)
14706122f3e6SDimitry Andric       AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
14716122f3e6SDimitry Andric 
1472f22ef01cSRoman Divacky     // If the function was passed too few arguments, don't transform.  If extra
1473f22ef01cSRoman Divacky     // arguments were passed, we silently drop them.  If any of the types
1474f22ef01cSRoman Divacky     // mismatch, we don't transform.
1475f22ef01cSRoman Divacky     unsigned ArgNo = 0;
1476f22ef01cSRoman Divacky     bool DontTransform = false;
1477f22ef01cSRoman Divacky     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1478f22ef01cSRoman Divacky          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1479f22ef01cSRoman Divacky       if (CS.arg_size() == ArgNo ||
1480f22ef01cSRoman Divacky           CS.getArgument(ArgNo)->getType() != AI->getType()) {
1481f22ef01cSRoman Divacky         DontTransform = true;
1482f22ef01cSRoman Divacky         break;
1483f22ef01cSRoman Divacky       }
14846122f3e6SDimitry Andric 
14856122f3e6SDimitry Andric       // Add any parameter attributes.
14866122f3e6SDimitry Andric       if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
14876122f3e6SDimitry Andric         AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
1488f22ef01cSRoman Divacky     }
1489f22ef01cSRoman Divacky     if (DontTransform)
1490f22ef01cSRoman Divacky       continue;
1491f22ef01cSRoman Divacky 
14926122f3e6SDimitry Andric     if (llvm::Attributes FnAttrs =  AttrList.getFnAttributes())
14936122f3e6SDimitry Andric       AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
14946122f3e6SDimitry Andric 
1495f22ef01cSRoman Divacky     // Okay, we can transform this.  Create the new call instruction and copy
1496f22ef01cSRoman Divacky     // over the required information.
1497f22ef01cSRoman Divacky     ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
149817a519f9SDimitry Andric     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
1499f22ef01cSRoman Divacky     ArgList.clear();
1500f22ef01cSRoman Divacky     if (!NewCall->getType()->isVoidTy())
1501f22ef01cSRoman Divacky       NewCall->takeName(CI);
15026122f3e6SDimitry Andric     NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(),
15036122f3e6SDimitry Andric                                                   AttrVec.end()));
1504f22ef01cSRoman Divacky     NewCall->setCallingConv(CI->getCallingConv());
1505f22ef01cSRoman Divacky 
1506f22ef01cSRoman Divacky     // Finally, remove the old call, replacing any uses with the new one.
1507f22ef01cSRoman Divacky     if (!CI->use_empty())
1508f22ef01cSRoman Divacky       CI->replaceAllUsesWith(NewCall);
1509f22ef01cSRoman Divacky 
1510f22ef01cSRoman Divacky     // Copy debug location attached to CI.
1511f22ef01cSRoman Divacky     if (!CI->getDebugLoc().isUnknown())
1512f22ef01cSRoman Divacky       NewCall->setDebugLoc(CI->getDebugLoc());
1513f22ef01cSRoman Divacky     CI->eraseFromParent();
1514f22ef01cSRoman Divacky   }
1515f22ef01cSRoman Divacky }
1516f22ef01cSRoman Divacky 
1517f22ef01cSRoman Divacky 
1518f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1519f22ef01cSRoman Divacky   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
15203b0f4066SDimitry Andric 
15213b0f4066SDimitry Andric   // Compute the function info and LLVM type.
15223b0f4066SDimitry Andric   const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
15233b0f4066SDimitry Andric   bool variadic = false;
15243b0f4066SDimitry Andric   if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
15253b0f4066SDimitry Andric     variadic = fpt->isVariadic();
15266122f3e6SDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic);
15273b0f4066SDimitry Andric 
1528f22ef01cSRoman Divacky   // Get or create the prototype for the function.
1529f22ef01cSRoman Divacky   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1530f22ef01cSRoman Divacky 
1531f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
1532f22ef01cSRoman Divacky   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1533f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast);
1534f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
1535f22ef01cSRoman Divacky   }
1536f22ef01cSRoman Divacky 
1537f22ef01cSRoman Divacky 
1538f22ef01cSRoman Divacky   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1539f22ef01cSRoman Divacky     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1540f22ef01cSRoman Divacky 
1541f22ef01cSRoman Divacky     // If the types mismatch then we have to rewrite the definition.
1542f22ef01cSRoman Divacky     assert(OldFn->isDeclaration() &&
1543f22ef01cSRoman Divacky            "Shouldn't replace non-declaration");
1544f22ef01cSRoman Divacky 
1545f22ef01cSRoman Divacky     // F is the Function* for the one with the wrong type, we must make a new
1546f22ef01cSRoman Divacky     // Function* and update everything that used F (a declaration) with the new
1547f22ef01cSRoman Divacky     // Function* (which will be a definition).
1548f22ef01cSRoman Divacky     //
1549f22ef01cSRoman Divacky     // This happens if there is a prototype for a function
1550f22ef01cSRoman Divacky     // (e.g. "int f()") and then a definition of a different type
1551f22ef01cSRoman Divacky     // (e.g. "int f(int x)").  Move the old function aside so that it
1552f22ef01cSRoman Divacky     // doesn't interfere with GetAddrOfFunction.
15536122f3e6SDimitry Andric     OldFn->setName(StringRef());
1554f22ef01cSRoman Divacky     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1555f22ef01cSRoman Divacky 
1556f22ef01cSRoman Divacky     // If this is an implementation of a function without a prototype, try to
1557f22ef01cSRoman Divacky     // replace any existing uses of the function (which may be calls) with uses
1558f22ef01cSRoman Divacky     // of the new function
1559f22ef01cSRoman Divacky     if (D->getType()->isFunctionNoProtoType()) {
1560f22ef01cSRoman Divacky       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1561f22ef01cSRoman Divacky       OldFn->removeDeadConstantUsers();
1562f22ef01cSRoman Divacky     }
1563f22ef01cSRoman Divacky 
1564f22ef01cSRoman Divacky     // Replace uses of F with the Function we will endow with a body.
1565f22ef01cSRoman Divacky     if (!Entry->use_empty()) {
1566f22ef01cSRoman Divacky       llvm::Constant *NewPtrForOldDecl =
1567f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1568f22ef01cSRoman Divacky       Entry->replaceAllUsesWith(NewPtrForOldDecl);
1569f22ef01cSRoman Divacky     }
1570f22ef01cSRoman Divacky 
1571f22ef01cSRoman Divacky     // Ok, delete the old function now, which is dead.
1572f22ef01cSRoman Divacky     OldFn->eraseFromParent();
1573f22ef01cSRoman Divacky 
1574f22ef01cSRoman Divacky     Entry = NewFn;
1575f22ef01cSRoman Divacky   }
1576f22ef01cSRoman Divacky 
15772754fe60SDimitry Andric   // We need to set linkage and visibility on the function before
15782754fe60SDimitry Andric   // generating code for it because various parts of IR generation
15792754fe60SDimitry Andric   // want to propagate this information down (e.g. to local static
15802754fe60SDimitry Andric   // declarations).
1581f22ef01cSRoman Divacky   llvm::Function *Fn = cast<llvm::Function>(Entry);
1582f22ef01cSRoman Divacky   setFunctionLinkage(D, Fn);
1583f22ef01cSRoman Divacky 
15842754fe60SDimitry Andric   // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
15852754fe60SDimitry Andric   setGlobalVisibility(Fn, D);
15862754fe60SDimitry Andric 
15873b0f4066SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
1588f22ef01cSRoman Divacky 
1589f22ef01cSRoman Divacky   SetFunctionDefinitionAttributes(D, Fn);
1590f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
1591f22ef01cSRoman Divacky 
1592f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1593f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
1594f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1595f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
15966122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
15976122f3e6SDimitry Andric     AddGlobalAnnotations(D, Fn);
1598f22ef01cSRoman Divacky }
1599f22ef01cSRoman Divacky 
1600f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1601f22ef01cSRoman Divacky   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1602f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
1603f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
1604f22ef01cSRoman Divacky 
16056122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
1606f22ef01cSRoman Divacky 
1607f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
1608f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
1609f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1610f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
1611f22ef01cSRoman Divacky     return;
1612f22ef01cSRoman Divacky 
16136122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1614f22ef01cSRoman Divacky 
1615f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
1616f22ef01cSRoman Divacky   // if a deferred decl.
1617f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1618f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
16192754fe60SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
16202754fe60SDimitry Andric                                       /*ForVTable=*/false);
1621f22ef01cSRoman Divacky   else
1622f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1623f22ef01cSRoman Divacky                                     llvm::PointerType::getUnqual(DeclTy), 0);
1624f22ef01cSRoman Divacky 
1625f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
1626f22ef01cSRoman Divacky   llvm::GlobalValue *GA =
1627f22ef01cSRoman Divacky     new llvm::GlobalAlias(Aliasee->getType(),
1628f22ef01cSRoman Divacky                           llvm::Function::ExternalLinkage,
1629f22ef01cSRoman Divacky                           "", Aliasee, &getModule());
1630f22ef01cSRoman Divacky 
1631f22ef01cSRoman Divacky   if (Entry) {
1632f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
1633f22ef01cSRoman Divacky 
1634f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
1635f22ef01cSRoman Divacky     // by the alias, as in:
1636f22ef01cSRoman Divacky     //   extern int test6();
1637f22ef01cSRoman Divacky     //   ...
1638f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
1639f22ef01cSRoman Divacky     //
1640f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
1641f22ef01cSRoman Divacky     GA->takeName(Entry);
1642f22ef01cSRoman Divacky 
1643f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1644f22ef01cSRoman Divacky                                                           Entry->getType()));
1645f22ef01cSRoman Divacky     Entry->eraseFromParent();
1646f22ef01cSRoman Divacky   } else {
1647ffd1746dSEd Schouten     GA->setName(MangledName);
1648f22ef01cSRoman Divacky   }
1649f22ef01cSRoman Divacky 
1650f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
1651f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
1652f22ef01cSRoman Divacky   // variable/function.
1653f22ef01cSRoman Divacky   if (D->hasAttr<DLLExportAttr>()) {
1654f22ef01cSRoman Divacky     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1655f22ef01cSRoman Divacky       // The dllexport attribute is ignored for undefined symbols.
1656ffd1746dSEd Schouten       if (FD->hasBody())
1657f22ef01cSRoman Divacky         GA->setLinkage(llvm::Function::DLLExportLinkage);
1658f22ef01cSRoman Divacky     } else {
1659f22ef01cSRoman Divacky       GA->setLinkage(llvm::Function::DLLExportLinkage);
1660f22ef01cSRoman Divacky     }
1661f22ef01cSRoman Divacky   } else if (D->hasAttr<WeakAttr>() ||
1662f22ef01cSRoman Divacky              D->hasAttr<WeakRefAttr>() ||
16633b0f4066SDimitry Andric              D->isWeakImported()) {
1664f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
1665f22ef01cSRoman Divacky   }
1666f22ef01cSRoman Divacky 
1667f22ef01cSRoman Divacky   SetCommonAttributes(D, GA);
1668f22ef01cSRoman Divacky }
1669f22ef01cSRoman Divacky 
167017a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
16716122f3e6SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
167217a519f9SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
167317a519f9SDimitry Andric                                          Tys);
1674f22ef01cSRoman Divacky }
1675f22ef01cSRoman Divacky 
1676f22ef01cSRoman Divacky static llvm::StringMapEntry<llvm::Constant*> &
1677f22ef01cSRoman Divacky GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1678f22ef01cSRoman Divacky                          const StringLiteral *Literal,
1679f22ef01cSRoman Divacky                          bool TargetIsLSB,
1680f22ef01cSRoman Divacky                          bool &IsUTF16,
1681f22ef01cSRoman Divacky                          unsigned &StringLength) {
16826122f3e6SDimitry Andric   StringRef String = Literal->getString();
1683e580952dSDimitry Andric   unsigned NumBytes = String.size();
1684f22ef01cSRoman Divacky 
1685f22ef01cSRoman Divacky   // Check for simple case.
1686f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
1687f22ef01cSRoman Divacky     StringLength = NumBytes;
1688e580952dSDimitry Andric     return Map.GetOrCreateValue(String);
1689f22ef01cSRoman Divacky   }
1690f22ef01cSRoman Divacky 
1691f22ef01cSRoman Divacky   // Otherwise, convert the UTF8 literals into a byte string.
16926122f3e6SDimitry Andric   SmallVector<UTF16, 128> ToBuf(NumBytes);
1693e580952dSDimitry Andric   const UTF8 *FromPtr = (UTF8 *)String.data();
1694f22ef01cSRoman Divacky   UTF16 *ToPtr = &ToBuf[0];
1695f22ef01cSRoman Divacky 
16962754fe60SDimitry Andric   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1697f22ef01cSRoman Divacky                            &ToPtr, ToPtr + NumBytes,
1698f22ef01cSRoman Divacky                            strictConversion);
1699f22ef01cSRoman Divacky 
1700f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
1701f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
1702f22ef01cSRoman Divacky 
1703f22ef01cSRoman Divacky   // Render the UTF-16 string into a byte array and convert to the target byte
1704f22ef01cSRoman Divacky   // order.
1705f22ef01cSRoman Divacky   //
1706f22ef01cSRoman Divacky   // FIXME: This isn't something we should need to do here.
1707f22ef01cSRoman Divacky   llvm::SmallString<128> AsBytes;
1708f22ef01cSRoman Divacky   AsBytes.reserve(StringLength * 2);
1709f22ef01cSRoman Divacky   for (unsigned i = 0; i != StringLength; ++i) {
1710f22ef01cSRoman Divacky     unsigned short Val = ToBuf[i];
1711f22ef01cSRoman Divacky     if (TargetIsLSB) {
1712f22ef01cSRoman Divacky       AsBytes.push_back(Val & 0xFF);
1713f22ef01cSRoman Divacky       AsBytes.push_back(Val >> 8);
1714f22ef01cSRoman Divacky     } else {
1715f22ef01cSRoman Divacky       AsBytes.push_back(Val >> 8);
1716f22ef01cSRoman Divacky       AsBytes.push_back(Val & 0xFF);
1717f22ef01cSRoman Divacky     }
1718f22ef01cSRoman Divacky   }
1719f22ef01cSRoman Divacky   // Append one extra null character, the second is automatically added by our
1720f22ef01cSRoman Divacky   // caller.
1721f22ef01cSRoman Divacky   AsBytes.push_back(0);
1722f22ef01cSRoman Divacky 
1723f22ef01cSRoman Divacky   IsUTF16 = true;
17246122f3e6SDimitry Andric   return Map.GetOrCreateValue(StringRef(AsBytes.data(), AsBytes.size()));
1725f22ef01cSRoman Divacky }
1726f22ef01cSRoman Divacky 
1727bd5abe19SDimitry Andric static llvm::StringMapEntry<llvm::Constant*> &
1728bd5abe19SDimitry Andric GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1729bd5abe19SDimitry Andric 		       const StringLiteral *Literal,
1730bd5abe19SDimitry Andric 		       unsigned &StringLength)
1731bd5abe19SDimitry Andric {
17326122f3e6SDimitry Andric 	StringRef String = Literal->getString();
1733bd5abe19SDimitry Andric 	StringLength = String.size();
1734bd5abe19SDimitry Andric 	return Map.GetOrCreateValue(String);
1735bd5abe19SDimitry Andric }
1736bd5abe19SDimitry Andric 
1737f22ef01cSRoman Divacky llvm::Constant *
1738f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1739f22ef01cSRoman Divacky   unsigned StringLength = 0;
1740f22ef01cSRoman Divacky   bool isUTF16 = false;
1741f22ef01cSRoman Divacky   llvm::StringMapEntry<llvm::Constant*> &Entry =
1742f22ef01cSRoman Divacky     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1743f22ef01cSRoman Divacky                              getTargetData().isLittleEndian(),
1744f22ef01cSRoman Divacky                              isUTF16, StringLength);
1745f22ef01cSRoman Divacky 
1746f22ef01cSRoman Divacky   if (llvm::Constant *C = Entry.getValue())
1747f22ef01cSRoman Divacky     return C;
1748f22ef01cSRoman Divacky 
1749f22ef01cSRoman Divacky   llvm::Constant *Zero =
1750f22ef01cSRoman Divacky       llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1751f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
1752f22ef01cSRoman Divacky 
1753f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
1754f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
17556122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1756f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
1757f22ef01cSRoman Divacky     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1758f22ef01cSRoman Divacky                                            "__CFConstantStringClassReference");
1759f22ef01cSRoman Divacky     // Decay array -> ptr
1760f22ef01cSRoman Divacky     CFConstantStringClassRef =
17616122f3e6SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1762f22ef01cSRoman Divacky   }
1763f22ef01cSRoman Divacky 
1764f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
1765f22ef01cSRoman Divacky 
17666122f3e6SDimitry Andric   llvm::StructType *STy =
1767f22ef01cSRoman Divacky     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1768f22ef01cSRoman Divacky 
1769f22ef01cSRoman Divacky   std::vector<llvm::Constant*> Fields(4);
1770f22ef01cSRoman Divacky 
1771f22ef01cSRoman Divacky   // Class pointer.
1772f22ef01cSRoman Divacky   Fields[0] = CFConstantStringClassRef;
1773f22ef01cSRoman Divacky 
1774f22ef01cSRoman Divacky   // Flags.
17756122f3e6SDimitry Andric   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1776f22ef01cSRoman Divacky   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1777f22ef01cSRoman Divacky     llvm::ConstantInt::get(Ty, 0x07C8);
1778f22ef01cSRoman Divacky 
1779f22ef01cSRoman Divacky   // String pointer.
1780f22ef01cSRoman Divacky   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1781f22ef01cSRoman Divacky 
1782f22ef01cSRoman Divacky   llvm::GlobalValue::LinkageTypes Linkage;
1783f22ef01cSRoman Divacky   bool isConstant;
1784f22ef01cSRoman Divacky   if (isUTF16) {
1785f22ef01cSRoman Divacky     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1786f22ef01cSRoman Divacky     Linkage = llvm::GlobalValue::InternalLinkage;
1787f22ef01cSRoman Divacky     // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1788f22ef01cSRoman Divacky     // does make plain ascii ones writable.
1789f22ef01cSRoman Divacky     isConstant = true;
1790f22ef01cSRoman Divacky   } else {
17913b0f4066SDimitry Andric     // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
17923b0f4066SDimitry Andric     // when using private linkage. It is not clear if this is a bug in ld
17933b0f4066SDimitry Andric     // or a reasonable new restriction.
17943b0f4066SDimitry Andric     Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
1795f22ef01cSRoman Divacky     isConstant = !Features.WritableStrings;
1796f22ef01cSRoman Divacky   }
1797f22ef01cSRoman Divacky 
1798f22ef01cSRoman Divacky   llvm::GlobalVariable *GV =
1799f22ef01cSRoman Divacky     new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1800f22ef01cSRoman Divacky                              ".str");
18012754fe60SDimitry Andric   GV->setUnnamedAddr(true);
1802f22ef01cSRoman Divacky   if (isUTF16) {
1803f22ef01cSRoman Divacky     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1804f22ef01cSRoman Divacky     GV->setAlignment(Align.getQuantity());
18053b0f4066SDimitry Andric   } else {
18063b0f4066SDimitry Andric     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
18073b0f4066SDimitry Andric     GV->setAlignment(Align.getQuantity());
1808f22ef01cSRoman Divacky   }
18096122f3e6SDimitry Andric   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1810f22ef01cSRoman Divacky 
1811f22ef01cSRoman Divacky   // String length.
1812f22ef01cSRoman Divacky   Ty = getTypes().ConvertType(getContext().LongTy);
1813f22ef01cSRoman Divacky   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1814f22ef01cSRoman Divacky 
1815f22ef01cSRoman Divacky   // The struct.
1816f22ef01cSRoman Divacky   C = llvm::ConstantStruct::get(STy, Fields);
1817f22ef01cSRoman Divacky   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1818f22ef01cSRoman Divacky                                 llvm::GlobalVariable::PrivateLinkage, C,
1819f22ef01cSRoman Divacky                                 "_unnamed_cfstring_");
18206122f3e6SDimitry Andric   if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
1821f22ef01cSRoman Divacky     GV->setSection(Sect);
1822f22ef01cSRoman Divacky   Entry.setValue(GV);
1823f22ef01cSRoman Divacky 
1824f22ef01cSRoman Divacky   return GV;
1825f22ef01cSRoman Divacky }
1826f22ef01cSRoman Divacky 
18276122f3e6SDimitry Andric static RecordDecl *
18286122f3e6SDimitry Andric CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
18296122f3e6SDimitry Andric                  DeclContext *DC, IdentifierInfo *Id) {
18306122f3e6SDimitry Andric   SourceLocation Loc;
18316122f3e6SDimitry Andric   if (Ctx.getLangOptions().CPlusPlus)
18326122f3e6SDimitry Andric     return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
18336122f3e6SDimitry Andric   else
18346122f3e6SDimitry Andric     return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
18356122f3e6SDimitry Andric }
18366122f3e6SDimitry Andric 
1837f22ef01cSRoman Divacky llvm::Constant *
18382754fe60SDimitry Andric CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
1839f22ef01cSRoman Divacky   unsigned StringLength = 0;
1840f22ef01cSRoman Divacky   llvm::StringMapEntry<llvm::Constant*> &Entry =
1841bd5abe19SDimitry Andric     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
1842f22ef01cSRoman Divacky 
1843f22ef01cSRoman Divacky   if (llvm::Constant *C = Entry.getValue())
1844f22ef01cSRoman Divacky     return C;
1845f22ef01cSRoman Divacky 
1846f22ef01cSRoman Divacky   llvm::Constant *Zero =
1847f22ef01cSRoman Divacky   llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1848f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
1849f22ef01cSRoman Divacky 
1850f22ef01cSRoman Divacky   // If we don't already have it, get _NSConstantStringClassReference.
18512754fe60SDimitry Andric   if (!ConstantStringClassRef) {
18522754fe60SDimitry Andric     std::string StringClass(getLangOptions().ObjCConstantStringClass);
18536122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
18542754fe60SDimitry Andric     llvm::Constant *GV;
1855bd5abe19SDimitry Andric     if (Features.ObjCNonFragileABI) {
1856bd5abe19SDimitry Andric       std::string str =
1857bd5abe19SDimitry Andric         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
1858bd5abe19SDimitry Andric                             : "OBJC_CLASS_$_" + StringClass;
1859bd5abe19SDimitry Andric       GV = getObjCRuntime().GetClassGlobal(str);
1860bd5abe19SDimitry Andric       // Make sure the result is of the correct type.
18616122f3e6SDimitry Andric       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1862bd5abe19SDimitry Andric       ConstantStringClassRef =
1863bd5abe19SDimitry Andric         llvm::ConstantExpr::getBitCast(GV, PTy);
1864bd5abe19SDimitry Andric     } else {
1865bd5abe19SDimitry Andric       std::string str =
1866bd5abe19SDimitry Andric         StringClass.empty() ? "_NSConstantStringClassReference"
1867bd5abe19SDimitry Andric                             : "_" + StringClass + "ClassReference";
18686122f3e6SDimitry Andric       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
1869bd5abe19SDimitry Andric       GV = CreateRuntimeVariable(PTy, str);
1870f22ef01cSRoman Divacky       // Decay array -> ptr
18712754fe60SDimitry Andric       ConstantStringClassRef =
18726122f3e6SDimitry Andric         llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1873f22ef01cSRoman Divacky     }
1874bd5abe19SDimitry Andric   }
1875f22ef01cSRoman Divacky 
18766122f3e6SDimitry Andric   if (!NSConstantStringType) {
18776122f3e6SDimitry Andric     // Construct the type for a constant NSString.
18786122f3e6SDimitry Andric     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
18796122f3e6SDimitry Andric                                      Context.getTranslationUnitDecl(),
18806122f3e6SDimitry Andric                                    &Context.Idents.get("__builtin_NSString"));
18816122f3e6SDimitry Andric     D->startDefinition();
1882f22ef01cSRoman Divacky 
18836122f3e6SDimitry Andric     QualType FieldTypes[3];
18846122f3e6SDimitry Andric 
18856122f3e6SDimitry Andric     // const int *isa;
18866122f3e6SDimitry Andric     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
18876122f3e6SDimitry Andric     // const char *str;
18886122f3e6SDimitry Andric     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
18896122f3e6SDimitry Andric     // unsigned int length;
18906122f3e6SDimitry Andric     FieldTypes[2] = Context.UnsignedIntTy;
18916122f3e6SDimitry Andric 
18926122f3e6SDimitry Andric     // Create fields
18936122f3e6SDimitry Andric     for (unsigned i = 0; i < 3; ++i) {
18946122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context, D,
18956122f3e6SDimitry Andric                                            SourceLocation(),
18966122f3e6SDimitry Andric                                            SourceLocation(), 0,
18976122f3e6SDimitry Andric                                            FieldTypes[i], /*TInfo=*/0,
18986122f3e6SDimitry Andric                                            /*BitWidth=*/0,
18996122f3e6SDimitry Andric                                            /*Mutable=*/false,
19006122f3e6SDimitry Andric                                            /*HasInit=*/false);
19016122f3e6SDimitry Andric       Field->setAccess(AS_public);
19026122f3e6SDimitry Andric       D->addDecl(Field);
19036122f3e6SDimitry Andric     }
19046122f3e6SDimitry Andric 
19056122f3e6SDimitry Andric     D->completeDefinition();
19066122f3e6SDimitry Andric     QualType NSTy = Context.getTagDeclType(D);
19076122f3e6SDimitry Andric     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
19086122f3e6SDimitry Andric   }
1909f22ef01cSRoman Divacky 
1910f22ef01cSRoman Divacky   std::vector<llvm::Constant*> Fields(3);
1911f22ef01cSRoman Divacky 
1912f22ef01cSRoman Divacky   // Class pointer.
19132754fe60SDimitry Andric   Fields[0] = ConstantStringClassRef;
1914f22ef01cSRoman Divacky 
1915f22ef01cSRoman Divacky   // String pointer.
1916f22ef01cSRoman Divacky   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1917f22ef01cSRoman Divacky 
1918f22ef01cSRoman Divacky   llvm::GlobalValue::LinkageTypes Linkage;
1919f22ef01cSRoman Divacky   bool isConstant;
1920f22ef01cSRoman Divacky   Linkage = llvm::GlobalValue::PrivateLinkage;
1921f22ef01cSRoman Divacky   isConstant = !Features.WritableStrings;
1922f22ef01cSRoman Divacky 
1923f22ef01cSRoman Divacky   llvm::GlobalVariable *GV =
1924f22ef01cSRoman Divacky   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1925f22ef01cSRoman Divacky                            ".str");
19262754fe60SDimitry Andric   GV->setUnnamedAddr(true);
19273b0f4066SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
19283b0f4066SDimitry Andric   GV->setAlignment(Align.getQuantity());
19296122f3e6SDimitry Andric   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1930f22ef01cSRoman Divacky 
1931f22ef01cSRoman Divacky   // String length.
19326122f3e6SDimitry Andric   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1933f22ef01cSRoman Divacky   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1934f22ef01cSRoman Divacky 
1935f22ef01cSRoman Divacky   // The struct.
19366122f3e6SDimitry Andric   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
1937f22ef01cSRoman Divacky   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1938f22ef01cSRoman Divacky                                 llvm::GlobalVariable::PrivateLinkage, C,
1939f22ef01cSRoman Divacky                                 "_unnamed_nsstring_");
1940f22ef01cSRoman Divacky   // FIXME. Fix section.
1941f22ef01cSRoman Divacky   if (const char *Sect =
1942f22ef01cSRoman Divacky         Features.ObjCNonFragileABI
19436122f3e6SDimitry Andric           ? getContext().getTargetInfo().getNSStringNonFragileABISection()
19446122f3e6SDimitry Andric           : getContext().getTargetInfo().getNSStringSection())
1945f22ef01cSRoman Divacky     GV->setSection(Sect);
1946f22ef01cSRoman Divacky   Entry.setValue(GV);
1947f22ef01cSRoman Divacky 
1948f22ef01cSRoman Divacky   return GV;
1949f22ef01cSRoman Divacky }
1950f22ef01cSRoman Divacky 
19516122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
19526122f3e6SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
19536122f3e6SDimitry Andric     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
19546122f3e6SDimitry Andric                                      Context.getTranslationUnitDecl(),
19556122f3e6SDimitry Andric                       &Context.Idents.get("__objcFastEnumerationState"));
19566122f3e6SDimitry Andric     D->startDefinition();
19576122f3e6SDimitry Andric 
19586122f3e6SDimitry Andric     QualType FieldTypes[] = {
19596122f3e6SDimitry Andric       Context.UnsignedLongTy,
19606122f3e6SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
19616122f3e6SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
19626122f3e6SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
19636122f3e6SDimitry Andric                            llvm::APInt(32, 5), ArrayType::Normal, 0)
19646122f3e6SDimitry Andric     };
19656122f3e6SDimitry Andric 
19666122f3e6SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
19676122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
19686122f3e6SDimitry Andric                                            D,
19696122f3e6SDimitry Andric                                            SourceLocation(),
19706122f3e6SDimitry Andric                                            SourceLocation(), 0,
19716122f3e6SDimitry Andric                                            FieldTypes[i], /*TInfo=*/0,
19726122f3e6SDimitry Andric                                            /*BitWidth=*/0,
19736122f3e6SDimitry Andric                                            /*Mutable=*/false,
19746122f3e6SDimitry Andric                                            /*HasInit=*/false);
19756122f3e6SDimitry Andric       Field->setAccess(AS_public);
19766122f3e6SDimitry Andric       D->addDecl(Field);
19776122f3e6SDimitry Andric     }
19786122f3e6SDimitry Andric 
19796122f3e6SDimitry Andric     D->completeDefinition();
19806122f3e6SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
19816122f3e6SDimitry Andric   }
19826122f3e6SDimitry Andric 
19836122f3e6SDimitry Andric   return ObjCFastEnumerationStateType;
19846122f3e6SDimitry Andric }
19856122f3e6SDimitry Andric 
1986f22ef01cSRoman Divacky /// GetStringForStringLiteral - Return the appropriate bytes for a
1987f22ef01cSRoman Divacky /// string literal, properly padded to match the literal type.
1988f22ef01cSRoman Divacky std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
19892754fe60SDimitry Andric   const ASTContext &Context = getContext();
1990f22ef01cSRoman Divacky   const ConstantArrayType *CAT =
19912754fe60SDimitry Andric     Context.getAsConstantArrayType(E->getType());
1992f22ef01cSRoman Divacky   assert(CAT && "String isn't pointer or array!");
1993f22ef01cSRoman Divacky 
1994f22ef01cSRoman Divacky   // Resize the string to the right size.
1995f22ef01cSRoman Divacky   uint64_t RealLen = CAT->getSize().getZExtValue();
1996f22ef01cSRoman Divacky 
19976122f3e6SDimitry Andric   switch (E->getKind()) {
19986122f3e6SDimitry Andric   case StringLiteral::Ascii:
19996122f3e6SDimitry Andric   case StringLiteral::UTF8:
20006122f3e6SDimitry Andric     break;
20016122f3e6SDimitry Andric   case StringLiteral::Wide:
20026122f3e6SDimitry Andric     RealLen *= Context.getTargetInfo().getWCharWidth() / Context.getCharWidth();
20036122f3e6SDimitry Andric     break;
20046122f3e6SDimitry Andric   case StringLiteral::UTF16:
20056122f3e6SDimitry Andric     RealLen *= Context.getTargetInfo().getChar16Width() / Context.getCharWidth();
20066122f3e6SDimitry Andric     break;
20076122f3e6SDimitry Andric   case StringLiteral::UTF32:
20086122f3e6SDimitry Andric     RealLen *= Context.getTargetInfo().getChar32Width() / Context.getCharWidth();
20096122f3e6SDimitry Andric     break;
20106122f3e6SDimitry Andric   }
2011f22ef01cSRoman Divacky 
2012e580952dSDimitry Andric   std::string Str = E->getString().str();
2013f22ef01cSRoman Divacky   Str.resize(RealLen, '\0');
2014f22ef01cSRoman Divacky 
2015f22ef01cSRoman Divacky   return Str;
2016f22ef01cSRoman Divacky }
2017f22ef01cSRoman Divacky 
2018f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2019f22ef01cSRoman Divacky /// constant array for the given string literal.
2020f22ef01cSRoman Divacky llvm::Constant *
2021f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2022f22ef01cSRoman Divacky   // FIXME: This can be more efficient.
2023f22ef01cSRoman Divacky   // FIXME: We shouldn't need to bitcast the constant in the wide string case.
20246122f3e6SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(S->getType());
20256122f3e6SDimitry Andric   llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S),
20266122f3e6SDimitry Andric                                               /* GlobalName */ 0,
20276122f3e6SDimitry Andric                                               Align.getQuantity());
20286122f3e6SDimitry Andric   if (S->isWide() || S->isUTF16() || S->isUTF32()) {
2029f22ef01cSRoman Divacky     llvm::Type *DestTy =
2030f22ef01cSRoman Divacky         llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
2031f22ef01cSRoman Divacky     C = llvm::ConstantExpr::getBitCast(C, DestTy);
2032f22ef01cSRoman Divacky   }
2033f22ef01cSRoman Divacky   return C;
2034f22ef01cSRoman Divacky }
2035f22ef01cSRoman Divacky 
2036f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2037f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
2038f22ef01cSRoman Divacky llvm::Constant *
2039f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2040f22ef01cSRoman Divacky   std::string Str;
2041f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2042f22ef01cSRoman Divacky 
2043f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
2044f22ef01cSRoman Divacky }
2045f22ef01cSRoman Divacky 
2046f22ef01cSRoman Divacky 
2047f22ef01cSRoman Divacky /// GenerateWritableString -- Creates storage for a string literal.
20486122f3e6SDimitry Andric static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2049f22ef01cSRoman Divacky                                              bool constant,
2050f22ef01cSRoman Divacky                                              CodeGenModule &CGM,
20516122f3e6SDimitry Andric                                              const char *GlobalName,
20526122f3e6SDimitry Andric                                              unsigned Alignment) {
2053f22ef01cSRoman Divacky   // Create Constant for this string literal. Don't add a '\0'.
2054f22ef01cSRoman Divacky   llvm::Constant *C =
2055f22ef01cSRoman Divacky       llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
2056f22ef01cSRoman Divacky 
2057f22ef01cSRoman Divacky   // Create a global variable for this string
20582754fe60SDimitry Andric   llvm::GlobalVariable *GV =
20592754fe60SDimitry Andric     new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2060f22ef01cSRoman Divacky                              llvm::GlobalValue::PrivateLinkage,
2061f22ef01cSRoman Divacky                              C, GlobalName);
20626122f3e6SDimitry Andric   GV->setAlignment(Alignment);
20632754fe60SDimitry Andric   GV->setUnnamedAddr(true);
20642754fe60SDimitry Andric   return GV;
2065f22ef01cSRoman Divacky }
2066f22ef01cSRoman Divacky 
2067f22ef01cSRoman Divacky /// GetAddrOfConstantString - Returns a pointer to a character array
2068f22ef01cSRoman Divacky /// containing the literal. This contents are exactly that of the
2069f22ef01cSRoman Divacky /// given string, i.e. it will not be null terminated automatically;
2070f22ef01cSRoman Divacky /// see GetAddrOfConstantCString. Note that whether the result is
2071f22ef01cSRoman Divacky /// actually a pointer to an LLVM constant depends on
2072f22ef01cSRoman Divacky /// Feature.WriteableStrings.
2073f22ef01cSRoman Divacky ///
2074f22ef01cSRoman Divacky /// The result has pointer to array type.
20756122f3e6SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
20766122f3e6SDimitry Andric                                                        const char *GlobalName,
20776122f3e6SDimitry Andric                                                        unsigned Alignment) {
2078f22ef01cSRoman Divacky   bool IsConstant = !Features.WritableStrings;
2079f22ef01cSRoman Divacky 
2080f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
2081f22ef01cSRoman Divacky   if (!GlobalName)
2082f22ef01cSRoman Divacky     GlobalName = ".str";
2083f22ef01cSRoman Divacky 
2084f22ef01cSRoman Divacky   // Don't share any string literals if strings aren't constant.
2085f22ef01cSRoman Divacky   if (!IsConstant)
20866122f3e6SDimitry Andric     return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2087f22ef01cSRoman Divacky 
20886122f3e6SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
20893b0f4066SDimitry Andric     ConstantStringMap.GetOrCreateValue(Str);
2090f22ef01cSRoman Divacky 
20916122f3e6SDimitry Andric   if (llvm::GlobalVariable *GV = Entry.getValue()) {
20926122f3e6SDimitry Andric     if (Alignment > GV->getAlignment()) {
20936122f3e6SDimitry Andric       GV->setAlignment(Alignment);
20946122f3e6SDimitry Andric     }
20956122f3e6SDimitry Andric     return GV;
20966122f3e6SDimitry Andric   }
2097f22ef01cSRoman Divacky 
2098f22ef01cSRoman Divacky   // Create a global variable for this.
20996122f3e6SDimitry Andric   llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, Alignment);
21006122f3e6SDimitry Andric   Entry.setValue(GV);
21016122f3e6SDimitry Andric   return GV;
2102f22ef01cSRoman Divacky }
2103f22ef01cSRoman Divacky 
2104f22ef01cSRoman Divacky /// GetAddrOfConstantCString - Returns a pointer to a character
21053b0f4066SDimitry Andric /// array containing the literal and a terminating '\0'
2106f22ef01cSRoman Divacky /// character. The result has pointer to array type.
21073b0f4066SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
21086122f3e6SDimitry Andric                                                         const char *GlobalName,
21096122f3e6SDimitry Andric                                                         unsigned Alignment) {
21106122f3e6SDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
21116122f3e6SDimitry Andric   return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2112f22ef01cSRoman Divacky }
2113f22ef01cSRoman Divacky 
2114f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
2115f22ef01cSRoman Divacky /// properties for an implementation.
2116f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
2117f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
2118f22ef01cSRoman Divacky   for (ObjCImplementationDecl::propimpl_iterator
2119f22ef01cSRoman Divacky          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2120f22ef01cSRoman Divacky     ObjCPropertyImplDecl *PID = *i;
2121f22ef01cSRoman Divacky 
2122f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
2123f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2124f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
2125f22ef01cSRoman Divacky 
2126f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
2127f22ef01cSRoman Divacky       // been overridden. Note that ::isSynthesized is not the method
2128f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
2129f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
2130f22ef01cSRoman Divacky       // this implementation.
2131f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
2132f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
2133f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
2134f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
2135f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
2136f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
2137f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
2138f22ef01cSRoman Divacky     }
2139f22ef01cSRoman Divacky   }
2140f22ef01cSRoman Divacky }
2141f22ef01cSRoman Divacky 
21423b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
21436122f3e6SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
21446122f3e6SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
21453b0f4066SDimitry Andric        ivar; ivar = ivar->getNextIvar())
21463b0f4066SDimitry Andric     if (ivar->getType().isDestructedType())
21473b0f4066SDimitry Andric       return true;
21483b0f4066SDimitry Andric 
21493b0f4066SDimitry Andric   return false;
21503b0f4066SDimitry Andric }
21513b0f4066SDimitry Andric 
2152f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
2153f22ef01cSRoman Divacky /// for an implementation.
2154f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
21553b0f4066SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
21563b0f4066SDimitry Andric   if (needsDestructMethod(D)) {
2157f22ef01cSRoman Divacky     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2158f22ef01cSRoman Divacky     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
21593b0f4066SDimitry Andric     ObjCMethodDecl *DTORMethod =
21603b0f4066SDimitry Andric       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
21616122f3e6SDimitry Andric                              cxxSelector, getContext().VoidTy, 0, D,
21626122f3e6SDimitry Andric                              /*isInstance=*/true, /*isVariadic=*/false,
21636122f3e6SDimitry Andric                           /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
21646122f3e6SDimitry Andric                              /*isDefined=*/false, ObjCMethodDecl::Required);
2165f22ef01cSRoman Divacky     D->addInstanceMethod(DTORMethod);
2166f22ef01cSRoman Divacky     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
216717a519f9SDimitry Andric     D->setHasCXXStructors(true);
21683b0f4066SDimitry Andric   }
2169f22ef01cSRoman Divacky 
21703b0f4066SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
21713b0f4066SDimitry Andric   // a .cxx_construct.
21723b0f4066SDimitry Andric   if (D->getNumIvarInitializers() == 0)
21733b0f4066SDimitry Andric     return;
21743b0f4066SDimitry Andric 
21753b0f4066SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
21763b0f4066SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2177f22ef01cSRoman Divacky   // The constructor returns 'self'.
2178f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2179f22ef01cSRoman Divacky                                                 D->getLocation(),
21806122f3e6SDimitry Andric                                                 D->getLocation(),
21816122f3e6SDimitry Andric                                                 cxxSelector,
2182f22ef01cSRoman Divacky                                                 getContext().getObjCIdType(), 0,
21836122f3e6SDimitry Andric                                                 D, /*isInstance=*/true,
21846122f3e6SDimitry Andric                                                 /*isVariadic=*/false,
21856122f3e6SDimitry Andric                                                 /*isSynthesized=*/true,
21866122f3e6SDimitry Andric                                                 /*isImplicitlyDeclared=*/true,
21876122f3e6SDimitry Andric                                                 /*isDefined=*/false,
2188f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
2189f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
2190f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
219117a519f9SDimitry Andric   D->setHasCXXStructors(true);
2192f22ef01cSRoman Divacky }
2193f22ef01cSRoman Divacky 
2194f22ef01cSRoman Divacky /// EmitNamespace - Emit all declarations in a namespace.
2195f22ef01cSRoman Divacky void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2196f22ef01cSRoman Divacky   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2197f22ef01cSRoman Divacky        I != E; ++I)
2198f22ef01cSRoman Divacky     EmitTopLevelDecl(*I);
2199f22ef01cSRoman Divacky }
2200f22ef01cSRoman Divacky 
2201f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
2202f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2203f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2204f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2205f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
2206f22ef01cSRoman Divacky     return;
2207f22ef01cSRoman Divacky   }
2208f22ef01cSRoman Divacky 
2209f22ef01cSRoman Divacky   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2210f22ef01cSRoman Divacky        I != E; ++I)
2211f22ef01cSRoman Divacky     EmitTopLevelDecl(*I);
2212f22ef01cSRoman Divacky }
2213f22ef01cSRoman Divacky 
2214f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
2215f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2216f22ef01cSRoman Divacky   // If an error has occurred, stop code generation, but continue
2217f22ef01cSRoman Divacky   // parsing and semantic analysis (to ensure all warnings and errors
2218f22ef01cSRoman Divacky   // are emitted).
2219f22ef01cSRoman Divacky   if (Diags.hasErrorOccurred())
2220f22ef01cSRoman Divacky     return;
2221f22ef01cSRoman Divacky 
2222f22ef01cSRoman Divacky   // Ignore dependent declarations.
2223f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2224f22ef01cSRoman Divacky     return;
2225f22ef01cSRoman Divacky 
2226f22ef01cSRoman Divacky   switch (D->getKind()) {
2227f22ef01cSRoman Divacky   case Decl::CXXConversion:
2228f22ef01cSRoman Divacky   case Decl::CXXMethod:
2229f22ef01cSRoman Divacky   case Decl::Function:
2230f22ef01cSRoman Divacky     // Skip function templates
22313b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
22323b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
2233f22ef01cSRoman Divacky       return;
2234f22ef01cSRoman Divacky 
2235f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
2236f22ef01cSRoman Divacky     break;
2237f22ef01cSRoman Divacky 
2238f22ef01cSRoman Divacky   case Decl::Var:
2239f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
2240f22ef01cSRoman Divacky     break;
2241f22ef01cSRoman Divacky 
22423b0f4066SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
22433b0f4066SDimitry Andric   // ignored; only the actual variable requires IR gen support.
22443b0f4066SDimitry Andric   case Decl::IndirectField:
22453b0f4066SDimitry Andric     break;
22463b0f4066SDimitry Andric 
2247f22ef01cSRoman Divacky   // C++ Decls
2248f22ef01cSRoman Divacky   case Decl::Namespace:
2249f22ef01cSRoman Divacky     EmitNamespace(cast<NamespaceDecl>(D));
2250f22ef01cSRoman Divacky     break;
2251f22ef01cSRoman Divacky     // No code generation needed.
2252f22ef01cSRoman Divacky   case Decl::UsingShadow:
2253f22ef01cSRoman Divacky   case Decl::Using:
2254f22ef01cSRoman Divacky   case Decl::UsingDirective:
2255f22ef01cSRoman Divacky   case Decl::ClassTemplate:
2256f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
2257bd5abe19SDimitry Andric   case Decl::TypeAliasTemplate:
2258f22ef01cSRoman Divacky   case Decl::NamespaceAlias:
2259bd5abe19SDimitry Andric   case Decl::Block:
2260f22ef01cSRoman Divacky     break;
2261f22ef01cSRoman Divacky   case Decl::CXXConstructor:
2262f22ef01cSRoman Divacky     // Skip function templates
22633b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
22643b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
2265f22ef01cSRoman Divacky       return;
2266f22ef01cSRoman Divacky 
2267f22ef01cSRoman Divacky     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2268f22ef01cSRoman Divacky     break;
2269f22ef01cSRoman Divacky   case Decl::CXXDestructor:
22703b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
22713b0f4066SDimitry Andric       return;
2272f22ef01cSRoman Divacky     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2273f22ef01cSRoman Divacky     break;
2274f22ef01cSRoman Divacky 
2275f22ef01cSRoman Divacky   case Decl::StaticAssert:
2276f22ef01cSRoman Divacky     // Nothing to do.
2277f22ef01cSRoman Divacky     break;
2278f22ef01cSRoman Divacky 
2279f22ef01cSRoman Divacky   // Objective-C Decls
2280f22ef01cSRoman Divacky 
2281f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
2282f22ef01cSRoman Divacky   case Decl::ObjCClass:
2283f22ef01cSRoman Divacky   case Decl::ObjCForwardProtocol:
2284f22ef01cSRoman Divacky   case Decl::ObjCInterface:
2285f22ef01cSRoman Divacky     break;
2286f22ef01cSRoman Divacky 
2287e580952dSDimitry Andric   case Decl::ObjCCategory: {
2288e580952dSDimitry Andric     ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2289e580952dSDimitry Andric     if (CD->IsClassExtension() && CD->hasSynthBitfield())
2290e580952dSDimitry Andric       Context.ResetObjCLayout(CD->getClassInterface());
2291e580952dSDimitry Andric     break;
2292e580952dSDimitry Andric   }
2293e580952dSDimitry Andric 
2294f22ef01cSRoman Divacky   case Decl::ObjCProtocol:
22956122f3e6SDimitry Andric     ObjCRuntime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
2296f22ef01cSRoman Divacky     break;
2297f22ef01cSRoman Divacky 
2298f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
2299f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
2300f22ef01cSRoman Divacky     // can ignore them here.
23016122f3e6SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2302f22ef01cSRoman Divacky     break;
2303f22ef01cSRoman Divacky 
2304f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
2305f22ef01cSRoman Divacky     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2306e580952dSDimitry Andric     if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2307e580952dSDimitry Andric       Context.ResetObjCLayout(OMD->getClassInterface());
2308f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
2309f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
23106122f3e6SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
2311f22ef01cSRoman Divacky     break;
2312f22ef01cSRoman Divacky   }
2313f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
2314f22ef01cSRoman Divacky     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2315f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
2316f22ef01cSRoman Divacky     if (OMD->getBody())
2317f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
2318f22ef01cSRoman Divacky     break;
2319f22ef01cSRoman Divacky   }
2320f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
2321f22ef01cSRoman Divacky     // compatibility-alias is a directive and has no code gen.
2322f22ef01cSRoman Divacky     break;
2323f22ef01cSRoman Divacky 
2324f22ef01cSRoman Divacky   case Decl::LinkageSpec:
2325f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2326f22ef01cSRoman Divacky     break;
2327f22ef01cSRoman Divacky 
2328f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
2329f22ef01cSRoman Divacky     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
23306122f3e6SDimitry Andric     StringRef AsmString = AD->getAsmString()->getString();
2331f22ef01cSRoman Divacky 
2332f22ef01cSRoman Divacky     const std::string &S = getModule().getModuleInlineAsm();
2333f22ef01cSRoman Divacky     if (S.empty())
2334f22ef01cSRoman Divacky       getModule().setModuleInlineAsm(AsmString);
23356122f3e6SDimitry Andric     else if (*--S.end() == '\n')
23366122f3e6SDimitry Andric       getModule().setModuleInlineAsm(S + AsmString.str());
2337f22ef01cSRoman Divacky     else
2338f22ef01cSRoman Divacky       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2339f22ef01cSRoman Divacky     break;
2340f22ef01cSRoman Divacky   }
2341f22ef01cSRoman Divacky 
2342f22ef01cSRoman Divacky   default:
2343f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
2344f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2345f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
2346f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2347f22ef01cSRoman Divacky   }
2348f22ef01cSRoman Divacky }
2349ffd1746dSEd Schouten 
2350ffd1746dSEd Schouten /// Turns the given pointer into a constant.
2351ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2352ffd1746dSEd Schouten                                           const void *Ptr) {
2353ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
23546122f3e6SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2355ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
2356ffd1746dSEd Schouten }
2357ffd1746dSEd Schouten 
2358ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2359ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
2360ffd1746dSEd Schouten                                    GlobalDecl D,
2361ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
2362ffd1746dSEd Schouten   if (!GlobalMetadata)
2363ffd1746dSEd Schouten     GlobalMetadata =
2364ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2365ffd1746dSEd Schouten 
2366ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
2367ffd1746dSEd Schouten   llvm::Value *Ops[] = {
2368ffd1746dSEd Schouten     Addr,
2369ffd1746dSEd Schouten     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2370ffd1746dSEd Schouten   };
23713b0f4066SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2372ffd1746dSEd Schouten }
2373ffd1746dSEd Schouten 
2374ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
2375ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
2376ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
2377ffd1746dSEd Schouten ///
2378ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
2379ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
2380ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
2381ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
2382ffd1746dSEd Schouten   llvm::NamedMDNode *GlobalMetadata = 0;
2383ffd1746dSEd Schouten 
2384ffd1746dSEd Schouten   // StaticLocalDeclMap
23856122f3e6SDimitry Andric   for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2386ffd1746dSEd Schouten          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2387ffd1746dSEd Schouten        I != E; ++I) {
2388ffd1746dSEd Schouten     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2389ffd1746dSEd Schouten     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2390ffd1746dSEd Schouten   }
2391ffd1746dSEd Schouten }
2392ffd1746dSEd Schouten 
2393ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
2394ffd1746dSEd Schouten /// function.
2395ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
2396ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
2397ffd1746dSEd Schouten 
2398ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
2399ffd1746dSEd Schouten 
2400ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
2401ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2402ffd1746dSEd Schouten 
2403ffd1746dSEd Schouten   llvm::NamedMDNode *GlobalMetadata = 0;
2404ffd1746dSEd Schouten 
2405ffd1746dSEd Schouten   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2406ffd1746dSEd Schouten          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2407ffd1746dSEd Schouten     const Decl *D = I->first;
2408ffd1746dSEd Schouten     llvm::Value *Addr = I->second;
2409ffd1746dSEd Schouten 
2410ffd1746dSEd Schouten     if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2411ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
24123b0f4066SDimitry Andric       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2413ffd1746dSEd Schouten     } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2414ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2415ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2416ffd1746dSEd Schouten     }
2417ffd1746dSEd Schouten   }
2418ffd1746dSEd Schouten }
2419e580952dSDimitry Andric 
2420bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() {
2421bd5abe19SDimitry Andric   if (!getCodeGenOpts().CoverageFile.empty()) {
2422bd5abe19SDimitry Andric     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2423bd5abe19SDimitry Andric       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2424bd5abe19SDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
2425bd5abe19SDimitry Andric       llvm::MDString *CoverageFile =
2426bd5abe19SDimitry Andric           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
2427bd5abe19SDimitry Andric       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2428bd5abe19SDimitry Andric         llvm::MDNode *CU = CUNode->getOperand(i);
2429bd5abe19SDimitry Andric         llvm::Value *node[] = { CoverageFile, CU };
2430bd5abe19SDimitry Andric         llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2431bd5abe19SDimitry Andric         GCov->addOperand(N);
2432bd5abe19SDimitry Andric       }
2433bd5abe19SDimitry Andric     }
2434bd5abe19SDimitry Andric   }
2435bd5abe19SDimitry Andric }
2436