CodeGenModule.cpp 92 KB

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