CodeGenModule.cpp 83 KB

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