CodeGenModule.cpp 85 KB

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