CodeGenModule.cpp 88 KB

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