CodeGenModule.cpp 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886
  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::AttributeSet::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::AttributeSet::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. /// Replace the uses of a function that was declared with a non-proto type.
  1520. /// We want to silently drop extra arguments from call sites
  1521. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  1522. llvm::Function *newFn) {
  1523. // Fast path.
  1524. if (old->use_empty()) return;
  1525. llvm::Type *newRetTy = newFn->getReturnType();
  1526. SmallVector<llvm::Value*, 4> newArgs;
  1527. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  1528. ui != ue; ) {
  1529. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  1530. llvm::User *user = *use;
  1531. // Recognize and replace uses of bitcasts. Most calls to
  1532. // unprototyped functions will use bitcasts.
  1533. if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  1534. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  1535. replaceUsesOfNonProtoConstant(bitcast, newFn);
  1536. continue;
  1537. }
  1538. // Recognize calls to the function.
  1539. llvm::CallSite callSite(user);
  1540. if (!callSite) continue;
  1541. if (!callSite.isCallee(use)) continue;
  1542. // If the return types don't match exactly, then we can't
  1543. // transform this call unless it's dead.
  1544. if (callSite->getType() != newRetTy && !callSite->use_empty())
  1545. continue;
  1546. // Get the call site's attribute list.
  1547. llvm::SmallVector<llvm::AttributeWithIndex, 8> newAttrs;
  1548. llvm::AttributeSet oldAttrs = callSite.getAttributes();
  1549. // Collect any return attributes from the call.
  1550. llvm::Attributes returnAttrs = oldAttrs.getRetAttributes();
  1551. if (returnAttrs.hasAttributes())
  1552. newAttrs.push_back(llvm::AttributeWithIndex::get(
  1553. llvm::AttributeSet::ReturnIndex, returnAttrs));
  1554. // If the function was passed too few arguments, don't transform.
  1555. unsigned newNumArgs = newFn->arg_size();
  1556. if (callSite.arg_size() < newNumArgs) continue;
  1557. // If extra arguments were passed, we silently drop them.
  1558. // If any of the types mismatch, we don't transform.
  1559. unsigned argNo = 0;
  1560. bool dontTransform = false;
  1561. for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
  1562. ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
  1563. if (callSite.getArgument(argNo)->getType() != ai->getType()) {
  1564. dontTransform = true;
  1565. break;
  1566. }
  1567. // Add any parameter attributes.
  1568. llvm::Attributes pAttrs = oldAttrs.getParamAttributes(argNo + 1);
  1569. if (pAttrs.hasAttributes())
  1570. newAttrs.push_back(llvm::AttributeWithIndex::get(argNo + 1, pAttrs));
  1571. }
  1572. if (dontTransform)
  1573. continue;
  1574. llvm::Attributes fnAttrs = oldAttrs.getFnAttributes();
  1575. if (fnAttrs.hasAttributes())
  1576. newAttrs.push_back(llvm::
  1577. AttributeWithIndex::get(llvm::AttributeSet::FunctionIndex,
  1578. fnAttrs));
  1579. // Okay, we can transform this. Create the new call instruction and copy
  1580. // over the required information.
  1581. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  1582. llvm::CallSite newCall;
  1583. if (callSite.isCall()) {
  1584. newCall = llvm::CallInst::Create(newFn, newArgs, "",
  1585. callSite.getInstruction());
  1586. } else {
  1587. llvm::InvokeInst *oldInvoke =
  1588. cast<llvm::InvokeInst>(callSite.getInstruction());
  1589. newCall = llvm::InvokeInst::Create(newFn,
  1590. oldInvoke->getNormalDest(),
  1591. oldInvoke->getUnwindDest(),
  1592. newArgs, "",
  1593. callSite.getInstruction());
  1594. }
  1595. newArgs.clear(); // for the next iteration
  1596. if (!newCall->getType()->isVoidTy())
  1597. newCall->takeName(callSite.getInstruction());
  1598. newCall.setAttributes(
  1599. llvm::AttributeSet::get(newFn->getContext(), newAttrs));
  1600. newCall.setCallingConv(callSite.getCallingConv());
  1601. // Finally, remove the old call, replacing any uses with the new one.
  1602. if (!callSite->use_empty())
  1603. callSite->replaceAllUsesWith(newCall.getInstruction());
  1604. // Copy debug location attached to CI.
  1605. if (!callSite->getDebugLoc().isUnknown())
  1606. newCall->setDebugLoc(callSite->getDebugLoc());
  1607. callSite->eraseFromParent();
  1608. }
  1609. }
  1610. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  1611. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  1612. /// existing call uses of the old function in the module, this adjusts them to
  1613. /// call the new function directly.
  1614. ///
  1615. /// This is not just a cleanup: the always_inline pass requires direct calls to
  1616. /// functions to be able to inline them. If there is a bitcast in the way, it
  1617. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  1618. /// run at -O0.
  1619. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1620. llvm::Function *NewFn) {
  1621. // If we're redefining a global as a function, don't transform it.
  1622. if (!isa<llvm::Function>(Old)) return;
  1623. replaceUsesOfNonProtoConstant(Old, NewFn);
  1624. }
  1625. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  1626. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  1627. // If we have a definition, this might be a deferred decl. If the
  1628. // instantiation is explicit, make sure we emit it at the end.
  1629. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  1630. GetAddrOfGlobalVar(VD);
  1631. }
  1632. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
  1633. const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
  1634. // Compute the function info and LLVM type.
  1635. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1636. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  1637. // Get or create the prototype for the function.
  1638. llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
  1639. // Strip off a bitcast if we got one back.
  1640. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1641. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  1642. Entry = CE->getOperand(0);
  1643. }
  1644. if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
  1645. llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
  1646. // If the types mismatch then we have to rewrite the definition.
  1647. assert(OldFn->isDeclaration() &&
  1648. "Shouldn't replace non-declaration");
  1649. // F is the Function* for the one with the wrong type, we must make a new
  1650. // Function* and update everything that used F (a declaration) with the new
  1651. // Function* (which will be a definition).
  1652. //
  1653. // This happens if there is a prototype for a function
  1654. // (e.g. "int f()") and then a definition of a different type
  1655. // (e.g. "int f(int x)"). Move the old function aside so that it
  1656. // doesn't interfere with GetAddrOfFunction.
  1657. OldFn->setName(StringRef());
  1658. llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
  1659. // This might be an implementation of a function without a
  1660. // prototype, in which case, try to do special replacement of
  1661. // calls which match the new prototype. The really key thing here
  1662. // is that we also potentially drop arguments from the call site
  1663. // so as to make a direct call, which makes the inliner happier
  1664. // and suppresses a number of optimizer warnings (!) about
  1665. // dropping arguments.
  1666. if (!OldFn->use_empty()) {
  1667. ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
  1668. OldFn->removeDeadConstantUsers();
  1669. }
  1670. // Replace uses of F with the Function we will endow with a body.
  1671. if (!Entry->use_empty()) {
  1672. llvm::Constant *NewPtrForOldDecl =
  1673. llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
  1674. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1675. }
  1676. // Ok, delete the old function now, which is dead.
  1677. OldFn->eraseFromParent();
  1678. Entry = NewFn;
  1679. }
  1680. // We need to set linkage and visibility on the function before
  1681. // generating code for it because various parts of IR generation
  1682. // want to propagate this information down (e.g. to local static
  1683. // declarations).
  1684. llvm::Function *Fn = cast<llvm::Function>(Entry);
  1685. setFunctionLinkage(D, Fn);
  1686. // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
  1687. setGlobalVisibility(Fn, D);
  1688. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  1689. SetFunctionDefinitionAttributes(D, Fn);
  1690. SetLLVMFunctionAttributesForDefinition(D, Fn);
  1691. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  1692. AddGlobalCtor(Fn, CA->getPriority());
  1693. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  1694. AddGlobalDtor(Fn, DA->getPriority());
  1695. if (D->hasAttr<AnnotateAttr>())
  1696. AddGlobalAnnotations(D, Fn);
  1697. }
  1698. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  1699. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  1700. const AliasAttr *AA = D->getAttr<AliasAttr>();
  1701. assert(AA && "Not an alias?");
  1702. StringRef MangledName = getMangledName(GD);
  1703. // If there is a definition in the module, then it wins over the alias.
  1704. // This is dubious, but allow it to be safe. Just ignore the alias.
  1705. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1706. if (Entry && !Entry->isDeclaration())
  1707. return;
  1708. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  1709. // Create a reference to the named value. This ensures that it is emitted
  1710. // if a deferred decl.
  1711. llvm::Constant *Aliasee;
  1712. if (isa<llvm::FunctionType>(DeclTy))
  1713. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  1714. /*ForVTable=*/false);
  1715. else
  1716. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1717. llvm::PointerType::getUnqual(DeclTy), 0);
  1718. // Create the new alias itself, but don't set a name yet.
  1719. llvm::GlobalValue *GA =
  1720. new llvm::GlobalAlias(Aliasee->getType(),
  1721. llvm::Function::ExternalLinkage,
  1722. "", Aliasee, &getModule());
  1723. if (Entry) {
  1724. assert(Entry->isDeclaration());
  1725. // If there is a declaration in the module, then we had an extern followed
  1726. // by the alias, as in:
  1727. // extern int test6();
  1728. // ...
  1729. // int test6() __attribute__((alias("test7")));
  1730. //
  1731. // Remove it and replace uses of it with the alias.
  1732. GA->takeName(Entry);
  1733. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  1734. Entry->getType()));
  1735. Entry->eraseFromParent();
  1736. } else {
  1737. GA->setName(MangledName);
  1738. }
  1739. // Set attributes which are particular to an alias; this is a
  1740. // specialization of the attributes which may be set on a global
  1741. // variable/function.
  1742. if (D->hasAttr<DLLExportAttr>()) {
  1743. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1744. // The dllexport attribute is ignored for undefined symbols.
  1745. if (FD->hasBody())
  1746. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1747. } else {
  1748. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1749. }
  1750. } else if (D->hasAttr<WeakAttr>() ||
  1751. D->hasAttr<WeakRefAttr>() ||
  1752. D->isWeakImported()) {
  1753. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  1754. }
  1755. SetCommonAttributes(D, GA);
  1756. }
  1757. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  1758. ArrayRef<llvm::Type*> Tys) {
  1759. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  1760. Tys);
  1761. }
  1762. static llvm::StringMapEntry<llvm::Constant*> &
  1763. GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1764. const StringLiteral *Literal,
  1765. bool TargetIsLSB,
  1766. bool &IsUTF16,
  1767. unsigned &StringLength) {
  1768. StringRef String = Literal->getString();
  1769. unsigned NumBytes = String.size();
  1770. // Check for simple case.
  1771. if (!Literal->containsNonAsciiOrNull()) {
  1772. StringLength = NumBytes;
  1773. return Map.GetOrCreateValue(String);
  1774. }
  1775. // Otherwise, convert the UTF8 literals into a string of shorts.
  1776. IsUTF16 = true;
  1777. SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  1778. const UTF8 *FromPtr = (const UTF8 *)String.data();
  1779. UTF16 *ToPtr = &ToBuf[0];
  1780. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1781. &ToPtr, ToPtr + NumBytes,
  1782. strictConversion);
  1783. // ConvertUTF8toUTF16 returns the length in ToPtr.
  1784. StringLength = ToPtr - &ToBuf[0];
  1785. // Add an explicit null.
  1786. *ToPtr = 0;
  1787. return Map.
  1788. GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  1789. (StringLength + 1) * 2));
  1790. }
  1791. static llvm::StringMapEntry<llvm::Constant*> &
  1792. GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1793. const StringLiteral *Literal,
  1794. unsigned &StringLength) {
  1795. StringRef String = Literal->getString();
  1796. StringLength = String.size();
  1797. return Map.GetOrCreateValue(String);
  1798. }
  1799. llvm::Constant *
  1800. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  1801. unsigned StringLength = 0;
  1802. bool isUTF16 = false;
  1803. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1804. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  1805. getDataLayout().isLittleEndian(),
  1806. isUTF16, StringLength);
  1807. if (llvm::Constant *C = Entry.getValue())
  1808. return C;
  1809. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  1810. llvm::Constant *Zeros[] = { Zero, Zero };
  1811. // If we don't already have it, get __CFConstantStringClassReference.
  1812. if (!CFConstantStringClassRef) {
  1813. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1814. Ty = llvm::ArrayType::get(Ty, 0);
  1815. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  1816. "__CFConstantStringClassReference");
  1817. // Decay array -> ptr
  1818. CFConstantStringClassRef =
  1819. llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1820. }
  1821. QualType CFTy = getContext().getCFConstantStringType();
  1822. llvm::StructType *STy =
  1823. cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  1824. llvm::Constant *Fields[4];
  1825. // Class pointer.
  1826. Fields[0] = CFConstantStringClassRef;
  1827. // Flags.
  1828. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1829. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  1830. llvm::ConstantInt::get(Ty, 0x07C8);
  1831. // String pointer.
  1832. llvm::Constant *C = 0;
  1833. if (isUTF16) {
  1834. ArrayRef<uint16_t> Arr =
  1835. llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
  1836. Entry.getKey().size() / 2);
  1837. C = llvm::ConstantDataArray::get(VMContext, Arr);
  1838. } else {
  1839. C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  1840. }
  1841. llvm::GlobalValue::LinkageTypes Linkage;
  1842. if (isUTF16)
  1843. // FIXME: why do utf strings get "_" labels instead of "L" labels?
  1844. Linkage = llvm::GlobalValue::InternalLinkage;
  1845. else
  1846. // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
  1847. // when using private linkage. It is not clear if this is a bug in ld
  1848. // or a reasonable new restriction.
  1849. Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
  1850. // Note: -fwritable-strings doesn't make the backing store strings of
  1851. // CFStrings writable. (See <rdar://problem/10657500>)
  1852. llvm::GlobalVariable *GV =
  1853. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  1854. Linkage, C, ".str");
  1855. GV->setUnnamedAddr(true);
  1856. if (isUTF16) {
  1857. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  1858. GV->setAlignment(Align.getQuantity());
  1859. } else {
  1860. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  1861. GV->setAlignment(Align.getQuantity());
  1862. }
  1863. // String.
  1864. Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1865. if (isUTF16)
  1866. // Cast the UTF16 string to the correct type.
  1867. Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
  1868. // String length.
  1869. Ty = getTypes().ConvertType(getContext().LongTy);
  1870. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  1871. // The struct.
  1872. C = llvm::ConstantStruct::get(STy, Fields);
  1873. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1874. llvm::GlobalVariable::PrivateLinkage, C,
  1875. "_unnamed_cfstring_");
  1876. if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
  1877. GV->setSection(Sect);
  1878. Entry.setValue(GV);
  1879. return GV;
  1880. }
  1881. static RecordDecl *
  1882. CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
  1883. DeclContext *DC, IdentifierInfo *Id) {
  1884. SourceLocation Loc;
  1885. if (Ctx.getLangOpts().CPlusPlus)
  1886. return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1887. else
  1888. return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1889. }
  1890. llvm::Constant *
  1891. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  1892. unsigned StringLength = 0;
  1893. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1894. GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
  1895. if (llvm::Constant *C = Entry.getValue())
  1896. return C;
  1897. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  1898. llvm::Constant *Zeros[] = { Zero, Zero };
  1899. // If we don't already have it, get _NSConstantStringClassReference.
  1900. if (!ConstantStringClassRef) {
  1901. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  1902. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1903. llvm::Constant *GV;
  1904. if (LangOpts.ObjCRuntime.isNonFragile()) {
  1905. std::string str =
  1906. StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
  1907. : "OBJC_CLASS_$_" + StringClass;
  1908. GV = getObjCRuntime().GetClassGlobal(str);
  1909. // Make sure the result is of the correct type.
  1910. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1911. ConstantStringClassRef =
  1912. llvm::ConstantExpr::getBitCast(GV, PTy);
  1913. } else {
  1914. std::string str =
  1915. StringClass.empty() ? "_NSConstantStringClassReference"
  1916. : "_" + StringClass + "ClassReference";
  1917. llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
  1918. GV = CreateRuntimeVariable(PTy, str);
  1919. // Decay array -> ptr
  1920. ConstantStringClassRef =
  1921. llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1922. }
  1923. }
  1924. if (!NSConstantStringType) {
  1925. // Construct the type for a constant NSString.
  1926. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  1927. Context.getTranslationUnitDecl(),
  1928. &Context.Idents.get("__builtin_NSString"));
  1929. D->startDefinition();
  1930. QualType FieldTypes[3];
  1931. // const int *isa;
  1932. FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
  1933. // const char *str;
  1934. FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
  1935. // unsigned int length;
  1936. FieldTypes[2] = Context.UnsignedIntTy;
  1937. // Create fields
  1938. for (unsigned i = 0; i < 3; ++i) {
  1939. FieldDecl *Field = FieldDecl::Create(Context, D,
  1940. SourceLocation(),
  1941. SourceLocation(), 0,
  1942. FieldTypes[i], /*TInfo=*/0,
  1943. /*BitWidth=*/0,
  1944. /*Mutable=*/false,
  1945. ICIS_NoInit);
  1946. Field->setAccess(AS_public);
  1947. D->addDecl(Field);
  1948. }
  1949. D->completeDefinition();
  1950. QualType NSTy = Context.getTagDeclType(D);
  1951. NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  1952. }
  1953. llvm::Constant *Fields[3];
  1954. // Class pointer.
  1955. Fields[0] = ConstantStringClassRef;
  1956. // String pointer.
  1957. llvm::Constant *C =
  1958. llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  1959. llvm::GlobalValue::LinkageTypes Linkage;
  1960. bool isConstant;
  1961. Linkage = llvm::GlobalValue::PrivateLinkage;
  1962. isConstant = !LangOpts.WritableStrings;
  1963. llvm::GlobalVariable *GV =
  1964. new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
  1965. ".str");
  1966. GV->setUnnamedAddr(true);
  1967. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  1968. GV->setAlignment(Align.getQuantity());
  1969. Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1970. // String length.
  1971. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1972. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  1973. // The struct.
  1974. C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
  1975. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1976. llvm::GlobalVariable::PrivateLinkage, C,
  1977. "_unnamed_nsstring_");
  1978. // FIXME. Fix section.
  1979. if (const char *Sect =
  1980. LangOpts.ObjCRuntime.isNonFragile()
  1981. ? getContext().getTargetInfo().getNSStringNonFragileABISection()
  1982. : getContext().getTargetInfo().getNSStringSection())
  1983. GV->setSection(Sect);
  1984. Entry.setValue(GV);
  1985. return GV;
  1986. }
  1987. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  1988. if (ObjCFastEnumerationStateType.isNull()) {
  1989. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  1990. Context.getTranslationUnitDecl(),
  1991. &Context.Idents.get("__objcFastEnumerationState"));
  1992. D->startDefinition();
  1993. QualType FieldTypes[] = {
  1994. Context.UnsignedLongTy,
  1995. Context.getPointerType(Context.getObjCIdType()),
  1996. Context.getPointerType(Context.UnsignedLongTy),
  1997. Context.getConstantArrayType(Context.UnsignedLongTy,
  1998. llvm::APInt(32, 5), ArrayType::Normal, 0)
  1999. };
  2000. for (size_t i = 0; i < 4; ++i) {
  2001. FieldDecl *Field = FieldDecl::Create(Context,
  2002. D,
  2003. SourceLocation(),
  2004. SourceLocation(), 0,
  2005. FieldTypes[i], /*TInfo=*/0,
  2006. /*BitWidth=*/0,
  2007. /*Mutable=*/false,
  2008. ICIS_NoInit);
  2009. Field->setAccess(AS_public);
  2010. D->addDecl(Field);
  2011. }
  2012. D->completeDefinition();
  2013. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  2014. }
  2015. return ObjCFastEnumerationStateType;
  2016. }
  2017. llvm::Constant *
  2018. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  2019. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  2020. // Don't emit it as the address of the string, emit the string data itself
  2021. // as an inline array.
  2022. if (E->getCharByteWidth() == 1) {
  2023. SmallString<64> Str(E->getString());
  2024. // Resize the string to the right size, which is indicated by its type.
  2025. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  2026. Str.resize(CAT->getSize().getZExtValue());
  2027. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  2028. }
  2029. llvm::ArrayType *AType =
  2030. cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  2031. llvm::Type *ElemTy = AType->getElementType();
  2032. unsigned NumElements = AType->getNumElements();
  2033. // Wide strings have either 2-byte or 4-byte elements.
  2034. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  2035. SmallVector<uint16_t, 32> Elements;
  2036. Elements.reserve(NumElements);
  2037. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2038. Elements.push_back(E->getCodeUnit(i));
  2039. Elements.resize(NumElements);
  2040. return llvm::ConstantDataArray::get(VMContext, Elements);
  2041. }
  2042. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  2043. SmallVector<uint32_t, 32> Elements;
  2044. Elements.reserve(NumElements);
  2045. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2046. Elements.push_back(E->getCodeUnit(i));
  2047. Elements.resize(NumElements);
  2048. return llvm::ConstantDataArray::get(VMContext, Elements);
  2049. }
  2050. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  2051. /// constant array for the given string literal.
  2052. llvm::Constant *
  2053. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
  2054. CharUnits Align = getContext().getTypeAlignInChars(S->getType());
  2055. if (S->isAscii() || S->isUTF8()) {
  2056. SmallString<64> Str(S->getString());
  2057. // Resize the string to the right size, which is indicated by its type.
  2058. const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
  2059. Str.resize(CAT->getSize().getZExtValue());
  2060. return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
  2061. }
  2062. // FIXME: the following does not memoize wide strings.
  2063. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  2064. llvm::GlobalVariable *GV =
  2065. new llvm::GlobalVariable(getModule(),C->getType(),
  2066. !LangOpts.WritableStrings,
  2067. llvm::GlobalValue::PrivateLinkage,
  2068. C,".str");
  2069. GV->setAlignment(Align.getQuantity());
  2070. GV->setUnnamedAddr(true);
  2071. return GV;
  2072. }
  2073. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  2074. /// array for the given ObjCEncodeExpr node.
  2075. llvm::Constant *
  2076. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  2077. std::string Str;
  2078. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  2079. return GetAddrOfConstantCString(Str);
  2080. }
  2081. /// GenerateWritableString -- Creates storage for a string literal.
  2082. static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
  2083. bool constant,
  2084. CodeGenModule &CGM,
  2085. const char *GlobalName,
  2086. unsigned Alignment) {
  2087. // Create Constant for this string literal. Don't add a '\0'.
  2088. llvm::Constant *C =
  2089. llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
  2090. // Create a global variable for this string
  2091. llvm::GlobalVariable *GV =
  2092. new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
  2093. llvm::GlobalValue::PrivateLinkage,
  2094. C, GlobalName);
  2095. GV->setAlignment(Alignment);
  2096. GV->setUnnamedAddr(true);
  2097. return GV;
  2098. }
  2099. /// GetAddrOfConstantString - Returns a pointer to a character array
  2100. /// containing the literal. This contents are exactly that of the
  2101. /// given string, i.e. it will not be null terminated automatically;
  2102. /// see GetAddrOfConstantCString. Note that whether the result is
  2103. /// actually a pointer to an LLVM constant depends on
  2104. /// Feature.WriteableStrings.
  2105. ///
  2106. /// The result has pointer to array type.
  2107. llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
  2108. const char *GlobalName,
  2109. unsigned Alignment) {
  2110. // Get the default prefix if a name wasn't specified.
  2111. if (!GlobalName)
  2112. GlobalName = ".str";
  2113. // Don't share any string literals if strings aren't constant.
  2114. if (LangOpts.WritableStrings)
  2115. return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
  2116. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2117. ConstantStringMap.GetOrCreateValue(Str);
  2118. if (llvm::GlobalVariable *GV = Entry.getValue()) {
  2119. if (Alignment > GV->getAlignment()) {
  2120. GV->setAlignment(Alignment);
  2121. }
  2122. return GV;
  2123. }
  2124. // Create a global variable for this.
  2125. llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
  2126. Alignment);
  2127. Entry.setValue(GV);
  2128. return GV;
  2129. }
  2130. /// GetAddrOfConstantCString - Returns a pointer to a character
  2131. /// array containing the literal and a terminating '\0'
  2132. /// character. The result has pointer to array type.
  2133. llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
  2134. const char *GlobalName,
  2135. unsigned Alignment) {
  2136. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  2137. return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
  2138. }
  2139. /// EmitObjCPropertyImplementations - Emit information for synthesized
  2140. /// properties for an implementation.
  2141. void CodeGenModule::EmitObjCPropertyImplementations(const
  2142. ObjCImplementationDecl *D) {
  2143. for (ObjCImplementationDecl::propimpl_iterator
  2144. i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
  2145. ObjCPropertyImplDecl *PID = *i;
  2146. // Dynamic is just for type-checking.
  2147. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  2148. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2149. // Determine which methods need to be implemented, some may have
  2150. // been overridden. Note that ::isPropertyAccessor is not the method
  2151. // we want, that just indicates if the decl came from a
  2152. // property. What we want to know is if the method is defined in
  2153. // this implementation.
  2154. if (!D->getInstanceMethod(PD->getGetterName()))
  2155. CodeGenFunction(*this).GenerateObjCGetter(
  2156. const_cast<ObjCImplementationDecl *>(D), PID);
  2157. if (!PD->isReadOnly() &&
  2158. !D->getInstanceMethod(PD->getSetterName()))
  2159. CodeGenFunction(*this).GenerateObjCSetter(
  2160. const_cast<ObjCImplementationDecl *>(D), PID);
  2161. }
  2162. }
  2163. }
  2164. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  2165. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  2166. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  2167. ivar; ivar = ivar->getNextIvar())
  2168. if (ivar->getType().isDestructedType())
  2169. return true;
  2170. return false;
  2171. }
  2172. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  2173. /// for an implementation.
  2174. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  2175. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  2176. if (needsDestructMethod(D)) {
  2177. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  2178. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2179. ObjCMethodDecl *DTORMethod =
  2180. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  2181. cxxSelector, getContext().VoidTy, 0, D,
  2182. /*isInstance=*/true, /*isVariadic=*/false,
  2183. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  2184. /*isDefined=*/false, ObjCMethodDecl::Required);
  2185. D->addInstanceMethod(DTORMethod);
  2186. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  2187. D->setHasDestructors(true);
  2188. }
  2189. // If the implementation doesn't have any ivar initializers, we don't need
  2190. // a .cxx_construct.
  2191. if (D->getNumIvarInitializers() == 0)
  2192. return;
  2193. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  2194. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2195. // The constructor returns 'self'.
  2196. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  2197. D->getLocation(),
  2198. D->getLocation(),
  2199. cxxSelector,
  2200. getContext().getObjCIdType(), 0,
  2201. D, /*isInstance=*/true,
  2202. /*isVariadic=*/false,
  2203. /*isPropertyAccessor=*/true,
  2204. /*isImplicitlyDeclared=*/true,
  2205. /*isDefined=*/false,
  2206. ObjCMethodDecl::Required);
  2207. D->addInstanceMethod(CTORMethod);
  2208. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  2209. D->setHasNonZeroConstructors(true);
  2210. }
  2211. /// EmitNamespace - Emit all declarations in a namespace.
  2212. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  2213. for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
  2214. I != E; ++I)
  2215. EmitTopLevelDecl(*I);
  2216. }
  2217. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  2218. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  2219. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  2220. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  2221. ErrorUnsupported(LSD, "linkage spec");
  2222. return;
  2223. }
  2224. for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
  2225. I != E; ++I) {
  2226. // Meta-data for ObjC class includes references to implemented methods.
  2227. // Generate class's method definitions first.
  2228. if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
  2229. for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
  2230. MEnd = OID->meth_end();
  2231. M != MEnd; ++M)
  2232. EmitTopLevelDecl(*M);
  2233. }
  2234. EmitTopLevelDecl(*I);
  2235. }
  2236. }
  2237. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  2238. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  2239. // If an error has occurred, stop code generation, but continue
  2240. // parsing and semantic analysis (to ensure all warnings and errors
  2241. // are emitted).
  2242. if (Diags.hasErrorOccurred())
  2243. return;
  2244. // Ignore dependent declarations.
  2245. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  2246. return;
  2247. switch (D->getKind()) {
  2248. case Decl::CXXConversion:
  2249. case Decl::CXXMethod:
  2250. case Decl::Function:
  2251. // Skip function templates
  2252. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2253. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2254. return;
  2255. EmitGlobal(cast<FunctionDecl>(D));
  2256. break;
  2257. case Decl::Var:
  2258. EmitGlobal(cast<VarDecl>(D));
  2259. break;
  2260. // Indirect fields from global anonymous structs and unions can be
  2261. // ignored; only the actual variable requires IR gen support.
  2262. case Decl::IndirectField:
  2263. break;
  2264. // C++ Decls
  2265. case Decl::Namespace:
  2266. EmitNamespace(cast<NamespaceDecl>(D));
  2267. break;
  2268. // No code generation needed.
  2269. case Decl::UsingShadow:
  2270. case Decl::Using:
  2271. case Decl::UsingDirective:
  2272. case Decl::ClassTemplate:
  2273. case Decl::FunctionTemplate:
  2274. case Decl::TypeAliasTemplate:
  2275. case Decl::NamespaceAlias:
  2276. case Decl::Block:
  2277. case Decl::Import:
  2278. break;
  2279. case Decl::CXXConstructor:
  2280. // Skip function templates
  2281. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2282. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2283. return;
  2284. EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  2285. break;
  2286. case Decl::CXXDestructor:
  2287. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  2288. return;
  2289. EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  2290. break;
  2291. case Decl::StaticAssert:
  2292. // Nothing to do.
  2293. break;
  2294. // Objective-C Decls
  2295. // Forward declarations, no (immediate) code generation.
  2296. case Decl::ObjCInterface:
  2297. case Decl::ObjCCategory:
  2298. break;
  2299. case Decl::ObjCProtocol: {
  2300. ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
  2301. if (Proto->isThisDeclarationADefinition())
  2302. ObjCRuntime->GenerateProtocol(Proto);
  2303. break;
  2304. }
  2305. case Decl::ObjCCategoryImpl:
  2306. // Categories have properties but don't support synthesize so we
  2307. // can ignore them here.
  2308. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  2309. break;
  2310. case Decl::ObjCImplementation: {
  2311. ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
  2312. EmitObjCPropertyImplementations(OMD);
  2313. EmitObjCIvarInitializations(OMD);
  2314. ObjCRuntime->GenerateClass(OMD);
  2315. // Emit global variable debug information.
  2316. if (CGDebugInfo *DI = getModuleDebugInfo())
  2317. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  2318. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  2319. OMD->getClassInterface()), OMD->getLocation());
  2320. break;
  2321. }
  2322. case Decl::ObjCMethod: {
  2323. ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
  2324. // If this is not a prototype, emit the body.
  2325. if (OMD->getBody())
  2326. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  2327. break;
  2328. }
  2329. case Decl::ObjCCompatibleAlias:
  2330. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  2331. break;
  2332. case Decl::LinkageSpec:
  2333. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  2334. break;
  2335. case Decl::FileScopeAsm: {
  2336. FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
  2337. StringRef AsmString = AD->getAsmString()->getString();
  2338. const std::string &S = getModule().getModuleInlineAsm();
  2339. if (S.empty())
  2340. getModule().setModuleInlineAsm(AsmString);
  2341. else if (S.end()[-1] == '\n')
  2342. getModule().setModuleInlineAsm(S + AsmString.str());
  2343. else
  2344. getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
  2345. break;
  2346. }
  2347. default:
  2348. // Make sure we handled everything we should, every other kind is a
  2349. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  2350. // function. Need to recode Decl::Kind to do that easily.
  2351. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  2352. }
  2353. }
  2354. /// Turns the given pointer into a constant.
  2355. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  2356. const void *Ptr) {
  2357. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  2358. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  2359. return llvm::ConstantInt::get(i64, PtrInt);
  2360. }
  2361. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  2362. llvm::NamedMDNode *&GlobalMetadata,
  2363. GlobalDecl D,
  2364. llvm::GlobalValue *Addr) {
  2365. if (!GlobalMetadata)
  2366. GlobalMetadata =
  2367. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  2368. // TODO: should we report variant information for ctors/dtors?
  2369. llvm::Value *Ops[] = {
  2370. Addr,
  2371. GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
  2372. };
  2373. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  2374. }
  2375. /// Emits metadata nodes associating all the global values in the
  2376. /// current module with the Decls they came from. This is useful for
  2377. /// projects using IR gen as a subroutine.
  2378. ///
  2379. /// Since there's currently no way to associate an MDNode directly
  2380. /// with an llvm::GlobalValue, we create a global named metadata
  2381. /// with the name 'clang.global.decl.ptrs'.
  2382. void CodeGenModule::EmitDeclMetadata() {
  2383. llvm::NamedMDNode *GlobalMetadata = 0;
  2384. // StaticLocalDeclMap
  2385. for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
  2386. I = MangledDeclNames.begin(), E = MangledDeclNames.end();
  2387. I != E; ++I) {
  2388. llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
  2389. EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
  2390. }
  2391. }
  2392. /// Emits metadata nodes for all the local variables in the current
  2393. /// function.
  2394. void CodeGenFunction::EmitDeclMetadata() {
  2395. if (LocalDeclMap.empty()) return;
  2396. llvm::LLVMContext &Context = getLLVMContext();
  2397. // Find the unique metadata ID for this name.
  2398. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  2399. llvm::NamedMDNode *GlobalMetadata = 0;
  2400. for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
  2401. I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
  2402. const Decl *D = I->first;
  2403. llvm::Value *Addr = I->second;
  2404. if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  2405. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  2406. Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
  2407. } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  2408. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  2409. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  2410. }
  2411. }
  2412. }
  2413. void CodeGenModule::EmitCoverageFile() {
  2414. if (!getCodeGenOpts().CoverageFile.empty()) {
  2415. if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
  2416. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  2417. llvm::LLVMContext &Ctx = TheModule.getContext();
  2418. llvm::MDString *CoverageFile =
  2419. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
  2420. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  2421. llvm::MDNode *CU = CUNode->getOperand(i);
  2422. llvm::Value *node[] = { CoverageFile, CU };
  2423. llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
  2424. GCov->addOperand(N);
  2425. }
  2426. }
  2427. }
  2428. }
  2429. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
  2430. QualType GuidType) {
  2431. // Sema has checked that all uuid strings are of the form
  2432. // "12345678-1234-1234-1234-1234567890ab".
  2433. assert(Uuid.size() == 36);
  2434. const char *Uuidstr = Uuid.data();
  2435. for (int i = 0; i < 36; ++i) {
  2436. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
  2437. else assert(isxdigit(Uuidstr[i]));
  2438. }
  2439. llvm::APInt Field0(32, StringRef(Uuidstr , 8), 16);
  2440. llvm::APInt Field1(16, StringRef(Uuidstr + 9, 4), 16);
  2441. llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
  2442. static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  2443. APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
  2444. InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
  2445. InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
  2446. InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
  2447. APValue& Arr = InitStruct.getStructField(3);
  2448. Arr = APValue(APValue::UninitArray(), 8, 8);
  2449. for (int t = 0; t < 8; ++t)
  2450. Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
  2451. llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
  2452. return EmitConstantValue(InitStruct, GuidType);
  2453. }