CodeGenModule.cpp 116 KB

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