CodeGenModule.cpp 79 KB

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