CodeGenModule.cpp 82 KB

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