CodeGenModule.cpp 114 KB

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