CodeGenModule.cpp 92 KB

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