CodeGenModule.cpp 117 KB

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