CodeGenModule.cpp 107 KB

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