CodeGenModule.cpp 116 KB

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