CodeGenModule.cpp 101 KB

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