CodeGenModule.cpp 97 KB

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