CodeGenModule.cpp 105 KB

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