CodeGenModule.cpp 122 KB

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