CodeGenModule.cpp 89 KB

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