CodeGenModule.cpp 115 KB

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