CodeGenModule.cpp 161 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277
  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 "CGBlocks.h"
  15. #include "CGCUDARuntime.h"
  16. #include "CGCXXABI.h"
  17. #include "CGCall.h"
  18. #include "CGDebugInfo.h"
  19. #include "CGObjCRuntime.h"
  20. #include "CGOpenCLRuntime.h"
  21. #include "CGOpenMPRuntime.h"
  22. #include "CGOpenMPRuntimeNVPTX.h"
  23. #include "CodeGenFunction.h"
  24. #include "CodeGenPGO.h"
  25. #include "CodeGenTBAA.h"
  26. #include "CoverageMappingGen.h"
  27. #include "TargetInfo.h"
  28. #include "clang/AST/ASTContext.h"
  29. #include "clang/AST/CharUnits.h"
  30. #include "clang/AST/DeclCXX.h"
  31. #include "clang/AST/DeclObjC.h"
  32. #include "clang/AST/DeclTemplate.h"
  33. #include "clang/AST/Mangle.h"
  34. #include "clang/AST/RecordLayout.h"
  35. #include "clang/AST/RecursiveASTVisitor.h"
  36. #include "clang/Basic/Builtins.h"
  37. #include "clang/Basic/CharInfo.h"
  38. #include "clang/Basic/Diagnostic.h"
  39. #include "clang/Basic/Module.h"
  40. #include "clang/Basic/SourceManager.h"
  41. #include "clang/Basic/TargetInfo.h"
  42. #include "clang/Basic/Version.h"
  43. #include "clang/Frontend/CodeGenOptions.h"
  44. #include "clang/Sema/SemaDiagnostic.h"
  45. #include "llvm/ADT/APSInt.h"
  46. #include "llvm/ADT/Triple.h"
  47. #include "llvm/IR/CallSite.h"
  48. #include "llvm/IR/CallingConv.h"
  49. #include "llvm/IR/DataLayout.h"
  50. #include "llvm/IR/Intrinsics.h"
  51. #include "llvm/IR/LLVMContext.h"
  52. #include "llvm/IR/Module.h"
  53. #include "llvm/ProfileData/InstrProfReader.h"
  54. #include "llvm/Support/ConvertUTF.h"
  55. #include "llvm/Support/ErrorHandling.h"
  56. #include "llvm/Support/MD5.h"
  57. using namespace clang;
  58. using namespace CodeGen;
  59. static const char AnnotationSection[] = "llvm.metadata";
  60. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  61. switch (CGM.getTarget().getCXXABI().getKind()) {
  62. case TargetCXXABI::GenericAArch64:
  63. case TargetCXXABI::GenericARM:
  64. case TargetCXXABI::iOS:
  65. case TargetCXXABI::iOS64:
  66. case TargetCXXABI::WatchOS:
  67. case TargetCXXABI::GenericMIPS:
  68. case TargetCXXABI::GenericItanium:
  69. case TargetCXXABI::WebAssembly:
  70. return CreateItaniumCXXABI(CGM);
  71. case TargetCXXABI::Microsoft:
  72. return CreateMicrosoftCXXABI(CGM);
  73. }
  74. llvm_unreachable("invalid C++ ABI kind");
  75. }
  76. CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
  77. const PreprocessorOptions &PPO,
  78. const CodeGenOptions &CGO, llvm::Module &M,
  79. DiagnosticsEngine &diags,
  80. CoverageSourceInfo *CoverageInfo)
  81. : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
  82. PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
  83. Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
  84. VMContext(M.getContext()), Types(*this), VTables(*this),
  85. SanitizerMD(new SanitizerMetadata(*this)) {
  86. // Initialize the type cache.
  87. llvm::LLVMContext &LLVMContext = M.getContext();
  88. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  89. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  90. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  91. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  92. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  93. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  94. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  95. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  96. PointerAlignInBytes =
  97. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  98. IntAlignInBytes =
  99. C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
  100. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  101. IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
  102. Int8PtrTy = Int8Ty->getPointerTo(0);
  103. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  104. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  105. BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
  106. if (LangOpts.ObjC1)
  107. createObjCRuntime();
  108. if (LangOpts.OpenCL)
  109. createOpenCLRuntime();
  110. if (LangOpts.OpenMP)
  111. createOpenMPRuntime();
  112. if (LangOpts.CUDA)
  113. createCUDARuntime();
  114. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  115. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  116. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  117. TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
  118. getCXXABI().getMangleContext()));
  119. // If debug info or coverage generation is enabled, create the CGDebugInfo
  120. // object.
  121. if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
  122. CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
  123. DebugInfo.reset(new CGDebugInfo(*this));
  124. Block.GlobalUniqueCount = 0;
  125. if (C.getLangOpts().ObjC1)
  126. ObjCData.reset(new ObjCEntrypoints());
  127. if (CodeGenOpts.hasProfileClangUse()) {
  128. auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
  129. CodeGenOpts.ProfileInstrumentUsePath);
  130. if (auto E = ReaderOrErr.takeError()) {
  131. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  132. "Could not read profile %0: %1");
  133. llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
  134. getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
  135. << EI.message();
  136. });
  137. } else
  138. PGOReader = std::move(ReaderOrErr.get());
  139. }
  140. // If coverage mapping generation is enabled, create the
  141. // CoverageMappingModuleGen object.
  142. if (CodeGenOpts.CoverageMapping)
  143. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  144. }
  145. CodeGenModule::~CodeGenModule() {}
  146. void CodeGenModule::createObjCRuntime() {
  147. // This is just isGNUFamily(), but we want to force implementors of
  148. // new ABIs to decide how best to do this.
  149. switch (LangOpts.ObjCRuntime.getKind()) {
  150. case ObjCRuntime::GNUstep:
  151. case ObjCRuntime::GCC:
  152. case ObjCRuntime::ObjFW:
  153. ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
  154. return;
  155. case ObjCRuntime::FragileMacOSX:
  156. case ObjCRuntime::MacOSX:
  157. case ObjCRuntime::iOS:
  158. case ObjCRuntime::WatchOS:
  159. ObjCRuntime.reset(CreateMacObjCRuntime(*this));
  160. return;
  161. }
  162. llvm_unreachable("bad runtime kind");
  163. }
  164. void CodeGenModule::createOpenCLRuntime() {
  165. OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
  166. }
  167. void CodeGenModule::createOpenMPRuntime() {
  168. // Select a specialized code generation class based on the target, if any.
  169. // If it does not exist use the default implementation.
  170. switch (getTarget().getTriple().getArch()) {
  171. case llvm::Triple::nvptx:
  172. case llvm::Triple::nvptx64:
  173. assert(getLangOpts().OpenMPIsDevice &&
  174. "OpenMP NVPTX is only prepared to deal with device code.");
  175. OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
  176. break;
  177. default:
  178. OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
  179. break;
  180. }
  181. }
  182. void CodeGenModule::createCUDARuntime() {
  183. CUDARuntime.reset(CreateNVCUDARuntime(*this));
  184. }
  185. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  186. Replacements[Name] = C;
  187. }
  188. void CodeGenModule::applyReplacements() {
  189. for (auto &I : Replacements) {
  190. StringRef MangledName = I.first();
  191. llvm::Constant *Replacement = I.second;
  192. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  193. if (!Entry)
  194. continue;
  195. auto *OldF = cast<llvm::Function>(Entry);
  196. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  197. if (!NewF) {
  198. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  199. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  200. } else {
  201. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  202. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  203. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  204. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  205. }
  206. }
  207. // Replace old with new, but keep the old order.
  208. OldF->replaceAllUsesWith(Replacement);
  209. if (NewF) {
  210. NewF->removeFromParent();
  211. OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
  212. NewF);
  213. }
  214. OldF->eraseFromParent();
  215. }
  216. }
  217. void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
  218. GlobalValReplacements.push_back(std::make_pair(GV, C));
  219. }
  220. void CodeGenModule::applyGlobalValReplacements() {
  221. for (auto &I : GlobalValReplacements) {
  222. llvm::GlobalValue *GV = I.first;
  223. llvm::Constant *C = I.second;
  224. GV->replaceAllUsesWith(C);
  225. GV->eraseFromParent();
  226. }
  227. }
  228. // This is only used in aliases that we created and we know they have a
  229. // linear structure.
  230. static const llvm::GlobalObject *getAliasedGlobal(
  231. const llvm::GlobalIndirectSymbol &GIS) {
  232. llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
  233. const llvm::Constant *C = &GIS;
  234. for (;;) {
  235. C = C->stripPointerCasts();
  236. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  237. return GO;
  238. // stripPointerCasts will not walk over weak aliases.
  239. auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
  240. if (!GIS2)
  241. return nullptr;
  242. if (!Visited.insert(GIS2).second)
  243. return nullptr;
  244. C = GIS2->getIndirectSymbol();
  245. }
  246. }
  247. void CodeGenModule::checkAliases() {
  248. // Check if the constructed aliases are well formed. It is really unfortunate
  249. // that we have to do this in CodeGen, but we only construct mangled names
  250. // and aliases during codegen.
  251. bool Error = false;
  252. DiagnosticsEngine &Diags = getDiags();
  253. for (const GlobalDecl &GD : Aliases) {
  254. const auto *D = cast<ValueDecl>(GD.getDecl());
  255. SourceLocation Location;
  256. bool IsIFunc = D->hasAttr<IFuncAttr>();
  257. if (const Attr *A = D->getDefiningAttr())
  258. Location = A->getLocation();
  259. else
  260. llvm_unreachable("Not an alias or ifunc?");
  261. StringRef MangledName = getMangledName(GD);
  262. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  263. auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
  264. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  265. if (!GV) {
  266. Error = true;
  267. Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
  268. } else if (GV->isDeclaration()) {
  269. Error = true;
  270. Diags.Report(Location, diag::err_alias_to_undefined)
  271. << IsIFunc << IsIFunc;
  272. } else if (IsIFunc) {
  273. // Check resolver function type.
  274. llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
  275. GV->getType()->getPointerElementType());
  276. assert(FTy);
  277. if (!FTy->getReturnType()->isPointerTy())
  278. Diags.Report(Location, diag::err_ifunc_resolver_return);
  279. if (FTy->getNumParams())
  280. Diags.Report(Location, diag::err_ifunc_resolver_params);
  281. }
  282. llvm::Constant *Aliasee = Alias->getIndirectSymbol();
  283. llvm::GlobalValue *AliaseeGV;
  284. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  285. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  286. else
  287. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  288. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  289. StringRef AliasSection = SA->getName();
  290. if (AliasSection != AliaseeGV->getSection())
  291. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  292. << AliasSection << IsIFunc << IsIFunc;
  293. }
  294. // We have to handle alias to weak aliases in here. LLVM itself disallows
  295. // this since the object semantics would not match the IL one. For
  296. // compatibility with gcc we implement it by just pointing the alias
  297. // to its aliasee's aliasee. We also warn, since the user is probably
  298. // expecting the link to be weak.
  299. if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
  300. if (GA->isInterposable()) {
  301. Diags.Report(Location, diag::warn_alias_to_weak_alias)
  302. << GV->getName() << GA->getName() << IsIFunc;
  303. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  304. GA->getIndirectSymbol(), Alias->getType());
  305. Alias->setIndirectSymbol(Aliasee);
  306. }
  307. }
  308. }
  309. if (!Error)
  310. return;
  311. for (const GlobalDecl &GD : Aliases) {
  312. StringRef MangledName = getMangledName(GD);
  313. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  314. auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
  315. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  316. Alias->eraseFromParent();
  317. }
  318. }
  319. void CodeGenModule::clear() {
  320. DeferredDeclsToEmit.clear();
  321. if (OpenMPRuntime)
  322. OpenMPRuntime->clear();
  323. }
  324. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  325. StringRef MainFile) {
  326. if (!hasDiagnostics())
  327. return;
  328. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  329. if (MainFile.empty())
  330. MainFile = "<stdin>";
  331. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  332. } else
  333. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
  334. << Mismatched;
  335. }
  336. void CodeGenModule::Release() {
  337. EmitDeferred();
  338. applyGlobalValReplacements();
  339. applyReplacements();
  340. checkAliases();
  341. EmitCXXGlobalInitFunc();
  342. EmitCXXGlobalDtorFunc();
  343. EmitCXXThreadLocalInitFunc();
  344. if (ObjCRuntime)
  345. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  346. AddGlobalCtor(ObjCInitFunction);
  347. if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
  348. CUDARuntime) {
  349. if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
  350. AddGlobalCtor(CudaCtorFunction);
  351. if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
  352. AddGlobalDtor(CudaDtorFunction);
  353. }
  354. if (OpenMPRuntime)
  355. if (llvm::Function *OpenMPRegistrationFunction =
  356. OpenMPRuntime->emitRegistrationFunction())
  357. AddGlobalCtor(OpenMPRegistrationFunction, 0);
  358. if (PGOReader) {
  359. getModule().setMaximumFunctionCount(PGOReader->getMaximumFunctionCount());
  360. getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
  361. if (PGOStats.hasDiagnostics())
  362. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  363. }
  364. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  365. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  366. EmitGlobalAnnotations();
  367. EmitStaticExternCAliases();
  368. EmitDeferredUnusedCoverageMappings();
  369. if (CoverageMapping)
  370. CoverageMapping->emit();
  371. if (CodeGenOpts.SanitizeCfiCrossDso)
  372. CodeGenFunction(*this).EmitCfiCheckFail();
  373. emitLLVMUsed();
  374. if (SanStats)
  375. SanStats->finish();
  376. if (CodeGenOpts.Autolink &&
  377. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  378. EmitModuleLinkOptions();
  379. }
  380. if (CodeGenOpts.DwarfVersion) {
  381. // We actually want the latest version when there are conflicts.
  382. // We can change from Warning to Latest if such mode is supported.
  383. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  384. CodeGenOpts.DwarfVersion);
  385. }
  386. if (CodeGenOpts.EmitCodeView) {
  387. // Indicate that we want CodeView in the metadata.
  388. getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
  389. }
  390. if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
  391. // We don't support LTO with 2 with different StrictVTablePointers
  392. // FIXME: we could support it by stripping all the information introduced
  393. // by StrictVTablePointers.
  394. getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
  395. llvm::Metadata *Ops[2] = {
  396. llvm::MDString::get(VMContext, "StrictVTablePointers"),
  397. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  398. llvm::Type::getInt32Ty(VMContext), 1))};
  399. getModule().addModuleFlag(llvm::Module::Require,
  400. "StrictVTablePointersRequirement",
  401. llvm::MDNode::get(VMContext, Ops));
  402. }
  403. if (DebugInfo)
  404. // We support a single version in the linked module. The LLVM
  405. // parser will drop debug info with a different version number
  406. // (and warn about it, too).
  407. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  408. llvm::DEBUG_METADATA_VERSION);
  409. // We need to record the widths of enums and wchar_t, so that we can generate
  410. // the correct build attributes in the ARM backend.
  411. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  412. if ( Arch == llvm::Triple::arm
  413. || Arch == llvm::Triple::armeb
  414. || Arch == llvm::Triple::thumb
  415. || Arch == llvm::Triple::thumbeb) {
  416. // Width of wchar_t in bytes
  417. uint64_t WCharWidth =
  418. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  419. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  420. // The minimum width of an enum in bytes
  421. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  422. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  423. }
  424. if (CodeGenOpts.SanitizeCfiCrossDso) {
  425. // Indicate that we want cross-DSO control flow integrity checks.
  426. getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
  427. }
  428. if (LangOpts.CUDAIsDevice && getTarget().getTriple().isNVPTX()) {
  429. // Indicate whether __nvvm_reflect should be configured to flush denormal
  430. // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
  431. // property.)
  432. getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
  433. LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
  434. }
  435. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  436. assert(PLevel < 3 && "Invalid PIC Level");
  437. getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
  438. }
  439. if (uint32_t PLevel = Context.getLangOpts().PIELevel) {
  440. assert(PLevel < 3 && "Invalid PIE Level");
  441. getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
  442. }
  443. SimplifyPersonality();
  444. if (getCodeGenOpts().EmitDeclMetadata)
  445. EmitDeclMetadata();
  446. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  447. EmitCoverageFile();
  448. if (DebugInfo)
  449. DebugInfo->finalize();
  450. EmitVersionIdentMetadata();
  451. EmitTargetMetadata();
  452. }
  453. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  454. // Make sure that this type is translated.
  455. Types.UpdateCompletedType(TD);
  456. }
  457. void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
  458. // Make sure that this type is translated.
  459. Types.RefreshTypeCacheForClass(RD);
  460. }
  461. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  462. if (!TBAA)
  463. return nullptr;
  464. return TBAA->getTBAAInfo(QTy);
  465. }
  466. llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
  467. if (!TBAA)
  468. return nullptr;
  469. return TBAA->getTBAAInfoForVTablePtr();
  470. }
  471. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  472. if (!TBAA)
  473. return nullptr;
  474. return TBAA->getTBAAStructInfo(QTy);
  475. }
  476. llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
  477. llvm::MDNode *AccessN,
  478. uint64_t O) {
  479. if (!TBAA)
  480. return nullptr;
  481. return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
  482. }
  483. /// Decorate the instruction with a TBAA tag. For both scalar TBAA
  484. /// and struct-path aware TBAA, the tag has the same format:
  485. /// base type, access type and offset.
  486. /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
  487. void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  488. llvm::MDNode *TBAAInfo,
  489. bool ConvertTypeToTag) {
  490. if (ConvertTypeToTag && TBAA)
  491. Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
  492. TBAA->getTBAAScalarTagInfo(TBAAInfo));
  493. else
  494. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  495. }
  496. void CodeGenModule::DecorateInstructionWithInvariantGroup(
  497. llvm::Instruction *I, const CXXRecordDecl *RD) {
  498. llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  499. auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
  500. // Check if we have to wrap MDString in MDNode.
  501. if (!MetaDataNode)
  502. MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
  503. I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
  504. }
  505. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  506. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  507. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  508. }
  509. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  510. /// specified stmt yet.
  511. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  512. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  513. "cannot compile this %0 yet");
  514. std::string Msg = Type;
  515. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  516. << Msg << S->getSourceRange();
  517. }
  518. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  519. /// specified decl yet.
  520. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  521. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  522. "cannot compile this %0 yet");
  523. std::string Msg = Type;
  524. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  525. }
  526. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  527. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  528. }
  529. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  530. const NamedDecl *D) const {
  531. // Internal definitions always have default visibility.
  532. if (GV->hasLocalLinkage()) {
  533. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  534. return;
  535. }
  536. // Set visibility for definitions.
  537. LinkageInfo LV = D->getLinkageAndVisibility();
  538. if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  539. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  540. }
  541. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  542. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  543. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  544. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  545. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  546. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  547. }
  548. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  549. CodeGenOptions::TLSModel M) {
  550. switch (M) {
  551. case CodeGenOptions::GeneralDynamicTLSModel:
  552. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  553. case CodeGenOptions::LocalDynamicTLSModel:
  554. return llvm::GlobalVariable::LocalDynamicTLSModel;
  555. case CodeGenOptions::InitialExecTLSModel:
  556. return llvm::GlobalVariable::InitialExecTLSModel;
  557. case CodeGenOptions::LocalExecTLSModel:
  558. return llvm::GlobalVariable::LocalExecTLSModel;
  559. }
  560. llvm_unreachable("Invalid TLS model!");
  561. }
  562. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  563. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  564. llvm::GlobalValue::ThreadLocalMode TLM;
  565. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  566. // Override the TLS model if it is explicitly specified.
  567. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  568. TLM = GetLLVMTLSModel(Attr->getModel());
  569. }
  570. GV->setThreadLocalMode(TLM);
  571. }
  572. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  573. GlobalDecl CanonicalGD = GD.getCanonicalDecl();
  574. // Some ABIs don't have constructor variants. Make sure that base and
  575. // complete constructors get mangled the same.
  576. if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
  577. if (!getTarget().getCXXABI().hasConstructorVariants()) {
  578. CXXCtorType OrigCtorType = GD.getCtorType();
  579. assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
  580. if (OrigCtorType == Ctor_Base)
  581. CanonicalGD = GlobalDecl(CD, Ctor_Complete);
  582. }
  583. }
  584. StringRef &FoundStr = MangledDeclNames[CanonicalGD];
  585. if (!FoundStr.empty())
  586. return FoundStr;
  587. const auto *ND = cast<NamedDecl>(GD.getDecl());
  588. SmallString<256> Buffer;
  589. StringRef Str;
  590. if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  591. llvm::raw_svector_ostream Out(Buffer);
  592. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  593. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  594. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  595. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  596. else
  597. getCXXABI().getMangleContext().mangleName(ND, Out);
  598. Str = Out.str();
  599. } else {
  600. IdentifierInfo *II = ND->getIdentifier();
  601. assert(II && "Attempt to mangle unnamed decl.");
  602. Str = II->getName();
  603. }
  604. // Keep the first result in the case of a mangling collision.
  605. auto Result = Manglings.insert(std::make_pair(Str, GD));
  606. return FoundStr = Result.first->first();
  607. }
  608. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  609. const BlockDecl *BD) {
  610. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  611. const Decl *D = GD.getDecl();
  612. SmallString<256> Buffer;
  613. llvm::raw_svector_ostream Out(Buffer);
  614. if (!D)
  615. MangleCtx.mangleGlobalBlock(BD,
  616. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  617. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  618. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  619. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  620. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  621. else
  622. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  623. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  624. return Result.first->first();
  625. }
  626. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  627. return getModule().getNamedValue(Name);
  628. }
  629. /// AddGlobalCtor - Add a function to the list that will be called before
  630. /// main() runs.
  631. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  632. llvm::Constant *AssociatedData) {
  633. // FIXME: Type coercion of void()* types.
  634. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  635. }
  636. /// AddGlobalDtor - Add a function to the list that will be called
  637. /// when the module is unloaded.
  638. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  639. // FIXME: Type coercion of void()* types.
  640. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  641. }
  642. void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
  643. // Ctor function type is void()*.
  644. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  645. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  646. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  647. llvm::StructType *CtorStructTy = llvm::StructType::get(
  648. Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
  649. // Construct the constructor and destructor arrays.
  650. SmallVector<llvm::Constant *, 8> Ctors;
  651. for (const auto &I : Fns) {
  652. llvm::Constant *S[] = {
  653. llvm::ConstantInt::get(Int32Ty, I.Priority, false),
  654. llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy),
  655. (I.AssociatedData
  656. ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)
  657. : llvm::Constant::getNullValue(VoidPtrTy))};
  658. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  659. }
  660. if (!Ctors.empty()) {
  661. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  662. new llvm::GlobalVariable(TheModule, AT, false,
  663. llvm::GlobalValue::AppendingLinkage,
  664. llvm::ConstantArray::get(AT, Ctors),
  665. GlobalName);
  666. }
  667. }
  668. llvm::GlobalValue::LinkageTypes
  669. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  670. const auto *D = cast<FunctionDecl>(GD.getDecl());
  671. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  672. if (isa<CXXDestructorDecl>(D) &&
  673. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  674. GD.getDtorType())) {
  675. // Destructor variants in the Microsoft C++ ABI are always internal or
  676. // linkonce_odr thunks emitted on an as-needed basis.
  677. return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
  678. : llvm::GlobalValue::LinkOnceODRLinkage;
  679. }
  680. return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
  681. }
  682. void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
  683. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  684. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
  685. if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
  686. // Don't dllexport/import destructor thunks.
  687. F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  688. return;
  689. }
  690. }
  691. if (FD->hasAttr<DLLImportAttr>())
  692. F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  693. else if (FD->hasAttr<DLLExportAttr>())
  694. F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  695. else
  696. F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  697. }
  698. llvm::ConstantInt *
  699. CodeGenModule::CreateCfiIdForTypeMetadata(llvm::Metadata *MD) {
  700. llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
  701. if (!MDS) return nullptr;
  702. llvm::MD5 md5;
  703. llvm::MD5::MD5Result result;
  704. md5.update(MDS->getString());
  705. md5.final(result);
  706. uint64_t id = 0;
  707. for (int i = 0; i < 8; ++i)
  708. id |= static_cast<uint64_t>(result[i]) << (i * 8);
  709. return llvm::ConstantInt::get(Int64Ty, id);
  710. }
  711. void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
  712. llvm::Function *F) {
  713. setNonAliasAttributes(D, F);
  714. }
  715. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  716. const CGFunctionInfo &Info,
  717. llvm::Function *F) {
  718. unsigned CallingConv;
  719. AttributeListType AttributeList;
  720. ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv,
  721. false);
  722. F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
  723. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  724. }
  725. /// Determines whether the language options require us to model
  726. /// unwind exceptions. We treat -fexceptions as mandating this
  727. /// except under the fragile ObjC ABI with only ObjC exceptions
  728. /// enabled. This means, for example, that C with -fexceptions
  729. /// enables this.
  730. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  731. // If exceptions are completely disabled, obviously this is false.
  732. if (!LangOpts.Exceptions) return false;
  733. // If C++ exceptions are enabled, this is true.
  734. if (LangOpts.CXXExceptions) return true;
  735. // If ObjC exceptions are enabled, this depends on the ABI.
  736. if (LangOpts.ObjCExceptions) {
  737. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  738. }
  739. return true;
  740. }
  741. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  742. llvm::Function *F) {
  743. llvm::AttrBuilder B;
  744. if (CodeGenOpts.UnwindTables)
  745. B.addAttribute(llvm::Attribute::UWTable);
  746. if (!hasUnwindExceptions(LangOpts))
  747. B.addAttribute(llvm::Attribute::NoUnwind);
  748. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  749. B.addAttribute(llvm::Attribute::StackProtect);
  750. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  751. B.addAttribute(llvm::Attribute::StackProtectStrong);
  752. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  753. B.addAttribute(llvm::Attribute::StackProtectReq);
  754. if (!D) {
  755. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  756. llvm::AttributeSet::get(
  757. F->getContext(),
  758. llvm::AttributeSet::FunctionIndex, B));
  759. return;
  760. }
  761. if (D->hasAttr<NakedAttr>()) {
  762. // Naked implies noinline: we should not be inlining such functions.
  763. B.addAttribute(llvm::Attribute::Naked);
  764. B.addAttribute(llvm::Attribute::NoInline);
  765. } else if (D->hasAttr<NoDuplicateAttr>()) {
  766. B.addAttribute(llvm::Attribute::NoDuplicate);
  767. } else if (D->hasAttr<NoInlineAttr>()) {
  768. B.addAttribute(llvm::Attribute::NoInline);
  769. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  770. !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
  771. llvm::Attribute::NoInline)) {
  772. // (noinline wins over always_inline, and we can't specify both in IR)
  773. B.addAttribute(llvm::Attribute::AlwaysInline);
  774. }
  775. if (D->hasAttr<ColdAttr>()) {
  776. if (!D->hasAttr<OptimizeNoneAttr>())
  777. B.addAttribute(llvm::Attribute::OptimizeForSize);
  778. B.addAttribute(llvm::Attribute::Cold);
  779. }
  780. if (D->hasAttr<MinSizeAttr>())
  781. B.addAttribute(llvm::Attribute::MinSize);
  782. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  783. llvm::AttributeSet::get(
  784. F->getContext(), llvm::AttributeSet::FunctionIndex, B));
  785. if (D->hasAttr<OptimizeNoneAttr>()) {
  786. // OptimizeNone implies noinline; we should not be inlining such functions.
  787. F->addFnAttr(llvm::Attribute::OptimizeNone);
  788. F->addFnAttr(llvm::Attribute::NoInline);
  789. // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
  790. F->removeFnAttr(llvm::Attribute::OptimizeForSize);
  791. F->removeFnAttr(llvm::Attribute::MinSize);
  792. assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  793. "OptimizeNone and AlwaysInline on same function!");
  794. // Attribute 'inlinehint' has no effect on 'optnone' functions.
  795. // Explicitly remove it from the set of function attributes.
  796. F->removeFnAttr(llvm::Attribute::InlineHint);
  797. }
  798. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  799. if (alignment)
  800. F->setAlignment(alignment);
  801. // Some C++ ABIs require 2-byte alignment for member functions, in order to
  802. // reserve a bit for differentiating between virtual and non-virtual member
  803. // functions. If the current target's C++ ABI requires this and this is a
  804. // member function, set its alignment accordingly.
  805. if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
  806. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  807. F->setAlignment(2);
  808. }
  809. }
  810. void CodeGenModule::SetCommonAttributes(const Decl *D,
  811. llvm::GlobalValue *GV) {
  812. if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
  813. setGlobalVisibility(GV, ND);
  814. else
  815. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  816. if (D && D->hasAttr<UsedAttr>())
  817. addUsedGlobal(GV);
  818. }
  819. void CodeGenModule::setAliasAttributes(const Decl *D,
  820. llvm::GlobalValue *GV) {
  821. SetCommonAttributes(D, GV);
  822. // Process the dllexport attribute based on whether the original definition
  823. // (not necessarily the aliasee) was exported.
  824. if (D->hasAttr<DLLExportAttr>())
  825. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  826. }
  827. void CodeGenModule::setNonAliasAttributes(const Decl *D,
  828. llvm::GlobalObject *GO) {
  829. SetCommonAttributes(D, GO);
  830. if (D)
  831. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  832. GO->setSection(SA->getName());
  833. getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
  834. }
  835. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  836. llvm::Function *F,
  837. const CGFunctionInfo &FI) {
  838. SetLLVMFunctionAttributes(D, FI, F);
  839. SetLLVMFunctionAttributesForDefinition(D, F);
  840. F->setLinkage(llvm::Function::InternalLinkage);
  841. setNonAliasAttributes(D, F);
  842. }
  843. static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
  844. const NamedDecl *ND) {
  845. // Set linkage and visibility in case we never see a definition.
  846. LinkageInfo LV = ND->getLinkageAndVisibility();
  847. if (LV.getLinkage() != ExternalLinkage) {
  848. // Don't set internal linkage on declarations.
  849. } else {
  850. if (ND->hasAttr<DLLImportAttr>()) {
  851. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  852. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  853. } else if (ND->hasAttr<DLLExportAttr>()) {
  854. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  855. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  856. } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
  857. // "extern_weak" is overloaded in LLVM; we probably should have
  858. // separate linkage types for this.
  859. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  860. }
  861. // Set visibility on a declaration only if it's explicit.
  862. if (LV.isVisibilityExplicit())
  863. GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
  864. }
  865. }
  866. void CodeGenModule::CreateFunctionBitSetEntry(const FunctionDecl *FD,
  867. llvm::Function *F) {
  868. // Only if we are checking indirect calls.
  869. if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
  870. return;
  871. // Non-static class methods are handled via vtable pointer checks elsewhere.
  872. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  873. return;
  874. // Additionally, if building with cross-DSO support...
  875. if (CodeGenOpts.SanitizeCfiCrossDso) {
  876. // Don't emit entries for function declarations. In cross-DSO mode these are
  877. // handled with better precision at run time.
  878. if (!FD->hasBody())
  879. return;
  880. // Skip available_externally functions. They won't be codegen'ed in the
  881. // current module anyway.
  882. if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
  883. return;
  884. }
  885. llvm::NamedMDNode *BitsetsMD =
  886. getModule().getOrInsertNamedMetadata("llvm.bitsets");
  887. llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
  888. llvm::Metadata *BitsetOps[] = {
  889. MD, llvm::ConstantAsMetadata::get(F),
  890. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))};
  891. BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps));
  892. // Emit a hash-based bit set entry for cross-DSO calls.
  893. if (CodeGenOpts.SanitizeCfiCrossDso) {
  894. if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) {
  895. llvm::Metadata *BitsetOps2[] = {
  896. llvm::ConstantAsMetadata::get(TypeId),
  897. llvm::ConstantAsMetadata::get(F),
  898. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))};
  899. BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2));
  900. }
  901. }
  902. }
  903. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  904. bool IsIncompleteFunction,
  905. bool IsThunk) {
  906. if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
  907. // If this is an intrinsic function, set the function's attributes
  908. // to the intrinsic's attributes.
  909. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
  910. return;
  911. }
  912. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  913. if (!IsIncompleteFunction)
  914. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  915. // Add the Returned attribute for "this", except for iOS 5 and earlier
  916. // where substantial code, including the libstdc++ dylib, was compiled with
  917. // GCC and does not actually return "this".
  918. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  919. !(getTarget().getTriple().isiOS() &&
  920. getTarget().getTriple().isOSVersionLT(6))) {
  921. assert(!F->arg_empty() &&
  922. F->arg_begin()->getType()
  923. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  924. "unexpected this return");
  925. F->addAttribute(1, llvm::Attribute::Returned);
  926. }
  927. // Only a few attributes are set on declarations; these may later be
  928. // overridden by a definition.
  929. setLinkageAndVisibilityForGV(F, FD);
  930. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  931. F->setSection(SA->getName());
  932. if (FD->isReplaceableGlobalAllocationFunction()) {
  933. // A replaceable global allocation function does not act like a builtin by
  934. // default, only if it is invoked by a new-expression or delete-expression.
  935. F->addAttribute(llvm::AttributeSet::FunctionIndex,
  936. llvm::Attribute::NoBuiltin);
  937. // A sane operator new returns a non-aliasing pointer.
  938. // FIXME: Also add NonNull attribute to the return value
  939. // for the non-nothrow forms?
  940. auto Kind = FD->getDeclName().getCXXOverloadedOperator();
  941. if (getCodeGenOpts().AssumeSaneOperatorNew &&
  942. (Kind == OO_New || Kind == OO_Array_New))
  943. F->addAttribute(llvm::AttributeSet::ReturnIndex,
  944. llvm::Attribute::NoAlias);
  945. }
  946. if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
  947. F->setUnnamedAddr(true);
  948. else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  949. if (MD->isVirtual())
  950. F->setUnnamedAddr(true);
  951. CreateFunctionBitSetEntry(FD, F);
  952. }
  953. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  954. assert(!GV->isDeclaration() &&
  955. "Only globals with definition can force usage.");
  956. LLVMUsed.emplace_back(GV);
  957. }
  958. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  959. assert(!GV->isDeclaration() &&
  960. "Only globals with definition can force usage.");
  961. LLVMCompilerUsed.emplace_back(GV);
  962. }
  963. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  964. std::vector<llvm::WeakVH> &List) {
  965. // Don't create llvm.used if there is no need.
  966. if (List.empty())
  967. return;
  968. // Convert List to what ConstantArray needs.
  969. SmallVector<llvm::Constant*, 8> UsedArray;
  970. UsedArray.resize(List.size());
  971. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  972. UsedArray[i] =
  973. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  974. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  975. }
  976. if (UsedArray.empty())
  977. return;
  978. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  979. auto *GV = new llvm::GlobalVariable(
  980. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  981. llvm::ConstantArray::get(ATy, UsedArray), Name);
  982. GV->setSection("llvm.metadata");
  983. }
  984. void CodeGenModule::emitLLVMUsed() {
  985. emitUsed(*this, "llvm.used", LLVMUsed);
  986. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  987. }
  988. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  989. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  990. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  991. }
  992. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  993. llvm::SmallString<32> Opt;
  994. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  995. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  996. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  997. }
  998. void CodeGenModule::AddDependentLib(StringRef Lib) {
  999. llvm::SmallString<24> Opt;
  1000. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  1001. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1002. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1003. }
  1004. /// \brief Add link options implied by the given module, including modules
  1005. /// it depends on, using a postorder walk.
  1006. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  1007. SmallVectorImpl<llvm::Metadata *> &Metadata,
  1008. llvm::SmallPtrSet<Module *, 16> &Visited) {
  1009. // Import this module's parent.
  1010. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  1011. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  1012. }
  1013. // Import this module's dependencies.
  1014. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  1015. if (Visited.insert(Mod->Imports[I - 1]).second)
  1016. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  1017. }
  1018. // Add linker options to link against the libraries/frameworks
  1019. // described by this module.
  1020. llvm::LLVMContext &Context = CGM.getLLVMContext();
  1021. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  1022. // Link against a framework. Frameworks are currently Darwin only, so we
  1023. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  1024. if (Mod->LinkLibraries[I-1].IsFramework) {
  1025. llvm::Metadata *Args[2] = {
  1026. llvm::MDString::get(Context, "-framework"),
  1027. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
  1028. Metadata.push_back(llvm::MDNode::get(Context, Args));
  1029. continue;
  1030. }
  1031. // Link against a library.
  1032. llvm::SmallString<24> Opt;
  1033. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  1034. Mod->LinkLibraries[I-1].Library, Opt);
  1035. auto *OptString = llvm::MDString::get(Context, Opt);
  1036. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  1037. }
  1038. }
  1039. void CodeGenModule::EmitModuleLinkOptions() {
  1040. // Collect the set of all of the modules we want to visit to emit link
  1041. // options, which is essentially the imported modules and all of their
  1042. // non-explicit child modules.
  1043. llvm::SetVector<clang::Module *> LinkModules;
  1044. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  1045. SmallVector<clang::Module *, 16> Stack;
  1046. // Seed the stack with imported modules.
  1047. for (Module *M : ImportedModules)
  1048. if (Visited.insert(M).second)
  1049. Stack.push_back(M);
  1050. // Find all of the modules to import, making a little effort to prune
  1051. // non-leaf modules.
  1052. while (!Stack.empty()) {
  1053. clang::Module *Mod = Stack.pop_back_val();
  1054. bool AnyChildren = false;
  1055. // Visit the submodules of this module.
  1056. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  1057. SubEnd = Mod->submodule_end();
  1058. Sub != SubEnd; ++Sub) {
  1059. // Skip explicit children; they need to be explicitly imported to be
  1060. // linked against.
  1061. if ((*Sub)->IsExplicit)
  1062. continue;
  1063. if (Visited.insert(*Sub).second) {
  1064. Stack.push_back(*Sub);
  1065. AnyChildren = true;
  1066. }
  1067. }
  1068. // We didn't find any children, so add this module to the list of
  1069. // modules to link against.
  1070. if (!AnyChildren) {
  1071. LinkModules.insert(Mod);
  1072. }
  1073. }
  1074. // Add link options for all of the imported modules in reverse topological
  1075. // order. We don't do anything to try to order import link flags with respect
  1076. // to linker options inserted by things like #pragma comment().
  1077. SmallVector<llvm::Metadata *, 16> MetadataArgs;
  1078. Visited.clear();
  1079. for (Module *M : LinkModules)
  1080. if (Visited.insert(M).second)
  1081. addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
  1082. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  1083. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  1084. // Add the linker options metadata flag.
  1085. getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
  1086. llvm::MDNode::get(getLLVMContext(),
  1087. LinkerOptionsMetadata));
  1088. }
  1089. void CodeGenModule::EmitDeferred() {
  1090. // Emit code for any potentially referenced deferred decls. Since a
  1091. // previously unused static decl may become used during the generation of code
  1092. // for a static function, iterate until no changes are made.
  1093. if (!DeferredVTables.empty()) {
  1094. EmitDeferredVTables();
  1095. // Emitting a vtable doesn't directly cause more vtables to
  1096. // become deferred, although it can cause functions to be
  1097. // emitted that then need those vtables.
  1098. assert(DeferredVTables.empty());
  1099. }
  1100. // Stop if we're out of both deferred vtables and deferred declarations.
  1101. if (DeferredDeclsToEmit.empty())
  1102. return;
  1103. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  1104. // work, it will not interfere with this.
  1105. std::vector<DeferredGlobal> CurDeclsToEmit;
  1106. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  1107. for (DeferredGlobal &G : CurDeclsToEmit) {
  1108. GlobalDecl D = G.GD;
  1109. G.GV = nullptr;
  1110. // We should call GetAddrOfGlobal with IsForDefinition set to true in order
  1111. // to get GlobalValue with exactly the type we need, not something that
  1112. // might had been created for another decl with the same mangled name but
  1113. // different type.
  1114. llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
  1115. GetAddrOfGlobal(D, /*IsForDefinition=*/true));
  1116. // In case of different address spaces, we may still get a cast, even with
  1117. // IsForDefinition equal to true. Query mangled names table to get
  1118. // GlobalValue.
  1119. if (!GV)
  1120. GV = GetGlobalValue(getMangledName(D));
  1121. // Make sure GetGlobalValue returned non-null.
  1122. assert(GV);
  1123. // Check to see if we've already emitted this. This is necessary
  1124. // for a couple of reasons: first, decls can end up in the
  1125. // deferred-decls queue multiple times, and second, decls can end
  1126. // up with definitions in unusual ways (e.g. by an extern inline
  1127. // function acquiring a strong function redefinition). Just
  1128. // ignore these cases.
  1129. if (!GV->isDeclaration())
  1130. continue;
  1131. // Otherwise, emit the definition and move on to the next one.
  1132. EmitGlobalDefinition(D, GV);
  1133. // If we found out that we need to emit more decls, do that recursively.
  1134. // This has the advantage that the decls are emitted in a DFS and related
  1135. // ones are close together, which is convenient for testing.
  1136. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  1137. EmitDeferred();
  1138. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  1139. }
  1140. }
  1141. }
  1142. void CodeGenModule::EmitGlobalAnnotations() {
  1143. if (Annotations.empty())
  1144. return;
  1145. // Create a new global variable for the ConstantStruct in the Module.
  1146. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  1147. Annotations[0]->getType(), Annotations.size()), Annotations);
  1148. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  1149. llvm::GlobalValue::AppendingLinkage,
  1150. Array, "llvm.global.annotations");
  1151. gv->setSection(AnnotationSection);
  1152. }
  1153. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  1154. llvm::Constant *&AStr = AnnotationStrings[Str];
  1155. if (AStr)
  1156. return AStr;
  1157. // Not found yet, create a new global.
  1158. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  1159. auto *gv =
  1160. new llvm::GlobalVariable(getModule(), s->getType(), true,
  1161. llvm::GlobalValue::PrivateLinkage, s, ".str");
  1162. gv->setSection(AnnotationSection);
  1163. gv->setUnnamedAddr(true);
  1164. AStr = gv;
  1165. return gv;
  1166. }
  1167. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  1168. SourceManager &SM = getContext().getSourceManager();
  1169. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  1170. if (PLoc.isValid())
  1171. return EmitAnnotationString(PLoc.getFilename());
  1172. return EmitAnnotationString(SM.getBufferName(Loc));
  1173. }
  1174. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  1175. SourceManager &SM = getContext().getSourceManager();
  1176. PresumedLoc PLoc = SM.getPresumedLoc(L);
  1177. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  1178. SM.getExpansionLineNumber(L);
  1179. return llvm::ConstantInt::get(Int32Ty, LineNo);
  1180. }
  1181. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  1182. const AnnotateAttr *AA,
  1183. SourceLocation L) {
  1184. // Get the globals for file name, annotation, and the line number.
  1185. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  1186. *UnitGV = EmitAnnotationUnit(L),
  1187. *LineNoCst = EmitAnnotationLineNo(L);
  1188. // Create the ConstantStruct for the global annotation.
  1189. llvm::Constant *Fields[4] = {
  1190. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  1191. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  1192. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  1193. LineNoCst
  1194. };
  1195. return llvm::ConstantStruct::getAnon(Fields);
  1196. }
  1197. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  1198. llvm::GlobalValue *GV) {
  1199. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1200. // Get the struct elements for these annotations.
  1201. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1202. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1203. }
  1204. bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
  1205. SourceLocation Loc) const {
  1206. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1207. // Blacklist by function name.
  1208. if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
  1209. return true;
  1210. // Blacklist by location.
  1211. if (Loc.isValid())
  1212. return SanitizerBL.isBlacklistedLocation(Loc);
  1213. // If location is unknown, this may be a compiler-generated function. Assume
  1214. // it's located in the main file.
  1215. auto &SM = Context.getSourceManager();
  1216. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1217. return SanitizerBL.isBlacklistedFile(MainFile->getName());
  1218. }
  1219. return false;
  1220. }
  1221. bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
  1222. SourceLocation Loc, QualType Ty,
  1223. StringRef Category) const {
  1224. // For now globals can be blacklisted only in ASan and KASan.
  1225. if (!LangOpts.Sanitize.hasOneOf(
  1226. SanitizerKind::Address | SanitizerKind::KernelAddress))
  1227. return false;
  1228. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1229. if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
  1230. return true;
  1231. if (SanitizerBL.isBlacklistedLocation(Loc, Category))
  1232. return true;
  1233. // Check global type.
  1234. if (!Ty.isNull()) {
  1235. // Drill down the array types: if global variable of a fixed type is
  1236. // blacklisted, we also don't instrument arrays of them.
  1237. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  1238. Ty = AT->getElementType();
  1239. Ty = Ty.getCanonicalType().getUnqualifiedType();
  1240. // We allow to blacklist only record types (classes, structs etc.)
  1241. if (Ty->isRecordType()) {
  1242. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  1243. if (SanitizerBL.isBlacklistedType(TypeStr, Category))
  1244. return true;
  1245. }
  1246. }
  1247. return false;
  1248. }
  1249. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  1250. // Never defer when EmitAllDecls is specified.
  1251. if (LangOpts.EmitAllDecls)
  1252. return true;
  1253. return getContext().DeclMustBeEmitted(Global);
  1254. }
  1255. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  1256. if (const auto *FD = dyn_cast<FunctionDecl>(Global))
  1257. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1258. // Implicit template instantiations may change linkage if they are later
  1259. // explicitly instantiated, so they should not be emitted eagerly.
  1260. return false;
  1261. // If OpenMP is enabled and threadprivates must be generated like TLS, delay
  1262. // codegen for global variables, because they may be marked as threadprivate.
  1263. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
  1264. getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
  1265. return false;
  1266. return true;
  1267. }
  1268. ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
  1269. const CXXUuidofExpr* E) {
  1270. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  1271. // well-formed.
  1272. StringRef Uuid = E->getUuidStr();
  1273. std::string Name = "_GUID_" + Uuid.lower();
  1274. std::replace(Name.begin(), Name.end(), '-', '_');
  1275. // The UUID descriptor should be pointer aligned.
  1276. CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
  1277. // Look for an existing global.
  1278. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  1279. return ConstantAddress(GV, Alignment);
  1280. llvm::Constant *Init = EmitUuidofInitializer(Uuid);
  1281. assert(Init && "failed to initialize as constant");
  1282. auto *GV = new llvm::GlobalVariable(
  1283. getModule(), Init->getType(),
  1284. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  1285. if (supportsCOMDAT())
  1286. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1287. return ConstantAddress(GV, Alignment);
  1288. }
  1289. ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  1290. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  1291. assert(AA && "No alias?");
  1292. CharUnits Alignment = getContext().getDeclAlign(VD);
  1293. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  1294. // See if there is already something with the target's name in the module.
  1295. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  1296. if (Entry) {
  1297. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  1298. auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  1299. return ConstantAddress(Ptr, Alignment);
  1300. }
  1301. llvm::Constant *Aliasee;
  1302. if (isa<llvm::FunctionType>(DeclTy))
  1303. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  1304. GlobalDecl(cast<FunctionDecl>(VD)),
  1305. /*ForVTable=*/false);
  1306. else
  1307. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1308. llvm::PointerType::getUnqual(DeclTy),
  1309. nullptr);
  1310. auto *F = cast<llvm::GlobalValue>(Aliasee);
  1311. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1312. WeakRefReferences.insert(F);
  1313. return ConstantAddress(Aliasee, Alignment);
  1314. }
  1315. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  1316. const auto *Global = cast<ValueDecl>(GD.getDecl());
  1317. // Weak references don't produce any output by themselves.
  1318. if (Global->hasAttr<WeakRefAttr>())
  1319. return;
  1320. // If this is an alias definition (which otherwise looks like a declaration)
  1321. // emit it now.
  1322. if (Global->hasAttr<AliasAttr>())
  1323. return EmitAliasDefinition(GD);
  1324. // IFunc like an alias whose value is resolved at runtime by calling resolver.
  1325. if (Global->hasAttr<IFuncAttr>())
  1326. return emitIFuncDefinition(GD);
  1327. // If this is CUDA, be selective about which declarations we emit.
  1328. if (LangOpts.CUDA) {
  1329. if (LangOpts.CUDAIsDevice) {
  1330. if (!Global->hasAttr<CUDADeviceAttr>() &&
  1331. !Global->hasAttr<CUDAGlobalAttr>() &&
  1332. !Global->hasAttr<CUDAConstantAttr>() &&
  1333. !Global->hasAttr<CUDASharedAttr>())
  1334. return;
  1335. } else {
  1336. // We need to emit host-side 'shadows' for all global
  1337. // device-side variables because the CUDA runtime needs their
  1338. // size and host-side address in order to provide access to
  1339. // their device-side incarnations.
  1340. // So device-only functions are the only things we skip.
  1341. if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
  1342. Global->hasAttr<CUDADeviceAttr>())
  1343. return;
  1344. assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
  1345. "Expected Variable or Function");
  1346. }
  1347. }
  1348. if (LangOpts.OpenMP) {
  1349. // If this is OpenMP device, check if it is legal to emit this global
  1350. // normally.
  1351. if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
  1352. return;
  1353. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
  1354. if (MustBeEmitted(Global))
  1355. EmitOMPDeclareReduction(DRD);
  1356. return;
  1357. }
  1358. }
  1359. // Ignore declarations, they will be emitted on their first use.
  1360. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  1361. // Forward declarations are emitted lazily on first use.
  1362. if (!FD->doesThisDeclarationHaveABody()) {
  1363. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  1364. return;
  1365. StringRef MangledName = getMangledName(GD);
  1366. // Compute the function info and LLVM type.
  1367. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1368. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  1369. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  1370. /*DontDefer=*/false);
  1371. return;
  1372. }
  1373. } else {
  1374. const auto *VD = cast<VarDecl>(Global);
  1375. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  1376. // We need to emit device-side global CUDA variables even if a
  1377. // variable does not have a definition -- we still need to define
  1378. // host-side shadow for it.
  1379. bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
  1380. !VD->hasDefinition() &&
  1381. (VD->hasAttr<CUDAConstantAttr>() ||
  1382. VD->hasAttr<CUDADeviceAttr>());
  1383. if (!MustEmitForCuda &&
  1384. VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  1385. !Context.isMSStaticDataMemberInlineDefinition(VD))
  1386. return;
  1387. }
  1388. // Defer code generation to first use when possible, e.g. if this is an inline
  1389. // function. If the global must always be emitted, do it eagerly if possible
  1390. // to benefit from cache locality.
  1391. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  1392. // Emit the definition if it can't be deferred.
  1393. EmitGlobalDefinition(GD);
  1394. return;
  1395. }
  1396. // If we're deferring emission of a C++ variable with an
  1397. // initializer, remember the order in which it appeared in the file.
  1398. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1399. cast<VarDecl>(Global)->hasInit()) {
  1400. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1401. CXXGlobalInits.push_back(nullptr);
  1402. }
  1403. StringRef MangledName = getMangledName(GD);
  1404. if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
  1405. // The value has already been used and should therefore be emitted.
  1406. addDeferredDeclToEmit(GV, GD);
  1407. } else if (MustBeEmitted(Global)) {
  1408. // The value must be emitted, but cannot be emitted eagerly.
  1409. assert(!MayBeEmittedEagerly(Global));
  1410. addDeferredDeclToEmit(/*GV=*/nullptr, GD);
  1411. } else {
  1412. // Otherwise, remember that we saw a deferred decl with this name. The
  1413. // first use of the mangled name will cause it to move into
  1414. // DeferredDeclsToEmit.
  1415. DeferredDecls[MangledName] = GD;
  1416. }
  1417. }
  1418. namespace {
  1419. struct FunctionIsDirectlyRecursive :
  1420. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  1421. const StringRef Name;
  1422. const Builtin::Context &BI;
  1423. bool Result;
  1424. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  1425. Name(N), BI(C), Result(false) {
  1426. }
  1427. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  1428. bool TraverseCallExpr(CallExpr *E) {
  1429. const FunctionDecl *FD = E->getDirectCallee();
  1430. if (!FD)
  1431. return true;
  1432. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1433. if (Attr && Name == Attr->getLabel()) {
  1434. Result = true;
  1435. return false;
  1436. }
  1437. unsigned BuiltinID = FD->getBuiltinID();
  1438. if (!BuiltinID || !BI.isLibFunction(BuiltinID))
  1439. return true;
  1440. StringRef BuiltinName = BI.getName(BuiltinID);
  1441. if (BuiltinName.startswith("__builtin_") &&
  1442. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  1443. Result = true;
  1444. return false;
  1445. }
  1446. return true;
  1447. }
  1448. };
  1449. struct DLLImportFunctionVisitor
  1450. : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
  1451. bool SafeToInline = true;
  1452. bool VisitVarDecl(VarDecl *VD) {
  1453. // A thread-local variable cannot be imported.
  1454. SafeToInline = !VD->getTLSKind();
  1455. return SafeToInline;
  1456. }
  1457. // Make sure we're not referencing non-imported vars or functions.
  1458. bool VisitDeclRefExpr(DeclRefExpr *E) {
  1459. ValueDecl *VD = E->getDecl();
  1460. if (isa<FunctionDecl>(VD))
  1461. SafeToInline = VD->hasAttr<DLLImportAttr>();
  1462. else if (VarDecl *V = dyn_cast<VarDecl>(VD))
  1463. SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
  1464. return SafeToInline;
  1465. }
  1466. bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  1467. SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
  1468. return SafeToInline;
  1469. }
  1470. bool VisitCXXNewExpr(CXXNewExpr *E) {
  1471. SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
  1472. return SafeToInline;
  1473. }
  1474. };
  1475. }
  1476. // isTriviallyRecursive - Check if this function calls another
  1477. // decl that, because of the asm attribute or the other decl being a builtin,
  1478. // ends up pointing to itself.
  1479. bool
  1480. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  1481. StringRef Name;
  1482. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  1483. // asm labels are a special kind of mangling we have to support.
  1484. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1485. if (!Attr)
  1486. return false;
  1487. Name = Attr->getLabel();
  1488. } else {
  1489. Name = FD->getName();
  1490. }
  1491. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  1492. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  1493. return Walker.Result;
  1494. }
  1495. bool
  1496. CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  1497. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  1498. return true;
  1499. const auto *F = cast<FunctionDecl>(GD.getDecl());
  1500. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  1501. return false;
  1502. if (F->hasAttr<DLLImportAttr>()) {
  1503. // Check whether it would be safe to inline this dllimport function.
  1504. DLLImportFunctionVisitor Visitor;
  1505. Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
  1506. if (!Visitor.SafeToInline)
  1507. return false;
  1508. }
  1509. // PR9614. Avoid cases where the source code is lying to us. An available
  1510. // externally function should have an equivalent function somewhere else,
  1511. // but a function that calls itself is clearly not equivalent to the real
  1512. // implementation.
  1513. // This happens in glibc's btowc and in some configure checks.
  1514. return !isTriviallyRecursive(F);
  1515. }
  1516. /// If the type for the method's class was generated by
  1517. /// CGDebugInfo::createContextChain(), the cache contains only a
  1518. /// limited DIType without any declarations. Since EmitFunctionStart()
  1519. /// needs to find the canonical declaration for each method, we need
  1520. /// to construct the complete type prior to emitting the method.
  1521. void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
  1522. if (!D->isInstance())
  1523. return;
  1524. if (CGDebugInfo *DI = getModuleDebugInfo())
  1525. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
  1526. const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
  1527. DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
  1528. }
  1529. }
  1530. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  1531. const auto *D = cast<ValueDecl>(GD.getDecl());
  1532. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  1533. Context.getSourceManager(),
  1534. "Generating code for declaration");
  1535. if (isa<FunctionDecl>(D)) {
  1536. // At -O0, don't generate IR for functions with available_externally
  1537. // linkage.
  1538. if (!shouldEmitFunction(GD))
  1539. return;
  1540. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  1541. CompleteDIClassType(Method);
  1542. // Make sure to emit the definition(s) before we emit the thunks.
  1543. // This is necessary for the generation of certain thunks.
  1544. if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
  1545. ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
  1546. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
  1547. ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
  1548. else
  1549. EmitGlobalFunctionDefinition(GD, GV);
  1550. if (Method->isVirtual())
  1551. getVTables().EmitThunks(GD);
  1552. return;
  1553. }
  1554. return EmitGlobalFunctionDefinition(GD, GV);
  1555. }
  1556. if (const auto *VD = dyn_cast<VarDecl>(D))
  1557. return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
  1558. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1559. }
  1560. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1561. llvm::Function *NewFn);
  1562. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  1563. /// module, create and return an llvm Function with the specified type. If there
  1564. /// is something in the module with the specified name, return it potentially
  1565. /// bitcasted to the right type.
  1566. ///
  1567. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1568. /// to set the attributes on the function when it is first created.
  1569. llvm::Constant *
  1570. CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
  1571. llvm::Type *Ty,
  1572. GlobalDecl GD, bool ForVTable,
  1573. bool DontDefer, bool IsThunk,
  1574. llvm::AttributeSet ExtraAttrs,
  1575. bool IsForDefinition) {
  1576. const Decl *D = GD.getDecl();
  1577. // Lookup the entry, lazily creating it if necessary.
  1578. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1579. if (Entry) {
  1580. if (WeakRefReferences.erase(Entry)) {
  1581. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  1582. if (FD && !FD->hasAttr<WeakAttr>())
  1583. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1584. }
  1585. // Handle dropped DLL attributes.
  1586. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1587. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1588. // If there are two attempts to define the same mangled name, issue an
  1589. // error.
  1590. if (IsForDefinition && !Entry->isDeclaration()) {
  1591. GlobalDecl OtherGD;
  1592. // Check that GD is not yet in DiagnosedConflictingDefinitions is required
  1593. // to make sure that we issue an error only once.
  1594. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  1595. (GD.getCanonicalDecl().getDecl() !=
  1596. OtherGD.getCanonicalDecl().getDecl()) &&
  1597. DiagnosedConflictingDefinitions.insert(GD).second) {
  1598. getDiags().Report(D->getLocation(),
  1599. diag::err_duplicate_mangled_name);
  1600. getDiags().Report(OtherGD.getDecl()->getLocation(),
  1601. diag::note_previous_definition);
  1602. }
  1603. }
  1604. if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
  1605. (Entry->getType()->getElementType() == Ty)) {
  1606. return Entry;
  1607. }
  1608. // Make sure the result is of the correct type.
  1609. // (If function is requested for a definition, we always need to create a new
  1610. // function, not just return a bitcast.)
  1611. if (!IsForDefinition)
  1612. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  1613. }
  1614. // This function doesn't have a complete type (for example, the return
  1615. // type is an incomplete struct). Use a fake type instead, and make
  1616. // sure not to try to set attributes.
  1617. bool IsIncompleteFunction = false;
  1618. llvm::FunctionType *FTy;
  1619. if (isa<llvm::FunctionType>(Ty)) {
  1620. FTy = cast<llvm::FunctionType>(Ty);
  1621. } else {
  1622. FTy = llvm::FunctionType::get(VoidTy, false);
  1623. IsIncompleteFunction = true;
  1624. }
  1625. llvm::Function *F =
  1626. llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
  1627. Entry ? StringRef() : MangledName, &getModule());
  1628. // If we already created a function with the same mangled name (but different
  1629. // type) before, take its name and add it to the list of functions to be
  1630. // replaced with F at the end of CodeGen.
  1631. //
  1632. // This happens if there is a prototype for a function (e.g. "int f()") and
  1633. // then a definition of a different type (e.g. "int f(int x)").
  1634. if (Entry) {
  1635. F->takeName(Entry);
  1636. // This might be an implementation of a function without a prototype, in
  1637. // which case, try to do special replacement of calls which match the new
  1638. // prototype. The really key thing here is that we also potentially drop
  1639. // arguments from the call site so as to make a direct call, which makes the
  1640. // inliner happier and suppresses a number of optimizer warnings (!) about
  1641. // dropping arguments.
  1642. if (!Entry->use_empty()) {
  1643. ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
  1644. Entry->removeDeadConstantUsers();
  1645. }
  1646. llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
  1647. F, Entry->getType()->getElementType()->getPointerTo());
  1648. addGlobalValReplacement(Entry, BC);
  1649. }
  1650. assert(F->getName() == MangledName && "name was uniqued!");
  1651. if (D)
  1652. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
  1653. if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
  1654. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
  1655. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  1656. llvm::AttributeSet::get(VMContext,
  1657. llvm::AttributeSet::FunctionIndex,
  1658. B));
  1659. }
  1660. if (!DontDefer) {
  1661. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  1662. // each other bottoming out with the base dtor. Therefore we emit non-base
  1663. // dtors on usage, even if there is no dtor definition in the TU.
  1664. if (D && isa<CXXDestructorDecl>(D) &&
  1665. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  1666. GD.getDtorType()))
  1667. addDeferredDeclToEmit(F, GD);
  1668. // This is the first use or definition of a mangled name. If there is a
  1669. // deferred decl with this name, remember that we need to emit it at the end
  1670. // of the file.
  1671. auto DDI = DeferredDecls.find(MangledName);
  1672. if (DDI != DeferredDecls.end()) {
  1673. // Move the potentially referenced deferred decl to the
  1674. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  1675. // don't need it anymore).
  1676. addDeferredDeclToEmit(F, DDI->second);
  1677. DeferredDecls.erase(DDI);
  1678. // Otherwise, there are cases we have to worry about where we're
  1679. // using a declaration for which we must emit a definition but where
  1680. // we might not find a top-level definition:
  1681. // - member functions defined inline in their classes
  1682. // - friend functions defined inline in some class
  1683. // - special member functions with implicit definitions
  1684. // If we ever change our AST traversal to walk into class methods,
  1685. // this will be unnecessary.
  1686. //
  1687. // We also don't emit a definition for a function if it's going to be an
  1688. // entry in a vtable, unless it's already marked as used.
  1689. } else if (getLangOpts().CPlusPlus && D) {
  1690. // Look for a declaration that's lexically in a record.
  1691. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  1692. FD = FD->getPreviousDecl()) {
  1693. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  1694. if (FD->doesThisDeclarationHaveABody()) {
  1695. addDeferredDeclToEmit(F, GD.getWithDecl(FD));
  1696. break;
  1697. }
  1698. }
  1699. }
  1700. }
  1701. }
  1702. // Make sure the result is of the requested type.
  1703. if (!IsIncompleteFunction) {
  1704. assert(F->getType()->getElementType() == Ty);
  1705. return F;
  1706. }
  1707. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1708. return llvm::ConstantExpr::getBitCast(F, PTy);
  1709. }
  1710. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  1711. /// non-null, then this function will use the specified type if it has to
  1712. /// create it (this occurs when we see a definition of the function).
  1713. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  1714. llvm::Type *Ty,
  1715. bool ForVTable,
  1716. bool DontDefer,
  1717. bool IsForDefinition) {
  1718. // If there was no specific requested type, just convert it now.
  1719. if (!Ty) {
  1720. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  1721. auto CanonTy = Context.getCanonicalType(FD->getType());
  1722. Ty = getTypes().ConvertFunctionType(CanonTy, FD);
  1723. }
  1724. StringRef MangledName = getMangledName(GD);
  1725. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
  1726. /*IsThunk=*/false, llvm::AttributeSet(),
  1727. IsForDefinition);
  1728. }
  1729. /// CreateRuntimeFunction - Create a new runtime function with the specified
  1730. /// type and name.
  1731. llvm::Constant *
  1732. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
  1733. StringRef Name,
  1734. llvm::AttributeSet ExtraAttrs) {
  1735. llvm::Constant *C =
  1736. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1737. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  1738. if (auto *F = dyn_cast<llvm::Function>(C))
  1739. if (F->empty())
  1740. F->setCallingConv(getRuntimeCC());
  1741. return C;
  1742. }
  1743. /// CreateBuiltinFunction - Create a new builtin function with the specified
  1744. /// type and name.
  1745. llvm::Constant *
  1746. CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
  1747. StringRef Name,
  1748. llvm::AttributeSet ExtraAttrs) {
  1749. llvm::Constant *C =
  1750. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1751. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  1752. if (auto *F = dyn_cast<llvm::Function>(C))
  1753. if (F->empty())
  1754. F->setCallingConv(getBuiltinCC());
  1755. return C;
  1756. }
  1757. /// isTypeConstant - Determine whether an object of this type can be emitted
  1758. /// as a constant.
  1759. ///
  1760. /// If ExcludeCtor is true, the duration when the object's constructor runs
  1761. /// will not be considered. The caller will need to verify that the object is
  1762. /// not written to during its construction.
  1763. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  1764. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  1765. return false;
  1766. if (Context.getLangOpts().CPlusPlus) {
  1767. if (const CXXRecordDecl *Record
  1768. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  1769. return ExcludeCtor && !Record->hasMutableFields() &&
  1770. Record->hasTrivialDestructor();
  1771. }
  1772. return true;
  1773. }
  1774. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  1775. /// create and return an llvm GlobalVariable with the specified type. If there
  1776. /// is something in the module with the specified name, return it potentially
  1777. /// bitcasted to the right type.
  1778. ///
  1779. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1780. /// to set the attributes on the global when it is first created.
  1781. ///
  1782. /// If IsForDefinition is true, it is guranteed that an actual global with
  1783. /// type Ty will be returned, not conversion of a variable with the same
  1784. /// mangled name but some other type.
  1785. llvm::Constant *
  1786. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  1787. llvm::PointerType *Ty,
  1788. const VarDecl *D,
  1789. bool IsForDefinition) {
  1790. // Lookup the entry, lazily creating it if necessary.
  1791. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1792. if (Entry) {
  1793. if (WeakRefReferences.erase(Entry)) {
  1794. if (D && !D->hasAttr<WeakAttr>())
  1795. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1796. }
  1797. // Handle dropped DLL attributes.
  1798. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1799. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1800. if (Entry->getType() == Ty)
  1801. return Entry;
  1802. // If there are two attempts to define the same mangled name, issue an
  1803. // error.
  1804. if (IsForDefinition && !Entry->isDeclaration()) {
  1805. GlobalDecl OtherGD;
  1806. const VarDecl *OtherD;
  1807. // Check that D is not yet in DiagnosedConflictingDefinitions is required
  1808. // to make sure that we issue an error only once.
  1809. if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
  1810. (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
  1811. (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
  1812. OtherD->hasInit() &&
  1813. DiagnosedConflictingDefinitions.insert(D).second) {
  1814. getDiags().Report(D->getLocation(),
  1815. diag::err_duplicate_mangled_name);
  1816. getDiags().Report(OtherGD.getDecl()->getLocation(),
  1817. diag::note_previous_definition);
  1818. }
  1819. }
  1820. // Make sure the result is of the correct type.
  1821. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
  1822. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  1823. // (If global is requested for a definition, we always need to create a new
  1824. // global, not just return a bitcast.)
  1825. if (!IsForDefinition)
  1826. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  1827. }
  1828. unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
  1829. auto *GV = new llvm::GlobalVariable(
  1830. getModule(), Ty->getElementType(), false,
  1831. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  1832. llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  1833. // If we already created a global with the same mangled name (but different
  1834. // type) before, take its name and remove it from its parent.
  1835. if (Entry) {
  1836. GV->takeName(Entry);
  1837. if (!Entry->use_empty()) {
  1838. llvm::Constant *NewPtrForOldDecl =
  1839. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1840. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1841. }
  1842. Entry->eraseFromParent();
  1843. }
  1844. // This is the first use or definition of a mangled name. If there is a
  1845. // deferred decl with this name, remember that we need to emit it at the end
  1846. // of the file.
  1847. auto DDI = DeferredDecls.find(MangledName);
  1848. if (DDI != DeferredDecls.end()) {
  1849. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1850. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1851. addDeferredDeclToEmit(GV, DDI->second);
  1852. DeferredDecls.erase(DDI);
  1853. }
  1854. // Handle things which are present even on external declarations.
  1855. if (D) {
  1856. // FIXME: This code is overly simple and should be merged with other global
  1857. // handling.
  1858. GV->setConstant(isTypeConstant(D->getType(), false));
  1859. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1860. setLinkageAndVisibilityForGV(GV, D);
  1861. if (D->getTLSKind()) {
  1862. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  1863. CXXThreadLocals.push_back(D);
  1864. setTLSMode(GV, *D);
  1865. }
  1866. // If required by the ABI, treat declarations of static data members with
  1867. // inline initializers as definitions.
  1868. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  1869. EmitGlobalVarDefinition(D);
  1870. }
  1871. // Handle XCore specific ABI requirements.
  1872. if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
  1873. D->getLanguageLinkage() == CLanguageLinkage &&
  1874. D->getType().isConstant(Context) &&
  1875. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  1876. GV->setSection(".cp.rodata");
  1877. }
  1878. if (AddrSpace != Ty->getAddressSpace())
  1879. return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
  1880. return GV;
  1881. }
  1882. llvm::Constant *
  1883. CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
  1884. bool IsForDefinition) {
  1885. if (isa<CXXConstructorDecl>(GD.getDecl()))
  1886. return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()),
  1887. getFromCtorType(GD.getCtorType()),
  1888. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  1889. /*DontDefer=*/false, IsForDefinition);
  1890. else if (isa<CXXDestructorDecl>(GD.getDecl()))
  1891. return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()),
  1892. getFromDtorType(GD.getDtorType()),
  1893. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  1894. /*DontDefer=*/false, IsForDefinition);
  1895. else if (isa<CXXMethodDecl>(GD.getDecl())) {
  1896. auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
  1897. cast<CXXMethodDecl>(GD.getDecl()));
  1898. auto Ty = getTypes().GetFunctionType(*FInfo);
  1899. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  1900. IsForDefinition);
  1901. } else if (isa<FunctionDecl>(GD.getDecl())) {
  1902. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1903. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  1904. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  1905. IsForDefinition);
  1906. } else
  1907. return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()), /*Ty=*/nullptr,
  1908. IsForDefinition);
  1909. }
  1910. llvm::GlobalVariable *
  1911. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  1912. llvm::Type *Ty,
  1913. llvm::GlobalValue::LinkageTypes Linkage) {
  1914. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  1915. llvm::GlobalVariable *OldGV = nullptr;
  1916. if (GV) {
  1917. // Check if the variable has the right type.
  1918. if (GV->getType()->getElementType() == Ty)
  1919. return GV;
  1920. // Because C++ name mangling, the only way we can end up with an already
  1921. // existing global with the same name is if it has been declared extern "C".
  1922. assert(GV->isDeclaration() && "Declaration has wrong type!");
  1923. OldGV = GV;
  1924. }
  1925. // Create a new variable.
  1926. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  1927. Linkage, nullptr, Name);
  1928. if (OldGV) {
  1929. // Replace occurrences of the old variable if needed.
  1930. GV->takeName(OldGV);
  1931. if (!OldGV->use_empty()) {
  1932. llvm::Constant *NewPtrForOldDecl =
  1933. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  1934. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  1935. }
  1936. OldGV->eraseFromParent();
  1937. }
  1938. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  1939. !GV->hasAvailableExternallyLinkage())
  1940. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1941. return GV;
  1942. }
  1943. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  1944. /// given global variable. If Ty is non-null and if the global doesn't exist,
  1945. /// then it will be created with the specified type instead of whatever the
  1946. /// normal requested type would be. If IsForDefinition is true, it is guranteed
  1947. /// that an actual global with type Ty will be returned, not conversion of a
  1948. /// variable with the same mangled name but some other type.
  1949. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  1950. llvm::Type *Ty,
  1951. bool IsForDefinition) {
  1952. assert(D->hasGlobalStorage() && "Not a global variable");
  1953. QualType ASTTy = D->getType();
  1954. if (!Ty)
  1955. Ty = getTypes().ConvertTypeForMem(ASTTy);
  1956. llvm::PointerType *PTy =
  1957. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  1958. StringRef MangledName = getMangledName(D);
  1959. return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
  1960. }
  1961. /// CreateRuntimeVariable - Create a new runtime global variable with the
  1962. /// specified type and name.
  1963. llvm::Constant *
  1964. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  1965. StringRef Name) {
  1966. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
  1967. }
  1968. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  1969. assert(!D->getInit() && "Cannot emit definite definitions here!");
  1970. StringRef MangledName = getMangledName(D);
  1971. llvm::GlobalValue *GV = GetGlobalValue(MangledName);
  1972. // We already have a definition, not declaration, with the same mangled name.
  1973. // Emitting of declaration is not required (and actually overwrites emitted
  1974. // definition).
  1975. if (GV && !GV->isDeclaration())
  1976. return;
  1977. // If we have not seen a reference to this variable yet, place it into the
  1978. // deferred declarations table to be emitted if needed later.
  1979. if (!MustBeEmitted(D) && !GV) {
  1980. DeferredDecls[MangledName] = D;
  1981. return;
  1982. }
  1983. // The tentative definition is the only definition.
  1984. EmitGlobalVarDefinition(D);
  1985. }
  1986. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  1987. return Context.toCharUnitsFromBits(
  1988. getDataLayout().getTypeStoreSizeInBits(Ty));
  1989. }
  1990. unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
  1991. unsigned AddrSpace) {
  1992. if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  1993. if (D->hasAttr<CUDAConstantAttr>())
  1994. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
  1995. else if (D->hasAttr<CUDASharedAttr>())
  1996. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
  1997. else
  1998. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
  1999. }
  2000. return AddrSpace;
  2001. }
  2002. template<typename SomeDecl>
  2003. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  2004. llvm::GlobalValue *GV) {
  2005. if (!getLangOpts().CPlusPlus)
  2006. return;
  2007. // Must have 'used' attribute, or else inline assembly can't rely on
  2008. // the name existing.
  2009. if (!D->template hasAttr<UsedAttr>())
  2010. return;
  2011. // Must have internal linkage and an ordinary name.
  2012. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  2013. return;
  2014. // Must be in an extern "C" context. Entities declared directly within
  2015. // a record are not extern "C" even if the record is in such a context.
  2016. const SomeDecl *First = D->getFirstDecl();
  2017. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  2018. return;
  2019. // OK, this is an internal linkage entity inside an extern "C" linkage
  2020. // specification. Make a note of that so we can give it the "expected"
  2021. // mangled name if nothing else is using that name.
  2022. std::pair<StaticExternCMap::iterator, bool> R =
  2023. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  2024. // If we have multiple internal linkage entities with the same name
  2025. // in extern "C" regions, none of them gets that name.
  2026. if (!R.second)
  2027. R.first->second = nullptr;
  2028. }
  2029. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  2030. if (!CGM.supportsCOMDAT())
  2031. return false;
  2032. if (D.hasAttr<SelectAnyAttr>())
  2033. return true;
  2034. GVALinkage Linkage;
  2035. if (auto *VD = dyn_cast<VarDecl>(&D))
  2036. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  2037. else
  2038. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  2039. switch (Linkage) {
  2040. case GVA_Internal:
  2041. case GVA_AvailableExternally:
  2042. case GVA_StrongExternal:
  2043. return false;
  2044. case GVA_DiscardableODR:
  2045. case GVA_StrongODR:
  2046. return true;
  2047. }
  2048. llvm_unreachable("No such linkage");
  2049. }
  2050. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  2051. llvm::GlobalObject &GO) {
  2052. if (!shouldBeInCOMDAT(*this, D))
  2053. return;
  2054. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  2055. }
  2056. /// Pass IsTentative as true if you want to create a tentative definition.
  2057. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
  2058. bool IsTentative) {
  2059. llvm::Constant *Init = nullptr;
  2060. QualType ASTTy = D->getType();
  2061. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2062. bool NeedsGlobalCtor = false;
  2063. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  2064. const VarDecl *InitDecl;
  2065. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  2066. // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
  2067. // as part of their declaration." Sema has already checked for
  2068. // error cases, so we just need to set Init to UndefValue.
  2069. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  2070. D->hasAttr<CUDASharedAttr>())
  2071. Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
  2072. else if (!InitExpr) {
  2073. // This is a tentative definition; tentative definitions are
  2074. // implicitly initialized with { 0 }.
  2075. //
  2076. // Note that tentative definitions are only emitted at the end of
  2077. // a translation unit, so they should never have incomplete
  2078. // type. In addition, EmitTentativeDefinition makes sure that we
  2079. // never attempt to emit a tentative definition if a real one
  2080. // exists. A use may still exists, however, so we still may need
  2081. // to do a RAUW.
  2082. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  2083. Init = EmitNullConstant(D->getType());
  2084. } else {
  2085. initializedGlobalDecl = GlobalDecl(D);
  2086. Init = EmitConstantInit(*InitDecl);
  2087. if (!Init) {
  2088. QualType T = InitExpr->getType();
  2089. if (D->getType()->isReferenceType())
  2090. T = D->getType();
  2091. if (getLangOpts().CPlusPlus) {
  2092. Init = EmitNullConstant(T);
  2093. NeedsGlobalCtor = true;
  2094. } else {
  2095. ErrorUnsupported(D, "static initializer");
  2096. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  2097. }
  2098. } else {
  2099. // We don't need an initializer, so remove the entry for the delayed
  2100. // initializer position (just in case this entry was delayed) if we
  2101. // also don't need to register a destructor.
  2102. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  2103. DelayedCXXInitPosition.erase(D);
  2104. }
  2105. }
  2106. llvm::Type* InitType = Init->getType();
  2107. llvm::Constant *Entry =
  2108. GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative);
  2109. // Strip off a bitcast if we got one back.
  2110. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  2111. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  2112. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  2113. // All zero index gep.
  2114. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  2115. Entry = CE->getOperand(0);
  2116. }
  2117. // Entry is now either a Function or GlobalVariable.
  2118. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  2119. // We have a definition after a declaration with the wrong type.
  2120. // We must make a new GlobalVariable* and update everything that used OldGV
  2121. // (a declaration or tentative definition) with the new GlobalVariable*
  2122. // (which will be a definition).
  2123. //
  2124. // This happens if there is a prototype for a global (e.g.
  2125. // "extern int x[];") and then a definition of a different type (e.g.
  2126. // "int x[10];"). This also happens when an initializer has a different type
  2127. // from the type of the global (this happens with unions).
  2128. if (!GV ||
  2129. GV->getType()->getElementType() != InitType ||
  2130. GV->getType()->getAddressSpace() !=
  2131. GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
  2132. // Move the old entry aside so that we'll create a new one.
  2133. Entry->setName(StringRef());
  2134. // Make a new global with the correct type, this is now guaranteed to work.
  2135. GV = cast<llvm::GlobalVariable>(
  2136. GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative));
  2137. // Replace all uses of the old global with the new global
  2138. llvm::Constant *NewPtrForOldDecl =
  2139. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2140. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2141. // Erase the old global, since it is no longer used.
  2142. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  2143. }
  2144. MaybeHandleStaticInExternC(D, GV);
  2145. if (D->hasAttr<AnnotateAttr>())
  2146. AddGlobalAnnotations(D, GV);
  2147. // Set the llvm linkage type as appropriate.
  2148. llvm::GlobalValue::LinkageTypes Linkage =
  2149. getLLVMLinkageVarDefinition(D, GV->isConstant());
  2150. // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
  2151. // the device. [...]"
  2152. // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
  2153. // __device__, declares a variable that: [...]
  2154. // Is accessible from all the threads within the grid and from the host
  2155. // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
  2156. // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
  2157. if (GV && LangOpts.CUDA) {
  2158. if (LangOpts.CUDAIsDevice) {
  2159. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
  2160. GV->setExternallyInitialized(true);
  2161. } else {
  2162. // Host-side shadows of external declarations of device-side
  2163. // global variables become internal definitions. These have to
  2164. // be internal in order to prevent name conflicts with global
  2165. // host variables with the same name in a different TUs.
  2166. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
  2167. Linkage = llvm::GlobalValue::InternalLinkage;
  2168. // Shadow variables and their properties must be registered
  2169. // with CUDA runtime.
  2170. unsigned Flags = 0;
  2171. if (!D->hasDefinition())
  2172. Flags |= CGCUDARuntime::ExternDeviceVar;
  2173. if (D->hasAttr<CUDAConstantAttr>())
  2174. Flags |= CGCUDARuntime::ConstantDeviceVar;
  2175. getCUDARuntime().registerDeviceVar(*GV, Flags);
  2176. } else if (D->hasAttr<CUDASharedAttr>())
  2177. // __shared__ variables are odd. Shadows do get created, but
  2178. // they are not registered with the CUDA runtime, so they
  2179. // can't really be used to access their device-side
  2180. // counterparts. It's not clear yet whether it's nvcc's bug or
  2181. // a feature, but we've got to do the same for compatibility.
  2182. Linkage = llvm::GlobalValue::InternalLinkage;
  2183. }
  2184. }
  2185. GV->setInitializer(Init);
  2186. // If it is safe to mark the global 'constant', do so now.
  2187. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  2188. isTypeConstant(D->getType(), true));
  2189. // If it is in a read-only section, mark it 'constant'.
  2190. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  2191. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  2192. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  2193. GV->setConstant(true);
  2194. }
  2195. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2196. // On Darwin, if the normal linkage of a C++ thread_local variable is
  2197. // LinkOnce or Weak, we keep the normal linkage to prevent multiple
  2198. // copies within a linkage unit; otherwise, the backing variable has
  2199. // internal linkage and all accesses should just be calls to the
  2200. // Itanium-specified entry point, which has the normal linkage of the
  2201. // variable. This is to preserve the ability to change the implementation
  2202. // behind the scenes.
  2203. if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
  2204. Context.getTargetInfo().getTriple().isOSDarwin() &&
  2205. !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
  2206. !llvm::GlobalVariable::isWeakLinkage(Linkage))
  2207. Linkage = llvm::GlobalValue::InternalLinkage;
  2208. GV->setLinkage(Linkage);
  2209. if (D->hasAttr<DLLImportAttr>())
  2210. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  2211. else if (D->hasAttr<DLLExportAttr>())
  2212. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  2213. else
  2214. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  2215. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  2216. // common vars aren't constant even if declared const.
  2217. GV->setConstant(false);
  2218. setNonAliasAttributes(D, GV);
  2219. if (D->getTLSKind() && !GV->isThreadLocal()) {
  2220. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2221. CXXThreadLocals.push_back(D);
  2222. setTLSMode(GV, *D);
  2223. }
  2224. maybeSetTrivialComdat(*D, *GV);
  2225. // Emit the initializer function if necessary.
  2226. if (NeedsGlobalCtor || NeedsGlobalDtor)
  2227. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  2228. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  2229. // Emit global variable debug information.
  2230. if (CGDebugInfo *DI = getModuleDebugInfo())
  2231. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  2232. DI->EmitGlobalVariable(GV, D);
  2233. }
  2234. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  2235. CodeGenModule &CGM, const VarDecl *D,
  2236. bool NoCommon) {
  2237. // Don't give variables common linkage if -fno-common was specified unless it
  2238. // was overridden by a NoCommon attribute.
  2239. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  2240. return true;
  2241. // C11 6.9.2/2:
  2242. // A declaration of an identifier for an object that has file scope without
  2243. // an initializer, and without a storage-class specifier or with the
  2244. // storage-class specifier static, constitutes a tentative definition.
  2245. if (D->getInit() || D->hasExternalStorage())
  2246. return true;
  2247. // A variable cannot be both common and exist in a section.
  2248. if (D->hasAttr<SectionAttr>())
  2249. return true;
  2250. // Thread local vars aren't considered common linkage.
  2251. if (D->getTLSKind())
  2252. return true;
  2253. // Tentative definitions marked with WeakImportAttr are true definitions.
  2254. if (D->hasAttr<WeakImportAttr>())
  2255. return true;
  2256. // A variable cannot be both common and exist in a comdat.
  2257. if (shouldBeInCOMDAT(CGM, *D))
  2258. return true;
  2259. // Declarations with a required alignment do not have common linakge in MSVC
  2260. // mode.
  2261. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2262. if (D->hasAttr<AlignedAttr>())
  2263. return true;
  2264. QualType VarType = D->getType();
  2265. if (Context.isAlignmentRequired(VarType))
  2266. return true;
  2267. if (const auto *RT = VarType->getAs<RecordType>()) {
  2268. const RecordDecl *RD = RT->getDecl();
  2269. for (const FieldDecl *FD : RD->fields()) {
  2270. if (FD->isBitField())
  2271. continue;
  2272. if (FD->hasAttr<AlignedAttr>())
  2273. return true;
  2274. if (Context.isAlignmentRequired(FD->getType()))
  2275. return true;
  2276. }
  2277. }
  2278. }
  2279. return false;
  2280. }
  2281. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  2282. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  2283. if (Linkage == GVA_Internal)
  2284. return llvm::Function::InternalLinkage;
  2285. if (D->hasAttr<WeakAttr>()) {
  2286. if (IsConstantVariable)
  2287. return llvm::GlobalVariable::WeakODRLinkage;
  2288. else
  2289. return llvm::GlobalVariable::WeakAnyLinkage;
  2290. }
  2291. // We are guaranteed to have a strong definition somewhere else,
  2292. // so we can use available_externally linkage.
  2293. if (Linkage == GVA_AvailableExternally)
  2294. return llvm::Function::AvailableExternallyLinkage;
  2295. // Note that Apple's kernel linker doesn't support symbol
  2296. // coalescing, so we need to avoid linkonce and weak linkages there.
  2297. // Normally, this means we just map to internal, but for explicit
  2298. // instantiations we'll map to external.
  2299. // In C++, the compiler has to emit a definition in every translation unit
  2300. // that references the function. We should use linkonce_odr because
  2301. // a) if all references in this translation unit are optimized away, we
  2302. // don't need to codegen it. b) if the function persists, it needs to be
  2303. // merged with other definitions. c) C++ has the ODR, so we know the
  2304. // definition is dependable.
  2305. if (Linkage == GVA_DiscardableODR)
  2306. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  2307. : llvm::Function::InternalLinkage;
  2308. // An explicit instantiation of a template has weak linkage, since
  2309. // explicit instantiations can occur in multiple translation units
  2310. // and must all be equivalent. However, we are not allowed to
  2311. // throw away these explicit instantiations.
  2312. if (Linkage == GVA_StrongODR)
  2313. return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
  2314. : llvm::Function::ExternalLinkage;
  2315. // C++ doesn't have tentative definitions and thus cannot have common
  2316. // linkage.
  2317. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  2318. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  2319. CodeGenOpts.NoCommon))
  2320. return llvm::GlobalVariable::CommonLinkage;
  2321. // selectany symbols are externally visible, so use weak instead of
  2322. // linkonce. MSVC optimizes away references to const selectany globals, so
  2323. // all definitions should be the same and ODR linkage should be used.
  2324. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  2325. if (D->hasAttr<SelectAnyAttr>())
  2326. return llvm::GlobalVariable::WeakODRLinkage;
  2327. // Otherwise, we have strong external linkage.
  2328. assert(Linkage == GVA_StrongExternal);
  2329. return llvm::GlobalVariable::ExternalLinkage;
  2330. }
  2331. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  2332. const VarDecl *VD, bool IsConstant) {
  2333. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  2334. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  2335. }
  2336. /// Replace the uses of a function that was declared with a non-proto type.
  2337. /// We want to silently drop extra arguments from call sites
  2338. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  2339. llvm::Function *newFn) {
  2340. // Fast path.
  2341. if (old->use_empty()) return;
  2342. llvm::Type *newRetTy = newFn->getReturnType();
  2343. SmallVector<llvm::Value*, 4> newArgs;
  2344. SmallVector<llvm::OperandBundleDef, 1> newBundles;
  2345. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  2346. ui != ue; ) {
  2347. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  2348. llvm::User *user = use->getUser();
  2349. // Recognize and replace uses of bitcasts. Most calls to
  2350. // unprototyped functions will use bitcasts.
  2351. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  2352. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  2353. replaceUsesOfNonProtoConstant(bitcast, newFn);
  2354. continue;
  2355. }
  2356. // Recognize calls to the function.
  2357. llvm::CallSite callSite(user);
  2358. if (!callSite) continue;
  2359. if (!callSite.isCallee(&*use)) continue;
  2360. // If the return types don't match exactly, then we can't
  2361. // transform this call unless it's dead.
  2362. if (callSite->getType() != newRetTy && !callSite->use_empty())
  2363. continue;
  2364. // Get the call site's attribute list.
  2365. SmallVector<llvm::AttributeSet, 8> newAttrs;
  2366. llvm::AttributeSet oldAttrs = callSite.getAttributes();
  2367. // Collect any return attributes from the call.
  2368. if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
  2369. newAttrs.push_back(
  2370. llvm::AttributeSet::get(newFn->getContext(),
  2371. oldAttrs.getRetAttributes()));
  2372. // If the function was passed too few arguments, don't transform.
  2373. unsigned newNumArgs = newFn->arg_size();
  2374. if (callSite.arg_size() < newNumArgs) continue;
  2375. // If extra arguments were passed, we silently drop them.
  2376. // If any of the types mismatch, we don't transform.
  2377. unsigned argNo = 0;
  2378. bool dontTransform = false;
  2379. for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
  2380. ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
  2381. if (callSite.getArgument(argNo)->getType() != ai->getType()) {
  2382. dontTransform = true;
  2383. break;
  2384. }
  2385. // Add any parameter attributes.
  2386. if (oldAttrs.hasAttributes(argNo + 1))
  2387. newAttrs.
  2388. push_back(llvm::
  2389. AttributeSet::get(newFn->getContext(),
  2390. oldAttrs.getParamAttributes(argNo + 1)));
  2391. }
  2392. if (dontTransform)
  2393. continue;
  2394. if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
  2395. newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
  2396. oldAttrs.getFnAttributes()));
  2397. // Okay, we can transform this. Create the new call instruction and copy
  2398. // over the required information.
  2399. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  2400. // Copy over any operand bundles.
  2401. callSite.getOperandBundlesAsDefs(newBundles);
  2402. llvm::CallSite newCall;
  2403. if (callSite.isCall()) {
  2404. newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
  2405. callSite.getInstruction());
  2406. } else {
  2407. auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
  2408. newCall = llvm::InvokeInst::Create(newFn,
  2409. oldInvoke->getNormalDest(),
  2410. oldInvoke->getUnwindDest(),
  2411. newArgs, newBundles, "",
  2412. callSite.getInstruction());
  2413. }
  2414. newArgs.clear(); // for the next iteration
  2415. if (!newCall->getType()->isVoidTy())
  2416. newCall->takeName(callSite.getInstruction());
  2417. newCall.setAttributes(
  2418. llvm::AttributeSet::get(newFn->getContext(), newAttrs));
  2419. newCall.setCallingConv(callSite.getCallingConv());
  2420. // Finally, remove the old call, replacing any uses with the new one.
  2421. if (!callSite->use_empty())
  2422. callSite->replaceAllUsesWith(newCall.getInstruction());
  2423. // Copy debug location attached to CI.
  2424. if (callSite->getDebugLoc())
  2425. newCall->setDebugLoc(callSite->getDebugLoc());
  2426. callSite->eraseFromParent();
  2427. }
  2428. }
  2429. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  2430. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  2431. /// existing call uses of the old function in the module, this adjusts them to
  2432. /// call the new function directly.
  2433. ///
  2434. /// This is not just a cleanup: the always_inline pass requires direct calls to
  2435. /// functions to be able to inline them. If there is a bitcast in the way, it
  2436. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  2437. /// run at -O0.
  2438. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  2439. llvm::Function *NewFn) {
  2440. // If we're redefining a global as a function, don't transform it.
  2441. if (!isa<llvm::Function>(Old)) return;
  2442. replaceUsesOfNonProtoConstant(Old, NewFn);
  2443. }
  2444. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  2445. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  2446. // If we have a definition, this might be a deferred decl. If the
  2447. // instantiation is explicit, make sure we emit it at the end.
  2448. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  2449. GetAddrOfGlobalVar(VD);
  2450. EmitTopLevelDecl(VD);
  2451. }
  2452. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  2453. llvm::GlobalValue *GV) {
  2454. const auto *D = cast<FunctionDecl>(GD.getDecl());
  2455. // Compute the function info and LLVM type.
  2456. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2457. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2458. // Get or create the prototype for the function.
  2459. if (!GV || (GV->getType()->getElementType() != Ty))
  2460. GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
  2461. /*DontDefer=*/true,
  2462. /*IsForDefinition=*/true));
  2463. // Already emitted.
  2464. if (!GV->isDeclaration())
  2465. return;
  2466. // We need to set linkage and visibility on the function before
  2467. // generating code for it because various parts of IR generation
  2468. // want to propagate this information down (e.g. to local static
  2469. // declarations).
  2470. auto *Fn = cast<llvm::Function>(GV);
  2471. setFunctionLinkage(GD, Fn);
  2472. setFunctionDLLStorageClass(GD, Fn);
  2473. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  2474. setGlobalVisibility(Fn, D);
  2475. MaybeHandleStaticInExternC(D, Fn);
  2476. maybeSetTrivialComdat(*D, *Fn);
  2477. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  2478. setFunctionDefinitionAttributes(D, Fn);
  2479. SetLLVMFunctionAttributesForDefinition(D, Fn);
  2480. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  2481. AddGlobalCtor(Fn, CA->getPriority());
  2482. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  2483. AddGlobalDtor(Fn, DA->getPriority());
  2484. if (D->hasAttr<AnnotateAttr>())
  2485. AddGlobalAnnotations(D, Fn);
  2486. }
  2487. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  2488. const auto *D = cast<ValueDecl>(GD.getDecl());
  2489. const AliasAttr *AA = D->getAttr<AliasAttr>();
  2490. assert(AA && "Not an alias?");
  2491. StringRef MangledName = getMangledName(GD);
  2492. if (AA->getAliasee() == MangledName) {
  2493. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  2494. return;
  2495. }
  2496. // If there is a definition in the module, then it wins over the alias.
  2497. // This is dubious, but allow it to be safe. Just ignore the alias.
  2498. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2499. if (Entry && !Entry->isDeclaration())
  2500. return;
  2501. Aliases.push_back(GD);
  2502. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  2503. // Create a reference to the named value. This ensures that it is emitted
  2504. // if a deferred decl.
  2505. llvm::Constant *Aliasee;
  2506. if (isa<llvm::FunctionType>(DeclTy))
  2507. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  2508. /*ForVTable=*/false);
  2509. else
  2510. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  2511. llvm::PointerType::getUnqual(DeclTy),
  2512. /*D=*/nullptr);
  2513. // Create the new alias itself, but don't set a name yet.
  2514. auto *GA = llvm::GlobalAlias::create(
  2515. DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
  2516. if (Entry) {
  2517. if (GA->getAliasee() == Entry) {
  2518. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  2519. return;
  2520. }
  2521. assert(Entry->isDeclaration());
  2522. // If there is a declaration in the module, then we had an extern followed
  2523. // by the alias, as in:
  2524. // extern int test6();
  2525. // ...
  2526. // int test6() __attribute__((alias("test7")));
  2527. //
  2528. // Remove it and replace uses of it with the alias.
  2529. GA->takeName(Entry);
  2530. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  2531. Entry->getType()));
  2532. Entry->eraseFromParent();
  2533. } else {
  2534. GA->setName(MangledName);
  2535. }
  2536. // Set attributes which are particular to an alias; this is a
  2537. // specialization of the attributes which may be set on a global
  2538. // variable/function.
  2539. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  2540. D->isWeakImported()) {
  2541. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  2542. }
  2543. if (const auto *VD = dyn_cast<VarDecl>(D))
  2544. if (VD->getTLSKind())
  2545. setTLSMode(GA, *VD);
  2546. setAliasAttributes(D, GA);
  2547. }
  2548. void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
  2549. const auto *D = cast<ValueDecl>(GD.getDecl());
  2550. const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
  2551. assert(IFA && "Not an ifunc?");
  2552. StringRef MangledName = getMangledName(GD);
  2553. if (IFA->getResolver() == MangledName) {
  2554. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  2555. return;
  2556. }
  2557. // Report an error if some definition overrides ifunc.
  2558. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2559. if (Entry && !Entry->isDeclaration()) {
  2560. GlobalDecl OtherGD;
  2561. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  2562. DiagnosedConflictingDefinitions.insert(GD).second) {
  2563. Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
  2564. Diags.Report(OtherGD.getDecl()->getLocation(),
  2565. diag::note_previous_definition);
  2566. }
  2567. return;
  2568. }
  2569. Aliases.push_back(GD);
  2570. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  2571. llvm::Constant *Resolver =
  2572. GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
  2573. /*ForVTable=*/false);
  2574. llvm::GlobalIFunc *GIF =
  2575. llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
  2576. "", Resolver, &getModule());
  2577. if (Entry) {
  2578. if (GIF->getResolver() == Entry) {
  2579. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  2580. return;
  2581. }
  2582. assert(Entry->isDeclaration());
  2583. // If there is a declaration in the module, then we had an extern followed
  2584. // by the ifunc, as in:
  2585. // extern int test();
  2586. // ...
  2587. // int test() __attribute__((ifunc("resolver")));
  2588. //
  2589. // Remove it and replace uses of it with the ifunc.
  2590. GIF->takeName(Entry);
  2591. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
  2592. Entry->getType()));
  2593. Entry->eraseFromParent();
  2594. } else
  2595. GIF->setName(MangledName);
  2596. SetCommonAttributes(D, GIF);
  2597. }
  2598. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  2599. ArrayRef<llvm::Type*> Tys) {
  2600. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  2601. Tys);
  2602. }
  2603. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  2604. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  2605. const StringLiteral *Literal, bool TargetIsLSB,
  2606. bool &IsUTF16, unsigned &StringLength) {
  2607. StringRef String = Literal->getString();
  2608. unsigned NumBytes = String.size();
  2609. // Check for simple case.
  2610. if (!Literal->containsNonAsciiOrNull()) {
  2611. StringLength = NumBytes;
  2612. return *Map.insert(std::make_pair(String, nullptr)).first;
  2613. }
  2614. // Otherwise, convert the UTF8 literals into a string of shorts.
  2615. IsUTF16 = true;
  2616. SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  2617. const UTF8 *FromPtr = (const UTF8 *)String.data();
  2618. UTF16 *ToPtr = &ToBuf[0];
  2619. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  2620. &ToPtr, ToPtr + NumBytes,
  2621. strictConversion);
  2622. // ConvertUTF8toUTF16 returns the length in ToPtr.
  2623. StringLength = ToPtr - &ToBuf[0];
  2624. // Add an explicit null.
  2625. *ToPtr = 0;
  2626. return *Map.insert(std::make_pair(
  2627. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  2628. (StringLength + 1) * 2),
  2629. nullptr)).first;
  2630. }
  2631. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  2632. GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  2633. const StringLiteral *Literal, unsigned &StringLength) {
  2634. StringRef String = Literal->getString();
  2635. StringLength = String.size();
  2636. return *Map.insert(std::make_pair(String, nullptr)).first;
  2637. }
  2638. ConstantAddress
  2639. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  2640. unsigned StringLength = 0;
  2641. bool isUTF16 = false;
  2642. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2643. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  2644. getDataLayout().isLittleEndian(), isUTF16,
  2645. StringLength);
  2646. if (auto *C = Entry.second)
  2647. return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
  2648. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2649. llvm::Constant *Zeros[] = { Zero, Zero };
  2650. llvm::Value *V;
  2651. // If we don't already have it, get __CFConstantStringClassReference.
  2652. if (!CFConstantStringClassRef) {
  2653. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2654. Ty = llvm::ArrayType::get(Ty, 0);
  2655. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  2656. "__CFConstantStringClassReference");
  2657. // Decay array -> ptr
  2658. V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
  2659. CFConstantStringClassRef = V;
  2660. }
  2661. else
  2662. V = CFConstantStringClassRef;
  2663. QualType CFTy = getContext().getCFConstantStringType();
  2664. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  2665. llvm::Constant *Fields[4];
  2666. // Class pointer.
  2667. Fields[0] = cast<llvm::ConstantExpr>(V);
  2668. // Flags.
  2669. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  2670. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  2671. llvm::ConstantInt::get(Ty, 0x07C8);
  2672. // String pointer.
  2673. llvm::Constant *C = nullptr;
  2674. if (isUTF16) {
  2675. auto Arr = llvm::makeArrayRef(
  2676. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  2677. Entry.first().size() / 2);
  2678. C = llvm::ConstantDataArray::get(VMContext, Arr);
  2679. } else {
  2680. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  2681. }
  2682. // Note: -fwritable-strings doesn't make the backing store strings of
  2683. // CFStrings writable. (See <rdar://problem/10657500>)
  2684. auto *GV =
  2685. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  2686. llvm::GlobalValue::PrivateLinkage, C, ".str");
  2687. GV->setUnnamedAddr(true);
  2688. // Don't enforce the target's minimum global alignment, since the only use
  2689. // of the string is via this class initializer.
  2690. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
  2691. // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
  2692. // that changes the section it ends in, which surprises ld64.
  2693. if (isUTF16) {
  2694. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  2695. GV->setAlignment(Align.getQuantity());
  2696. GV->setSection("__TEXT,__ustring");
  2697. } else {
  2698. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  2699. GV->setAlignment(Align.getQuantity());
  2700. GV->setSection("__TEXT,__cstring,cstring_literals");
  2701. }
  2702. // String.
  2703. Fields[2] =
  2704. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  2705. if (isUTF16)
  2706. // Cast the UTF16 string to the correct type.
  2707. Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
  2708. // String length.
  2709. Ty = getTypes().ConvertType(getContext().LongTy);
  2710. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  2711. CharUnits Alignment = getPointerAlign();
  2712. // The struct.
  2713. C = llvm::ConstantStruct::get(STy, Fields);
  2714. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  2715. llvm::GlobalVariable::PrivateLinkage, C,
  2716. "_unnamed_cfstring_");
  2717. GV->setSection("__DATA,__cfstring");
  2718. GV->setAlignment(Alignment.getQuantity());
  2719. Entry.second = GV;
  2720. return ConstantAddress(GV, Alignment);
  2721. }
  2722. ConstantAddress
  2723. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  2724. unsigned StringLength = 0;
  2725. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2726. GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
  2727. if (auto *C = Entry.second)
  2728. return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
  2729. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2730. llvm::Constant *Zeros[] = { Zero, Zero };
  2731. llvm::Value *V;
  2732. // If we don't already have it, get _NSConstantStringClassReference.
  2733. if (!ConstantStringClassRef) {
  2734. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  2735. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2736. llvm::Constant *GV;
  2737. if (LangOpts.ObjCRuntime.isNonFragile()) {
  2738. std::string str =
  2739. StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
  2740. : "OBJC_CLASS_$_" + StringClass;
  2741. GV = getObjCRuntime().GetClassGlobal(str);
  2742. // Make sure the result is of the correct type.
  2743. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  2744. V = llvm::ConstantExpr::getBitCast(GV, PTy);
  2745. ConstantStringClassRef = V;
  2746. } else {
  2747. std::string str =
  2748. StringClass.empty() ? "_NSConstantStringClassReference"
  2749. : "_" + StringClass + "ClassReference";
  2750. llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
  2751. GV = CreateRuntimeVariable(PTy, str);
  2752. // Decay array -> ptr
  2753. V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
  2754. ConstantStringClassRef = V;
  2755. }
  2756. } else
  2757. V = ConstantStringClassRef;
  2758. if (!NSConstantStringType) {
  2759. // Construct the type for a constant NSString.
  2760. RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
  2761. D->startDefinition();
  2762. QualType FieldTypes[3];
  2763. // const int *isa;
  2764. FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
  2765. // const char *str;
  2766. FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
  2767. // unsigned int length;
  2768. FieldTypes[2] = Context.UnsignedIntTy;
  2769. // Create fields
  2770. for (unsigned i = 0; i < 3; ++i) {
  2771. FieldDecl *Field = FieldDecl::Create(Context, D,
  2772. SourceLocation(),
  2773. SourceLocation(), nullptr,
  2774. FieldTypes[i], /*TInfo=*/nullptr,
  2775. /*BitWidth=*/nullptr,
  2776. /*Mutable=*/false,
  2777. ICIS_NoInit);
  2778. Field->setAccess(AS_public);
  2779. D->addDecl(Field);
  2780. }
  2781. D->completeDefinition();
  2782. QualType NSTy = Context.getTagDeclType(D);
  2783. NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  2784. }
  2785. llvm::Constant *Fields[3];
  2786. // Class pointer.
  2787. Fields[0] = cast<llvm::ConstantExpr>(V);
  2788. // String pointer.
  2789. llvm::Constant *C =
  2790. llvm::ConstantDataArray::getString(VMContext, Entry.first());
  2791. llvm::GlobalValue::LinkageTypes Linkage;
  2792. bool isConstant;
  2793. Linkage = llvm::GlobalValue::PrivateLinkage;
  2794. isConstant = !LangOpts.WritableStrings;
  2795. auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
  2796. Linkage, C, ".str");
  2797. GV->setUnnamedAddr(true);
  2798. // Don't enforce the target's minimum global alignment, since the only use
  2799. // of the string is via this class initializer.
  2800. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  2801. GV->setAlignment(Align.getQuantity());
  2802. Fields[1] =
  2803. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  2804. // String length.
  2805. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  2806. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  2807. // The struct.
  2808. CharUnits Alignment = getPointerAlign();
  2809. C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
  2810. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  2811. llvm::GlobalVariable::PrivateLinkage, C,
  2812. "_unnamed_nsstring_");
  2813. GV->setAlignment(Alignment.getQuantity());
  2814. const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
  2815. const char *NSStringNonFragileABISection =
  2816. "__DATA,__objc_stringobj,regular,no_dead_strip";
  2817. // FIXME. Fix section.
  2818. GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
  2819. ? NSStringNonFragileABISection
  2820. : NSStringSection);
  2821. Entry.second = GV;
  2822. return ConstantAddress(GV, Alignment);
  2823. }
  2824. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  2825. if (ObjCFastEnumerationStateType.isNull()) {
  2826. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  2827. D->startDefinition();
  2828. QualType FieldTypes[] = {
  2829. Context.UnsignedLongTy,
  2830. Context.getPointerType(Context.getObjCIdType()),
  2831. Context.getPointerType(Context.UnsignedLongTy),
  2832. Context.getConstantArrayType(Context.UnsignedLongTy,
  2833. llvm::APInt(32, 5), ArrayType::Normal, 0)
  2834. };
  2835. for (size_t i = 0; i < 4; ++i) {
  2836. FieldDecl *Field = FieldDecl::Create(Context,
  2837. D,
  2838. SourceLocation(),
  2839. SourceLocation(), nullptr,
  2840. FieldTypes[i], /*TInfo=*/nullptr,
  2841. /*BitWidth=*/nullptr,
  2842. /*Mutable=*/false,
  2843. ICIS_NoInit);
  2844. Field->setAccess(AS_public);
  2845. D->addDecl(Field);
  2846. }
  2847. D->completeDefinition();
  2848. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  2849. }
  2850. return ObjCFastEnumerationStateType;
  2851. }
  2852. llvm::Constant *
  2853. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  2854. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  2855. // Don't emit it as the address of the string, emit the string data itself
  2856. // as an inline array.
  2857. if (E->getCharByteWidth() == 1) {
  2858. SmallString<64> Str(E->getString());
  2859. // Resize the string to the right size, which is indicated by its type.
  2860. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  2861. Str.resize(CAT->getSize().getZExtValue());
  2862. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  2863. }
  2864. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  2865. llvm::Type *ElemTy = AType->getElementType();
  2866. unsigned NumElements = AType->getNumElements();
  2867. // Wide strings have either 2-byte or 4-byte elements.
  2868. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  2869. SmallVector<uint16_t, 32> Elements;
  2870. Elements.reserve(NumElements);
  2871. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2872. Elements.push_back(E->getCodeUnit(i));
  2873. Elements.resize(NumElements);
  2874. return llvm::ConstantDataArray::get(VMContext, Elements);
  2875. }
  2876. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  2877. SmallVector<uint32_t, 32> Elements;
  2878. Elements.reserve(NumElements);
  2879. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2880. Elements.push_back(E->getCodeUnit(i));
  2881. Elements.resize(NumElements);
  2882. return llvm::ConstantDataArray::get(VMContext, Elements);
  2883. }
  2884. static llvm::GlobalVariable *
  2885. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  2886. CodeGenModule &CGM, StringRef GlobalName,
  2887. CharUnits Alignment) {
  2888. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  2889. unsigned AddrSpace = 0;
  2890. if (CGM.getLangOpts().OpenCL)
  2891. AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
  2892. llvm::Module &M = CGM.getModule();
  2893. // Create a global variable for this string
  2894. auto *GV = new llvm::GlobalVariable(
  2895. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  2896. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  2897. GV->setAlignment(Alignment.getQuantity());
  2898. GV->setUnnamedAddr(true);
  2899. if (GV->isWeakForLinker()) {
  2900. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  2901. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  2902. }
  2903. return GV;
  2904. }
  2905. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  2906. /// constant array for the given string literal.
  2907. ConstantAddress
  2908. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  2909. StringRef Name) {
  2910. CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
  2911. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  2912. llvm::GlobalVariable **Entry = nullptr;
  2913. if (!LangOpts.WritableStrings) {
  2914. Entry = &ConstantStringMap[C];
  2915. if (auto GV = *Entry) {
  2916. if (Alignment.getQuantity() > GV->getAlignment())
  2917. GV->setAlignment(Alignment.getQuantity());
  2918. return ConstantAddress(GV, Alignment);
  2919. }
  2920. }
  2921. SmallString<256> MangledNameBuffer;
  2922. StringRef GlobalVariableName;
  2923. llvm::GlobalValue::LinkageTypes LT;
  2924. // Mangle the string literal if the ABI allows for it. However, we cannot
  2925. // do this if we are compiling with ASan or -fwritable-strings because they
  2926. // rely on strings having normal linkage.
  2927. if (!LangOpts.WritableStrings &&
  2928. !LangOpts.Sanitize.has(SanitizerKind::Address) &&
  2929. getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
  2930. llvm::raw_svector_ostream Out(MangledNameBuffer);
  2931. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  2932. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  2933. GlobalVariableName = MangledNameBuffer;
  2934. } else {
  2935. LT = llvm::GlobalValue::PrivateLinkage;
  2936. GlobalVariableName = Name;
  2937. }
  2938. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  2939. if (Entry)
  2940. *Entry = GV;
  2941. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  2942. QualType());
  2943. return ConstantAddress(GV, Alignment);
  2944. }
  2945. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  2946. /// array for the given ObjCEncodeExpr node.
  2947. ConstantAddress
  2948. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  2949. std::string Str;
  2950. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  2951. return GetAddrOfConstantCString(Str);
  2952. }
  2953. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  2954. /// the literal and a terminating '\0' character.
  2955. /// The result has pointer to array type.
  2956. ConstantAddress CodeGenModule::GetAddrOfConstantCString(
  2957. const std::string &Str, const char *GlobalName) {
  2958. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  2959. CharUnits Alignment =
  2960. getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
  2961. llvm::Constant *C =
  2962. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  2963. // Don't share any string literals if strings aren't constant.
  2964. llvm::GlobalVariable **Entry = nullptr;
  2965. if (!LangOpts.WritableStrings) {
  2966. Entry = &ConstantStringMap[C];
  2967. if (auto GV = *Entry) {
  2968. if (Alignment.getQuantity() > GV->getAlignment())
  2969. GV->setAlignment(Alignment.getQuantity());
  2970. return ConstantAddress(GV, Alignment);
  2971. }
  2972. }
  2973. // Get the default prefix if a name wasn't specified.
  2974. if (!GlobalName)
  2975. GlobalName = ".str";
  2976. // Create a global variable for this.
  2977. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  2978. GlobalName, Alignment);
  2979. if (Entry)
  2980. *Entry = GV;
  2981. return ConstantAddress(GV, Alignment);
  2982. }
  2983. ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
  2984. const MaterializeTemporaryExpr *E, const Expr *Init) {
  2985. assert((E->getStorageDuration() == SD_Static ||
  2986. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  2987. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  2988. // If we're not materializing a subobject of the temporary, keep the
  2989. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  2990. QualType MaterializedType = Init->getType();
  2991. if (Init == E->GetTemporaryExpr())
  2992. MaterializedType = E->getType();
  2993. CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
  2994. if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
  2995. return ConstantAddress(Slot, Align);
  2996. // FIXME: If an externally-visible declaration extends multiple temporaries,
  2997. // we need to give each temporary the same name in every translation unit (and
  2998. // we also need to make the temporaries externally-visible).
  2999. SmallString<256> Name;
  3000. llvm::raw_svector_ostream Out(Name);
  3001. getCXXABI().getMangleContext().mangleReferenceTemporary(
  3002. VD, E->getManglingNumber(), Out);
  3003. APValue *Value = nullptr;
  3004. if (E->getStorageDuration() == SD_Static) {
  3005. // We might have a cached constant initializer for this temporary. Note
  3006. // that this might have a different value from the value computed by
  3007. // evaluating the initializer if the surrounding constant expression
  3008. // modifies the temporary.
  3009. Value = getContext().getMaterializedTemporaryValue(E, false);
  3010. if (Value && Value->isUninit())
  3011. Value = nullptr;
  3012. }
  3013. // Try evaluating it now, it might have a constant initializer.
  3014. Expr::EvalResult EvalResult;
  3015. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  3016. !EvalResult.hasSideEffects())
  3017. Value = &EvalResult.Val;
  3018. llvm::Constant *InitialValue = nullptr;
  3019. bool Constant = false;
  3020. llvm::Type *Type;
  3021. if (Value) {
  3022. // The temporary has a constant initializer, use it.
  3023. InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
  3024. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  3025. Type = InitialValue->getType();
  3026. } else {
  3027. // No initializer, the initialization will be provided when we
  3028. // initialize the declaration which performed lifetime extension.
  3029. Type = getTypes().ConvertTypeForMem(MaterializedType);
  3030. }
  3031. // Create a global variable for this lifetime-extended temporary.
  3032. llvm::GlobalValue::LinkageTypes Linkage =
  3033. getLLVMLinkageVarDefinition(VD, Constant);
  3034. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  3035. const VarDecl *InitVD;
  3036. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  3037. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  3038. // Temporaries defined inside a class get linkonce_odr linkage because the
  3039. // class can be defined in multipe translation units.
  3040. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  3041. } else {
  3042. // There is no need for this temporary to have external linkage if the
  3043. // VarDecl has external linkage.
  3044. Linkage = llvm::GlobalVariable::InternalLinkage;
  3045. }
  3046. }
  3047. unsigned AddrSpace = GetGlobalVarAddressSpace(
  3048. VD, getContext().getTargetAddressSpace(MaterializedType));
  3049. auto *GV = new llvm::GlobalVariable(
  3050. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  3051. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
  3052. AddrSpace);
  3053. setGlobalVisibility(GV, VD);
  3054. GV->setAlignment(Align.getQuantity());
  3055. if (supportsCOMDAT() && GV->isWeakForLinker())
  3056. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  3057. if (VD->getTLSKind())
  3058. setTLSMode(GV, *VD);
  3059. MaterializedGlobalTemporaryMap[E] = GV;
  3060. return ConstantAddress(GV, Align);
  3061. }
  3062. /// EmitObjCPropertyImplementations - Emit information for synthesized
  3063. /// properties for an implementation.
  3064. void CodeGenModule::EmitObjCPropertyImplementations(const
  3065. ObjCImplementationDecl *D) {
  3066. for (const auto *PID : D->property_impls()) {
  3067. // Dynamic is just for type-checking.
  3068. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  3069. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  3070. // Determine which methods need to be implemented, some may have
  3071. // been overridden. Note that ::isPropertyAccessor is not the method
  3072. // we want, that just indicates if the decl came from a
  3073. // property. What we want to know is if the method is defined in
  3074. // this implementation.
  3075. if (!D->getInstanceMethod(PD->getGetterName()))
  3076. CodeGenFunction(*this).GenerateObjCGetter(
  3077. const_cast<ObjCImplementationDecl *>(D), PID);
  3078. if (!PD->isReadOnly() &&
  3079. !D->getInstanceMethod(PD->getSetterName()))
  3080. CodeGenFunction(*this).GenerateObjCSetter(
  3081. const_cast<ObjCImplementationDecl *>(D), PID);
  3082. }
  3083. }
  3084. }
  3085. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  3086. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  3087. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  3088. ivar; ivar = ivar->getNextIvar())
  3089. if (ivar->getType().isDestructedType())
  3090. return true;
  3091. return false;
  3092. }
  3093. static bool AllTrivialInitializers(CodeGenModule &CGM,
  3094. ObjCImplementationDecl *D) {
  3095. CodeGenFunction CGF(CGM);
  3096. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  3097. E = D->init_end(); B != E; ++B) {
  3098. CXXCtorInitializer *CtorInitExp = *B;
  3099. Expr *Init = CtorInitExp->getInit();
  3100. if (!CGF.isTrivialInitializer(Init))
  3101. return false;
  3102. }
  3103. return true;
  3104. }
  3105. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  3106. /// for an implementation.
  3107. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  3108. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  3109. if (needsDestructMethod(D)) {
  3110. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  3111. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3112. ObjCMethodDecl *DTORMethod =
  3113. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  3114. cxxSelector, getContext().VoidTy, nullptr, D,
  3115. /*isInstance=*/true, /*isVariadic=*/false,
  3116. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  3117. /*isDefined=*/false, ObjCMethodDecl::Required);
  3118. D->addInstanceMethod(DTORMethod);
  3119. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  3120. D->setHasDestructors(true);
  3121. }
  3122. // If the implementation doesn't have any ivar initializers, we don't need
  3123. // a .cxx_construct.
  3124. if (D->getNumIvarInitializers() == 0 ||
  3125. AllTrivialInitializers(*this, D))
  3126. return;
  3127. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  3128. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3129. // The constructor returns 'self'.
  3130. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  3131. D->getLocation(),
  3132. D->getLocation(),
  3133. cxxSelector,
  3134. getContext().getObjCIdType(),
  3135. nullptr, D, /*isInstance=*/true,
  3136. /*isVariadic=*/false,
  3137. /*isPropertyAccessor=*/true,
  3138. /*isImplicitlyDeclared=*/true,
  3139. /*isDefined=*/false,
  3140. ObjCMethodDecl::Required);
  3141. D->addInstanceMethod(CTORMethod);
  3142. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  3143. D->setHasNonZeroConstructors(true);
  3144. }
  3145. /// EmitNamespace - Emit all declarations in a namespace.
  3146. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  3147. for (auto *I : ND->decls()) {
  3148. if (const auto *VD = dyn_cast<VarDecl>(I))
  3149. if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
  3150. VD->getTemplateSpecializationKind() != TSK_Undeclared)
  3151. continue;
  3152. EmitTopLevelDecl(I);
  3153. }
  3154. }
  3155. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  3156. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  3157. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  3158. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  3159. ErrorUnsupported(LSD, "linkage spec");
  3160. return;
  3161. }
  3162. for (auto *I : LSD->decls()) {
  3163. // Meta-data for ObjC class includes references to implemented methods.
  3164. // Generate class's method definitions first.
  3165. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  3166. for (auto *M : OID->methods())
  3167. EmitTopLevelDecl(M);
  3168. }
  3169. EmitTopLevelDecl(I);
  3170. }
  3171. }
  3172. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  3173. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  3174. // Ignore dependent declarations.
  3175. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  3176. return;
  3177. switch (D->getKind()) {
  3178. case Decl::CXXConversion:
  3179. case Decl::CXXMethod:
  3180. case Decl::Function:
  3181. // Skip function templates
  3182. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  3183. cast<FunctionDecl>(D)->isLateTemplateParsed())
  3184. return;
  3185. EmitGlobal(cast<FunctionDecl>(D));
  3186. // Always provide some coverage mapping
  3187. // even for the functions that aren't emitted.
  3188. AddDeferredUnusedCoverageMapping(D);
  3189. break;
  3190. case Decl::Var:
  3191. // Skip variable templates
  3192. if (cast<VarDecl>(D)->getDescribedVarTemplate())
  3193. return;
  3194. case Decl::VarTemplateSpecialization:
  3195. EmitGlobal(cast<VarDecl>(D));
  3196. break;
  3197. // Indirect fields from global anonymous structs and unions can be
  3198. // ignored; only the actual variable requires IR gen support.
  3199. case Decl::IndirectField:
  3200. break;
  3201. // C++ Decls
  3202. case Decl::Namespace:
  3203. EmitNamespace(cast<NamespaceDecl>(D));
  3204. break;
  3205. // No code generation needed.
  3206. case Decl::UsingShadow:
  3207. case Decl::ClassTemplate:
  3208. case Decl::VarTemplate:
  3209. case Decl::VarTemplatePartialSpecialization:
  3210. case Decl::FunctionTemplate:
  3211. case Decl::TypeAliasTemplate:
  3212. case Decl::Block:
  3213. case Decl::Empty:
  3214. break;
  3215. case Decl::Using: // using X; [C++]
  3216. if (CGDebugInfo *DI = getModuleDebugInfo())
  3217. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  3218. return;
  3219. case Decl::NamespaceAlias:
  3220. if (CGDebugInfo *DI = getModuleDebugInfo())
  3221. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  3222. return;
  3223. case Decl::UsingDirective: // using namespace X; [C++]
  3224. if (CGDebugInfo *DI = getModuleDebugInfo())
  3225. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  3226. return;
  3227. case Decl::CXXConstructor:
  3228. // Skip function templates
  3229. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  3230. cast<FunctionDecl>(D)->isLateTemplateParsed())
  3231. return;
  3232. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  3233. break;
  3234. case Decl::CXXDestructor:
  3235. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  3236. return;
  3237. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  3238. break;
  3239. case Decl::StaticAssert:
  3240. // Nothing to do.
  3241. break;
  3242. // Objective-C Decls
  3243. // Forward declarations, no (immediate) code generation.
  3244. case Decl::ObjCInterface:
  3245. case Decl::ObjCCategory:
  3246. break;
  3247. case Decl::ObjCProtocol: {
  3248. auto *Proto = cast<ObjCProtocolDecl>(D);
  3249. if (Proto->isThisDeclarationADefinition())
  3250. ObjCRuntime->GenerateProtocol(Proto);
  3251. break;
  3252. }
  3253. case Decl::ObjCCategoryImpl:
  3254. // Categories have properties but don't support synthesize so we
  3255. // can ignore them here.
  3256. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  3257. break;
  3258. case Decl::ObjCImplementation: {
  3259. auto *OMD = cast<ObjCImplementationDecl>(D);
  3260. EmitObjCPropertyImplementations(OMD);
  3261. EmitObjCIvarInitializations(OMD);
  3262. ObjCRuntime->GenerateClass(OMD);
  3263. // Emit global variable debug information.
  3264. if (CGDebugInfo *DI = getModuleDebugInfo())
  3265. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  3266. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  3267. OMD->getClassInterface()), OMD->getLocation());
  3268. break;
  3269. }
  3270. case Decl::ObjCMethod: {
  3271. auto *OMD = cast<ObjCMethodDecl>(D);
  3272. // If this is not a prototype, emit the body.
  3273. if (OMD->getBody())
  3274. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  3275. break;
  3276. }
  3277. case Decl::ObjCCompatibleAlias:
  3278. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  3279. break;
  3280. case Decl::PragmaComment: {
  3281. const auto *PCD = cast<PragmaCommentDecl>(D);
  3282. switch (PCD->getCommentKind()) {
  3283. case PCK_Unknown:
  3284. llvm_unreachable("unexpected pragma comment kind");
  3285. case PCK_Linker:
  3286. AppendLinkerOptions(PCD->getArg());
  3287. break;
  3288. case PCK_Lib:
  3289. AddDependentLib(PCD->getArg());
  3290. break;
  3291. case PCK_Compiler:
  3292. case PCK_ExeStr:
  3293. case PCK_User:
  3294. break; // We ignore all of these.
  3295. }
  3296. break;
  3297. }
  3298. case Decl::PragmaDetectMismatch: {
  3299. const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
  3300. AddDetectMismatch(PDMD->getName(), PDMD->getValue());
  3301. break;
  3302. }
  3303. case Decl::LinkageSpec:
  3304. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  3305. break;
  3306. case Decl::FileScopeAsm: {
  3307. // File-scope asm is ignored during device-side CUDA compilation.
  3308. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  3309. break;
  3310. // File-scope asm is ignored during device-side OpenMP compilation.
  3311. if (LangOpts.OpenMPIsDevice)
  3312. break;
  3313. auto *AD = cast<FileScopeAsmDecl>(D);
  3314. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  3315. break;
  3316. }
  3317. case Decl::Import: {
  3318. auto *Import = cast<ImportDecl>(D);
  3319. // Ignore import declarations that come from imported modules.
  3320. if (Import->getImportedOwningModule())
  3321. break;
  3322. if (CGDebugInfo *DI = getModuleDebugInfo())
  3323. DI->EmitImportDecl(*Import);
  3324. ImportedModules.insert(Import->getImportedModule());
  3325. break;
  3326. }
  3327. case Decl::OMPThreadPrivate:
  3328. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  3329. break;
  3330. case Decl::ClassTemplateSpecialization: {
  3331. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  3332. if (DebugInfo &&
  3333. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
  3334. Spec->hasDefinition())
  3335. DebugInfo->completeTemplateDefinition(*Spec);
  3336. break;
  3337. }
  3338. case Decl::OMPDeclareReduction:
  3339. EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
  3340. break;
  3341. default:
  3342. // Make sure we handled everything we should, every other kind is a
  3343. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  3344. // function. Need to recode Decl::Kind to do that easily.
  3345. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  3346. break;
  3347. }
  3348. }
  3349. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  3350. // Do we need to generate coverage mapping?
  3351. if (!CodeGenOpts.CoverageMapping)
  3352. return;
  3353. switch (D->getKind()) {
  3354. case Decl::CXXConversion:
  3355. case Decl::CXXMethod:
  3356. case Decl::Function:
  3357. case Decl::ObjCMethod:
  3358. case Decl::CXXConstructor:
  3359. case Decl::CXXDestructor: {
  3360. if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
  3361. return;
  3362. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3363. if (I == DeferredEmptyCoverageMappingDecls.end())
  3364. DeferredEmptyCoverageMappingDecls[D] = true;
  3365. break;
  3366. }
  3367. default:
  3368. break;
  3369. };
  3370. }
  3371. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  3372. // Do we need to generate coverage mapping?
  3373. if (!CodeGenOpts.CoverageMapping)
  3374. return;
  3375. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  3376. if (Fn->isTemplateInstantiation())
  3377. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  3378. }
  3379. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3380. if (I == DeferredEmptyCoverageMappingDecls.end())
  3381. DeferredEmptyCoverageMappingDecls[D] = false;
  3382. else
  3383. I->second = false;
  3384. }
  3385. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  3386. std::vector<const Decl *> DeferredDecls;
  3387. for (const auto &I : DeferredEmptyCoverageMappingDecls) {
  3388. if (!I.second)
  3389. continue;
  3390. DeferredDecls.push_back(I.first);
  3391. }
  3392. // Sort the declarations by their location to make sure that the tests get a
  3393. // predictable order for the coverage mapping for the unused declarations.
  3394. if (CodeGenOpts.DumpCoverageMapping)
  3395. std::sort(DeferredDecls.begin(), DeferredDecls.end(),
  3396. [] (const Decl *LHS, const Decl *RHS) {
  3397. return LHS->getLocStart() < RHS->getLocStart();
  3398. });
  3399. for (const auto *D : DeferredDecls) {
  3400. switch (D->getKind()) {
  3401. case Decl::CXXConversion:
  3402. case Decl::CXXMethod:
  3403. case Decl::Function:
  3404. case Decl::ObjCMethod: {
  3405. CodeGenPGO PGO(*this);
  3406. GlobalDecl GD(cast<FunctionDecl>(D));
  3407. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3408. getFunctionLinkage(GD));
  3409. break;
  3410. }
  3411. case Decl::CXXConstructor: {
  3412. CodeGenPGO PGO(*this);
  3413. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  3414. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3415. getFunctionLinkage(GD));
  3416. break;
  3417. }
  3418. case Decl::CXXDestructor: {
  3419. CodeGenPGO PGO(*this);
  3420. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  3421. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3422. getFunctionLinkage(GD));
  3423. break;
  3424. }
  3425. default:
  3426. break;
  3427. };
  3428. }
  3429. }
  3430. /// Turns the given pointer into a constant.
  3431. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  3432. const void *Ptr) {
  3433. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  3434. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  3435. return llvm::ConstantInt::get(i64, PtrInt);
  3436. }
  3437. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  3438. llvm::NamedMDNode *&GlobalMetadata,
  3439. GlobalDecl D,
  3440. llvm::GlobalValue *Addr) {
  3441. if (!GlobalMetadata)
  3442. GlobalMetadata =
  3443. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  3444. // TODO: should we report variant information for ctors/dtors?
  3445. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  3446. llvm::ConstantAsMetadata::get(GetPointerConstant(
  3447. CGM.getLLVMContext(), D.getDecl()))};
  3448. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  3449. }
  3450. /// For each function which is declared within an extern "C" region and marked
  3451. /// as 'used', but has internal linkage, create an alias from the unmangled
  3452. /// name to the mangled name if possible. People expect to be able to refer
  3453. /// to such functions with an unmangled name from inline assembly within the
  3454. /// same translation unit.
  3455. void CodeGenModule::EmitStaticExternCAliases() {
  3456. // Don't do anything if we're generating CUDA device code -- the NVPTX
  3457. // assembly target doesn't support aliases.
  3458. if (Context.getTargetInfo().getTriple().isNVPTX())
  3459. return;
  3460. for (auto &I : StaticExternCValues) {
  3461. IdentifierInfo *Name = I.first;
  3462. llvm::GlobalValue *Val = I.second;
  3463. if (Val && !getModule().getNamedValue(Name->getName()))
  3464. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  3465. }
  3466. }
  3467. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  3468. GlobalDecl &Result) const {
  3469. auto Res = Manglings.find(MangledName);
  3470. if (Res == Manglings.end())
  3471. return false;
  3472. Result = Res->getValue();
  3473. return true;
  3474. }
  3475. /// Emits metadata nodes associating all the global values in the
  3476. /// current module with the Decls they came from. This is useful for
  3477. /// projects using IR gen as a subroutine.
  3478. ///
  3479. /// Since there's currently no way to associate an MDNode directly
  3480. /// with an llvm::GlobalValue, we create a global named metadata
  3481. /// with the name 'clang.global.decl.ptrs'.
  3482. void CodeGenModule::EmitDeclMetadata() {
  3483. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3484. for (auto &I : MangledDeclNames) {
  3485. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  3486. // Some mangled names don't necessarily have an associated GlobalValue
  3487. // in this module, e.g. if we mangled it for DebugInfo.
  3488. if (Addr)
  3489. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  3490. }
  3491. }
  3492. /// Emits metadata nodes for all the local variables in the current
  3493. /// function.
  3494. void CodeGenFunction::EmitDeclMetadata() {
  3495. if (LocalDeclMap.empty()) return;
  3496. llvm::LLVMContext &Context = getLLVMContext();
  3497. // Find the unique metadata ID for this name.
  3498. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  3499. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3500. for (auto &I : LocalDeclMap) {
  3501. const Decl *D = I.first;
  3502. llvm::Value *Addr = I.second.getPointer();
  3503. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  3504. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  3505. Alloca->setMetadata(
  3506. DeclPtrKind, llvm::MDNode::get(
  3507. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  3508. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  3509. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  3510. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  3511. }
  3512. }
  3513. }
  3514. void CodeGenModule::EmitVersionIdentMetadata() {
  3515. llvm::NamedMDNode *IdentMetadata =
  3516. TheModule.getOrInsertNamedMetadata("llvm.ident");
  3517. std::string Version = getClangFullVersion();
  3518. llvm::LLVMContext &Ctx = TheModule.getContext();
  3519. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  3520. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  3521. }
  3522. void CodeGenModule::EmitTargetMetadata() {
  3523. // Warning, new MangledDeclNames may be appended within this loop.
  3524. // We rely on MapVector insertions adding new elements to the end
  3525. // of the container.
  3526. // FIXME: Move this loop into the one target that needs it, and only
  3527. // loop over those declarations for which we couldn't emit the target
  3528. // metadata when we emitted the declaration.
  3529. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  3530. auto Val = *(MangledDeclNames.begin() + I);
  3531. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  3532. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  3533. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  3534. }
  3535. }
  3536. void CodeGenModule::EmitCoverageFile() {
  3537. if (!getCodeGenOpts().CoverageFile.empty()) {
  3538. if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
  3539. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  3540. llvm::LLVMContext &Ctx = TheModule.getContext();
  3541. llvm::MDString *CoverageFile =
  3542. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
  3543. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  3544. llvm::MDNode *CU = CUNode->getOperand(i);
  3545. llvm::Metadata *Elts[] = {CoverageFile, CU};
  3546. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  3547. }
  3548. }
  3549. }
  3550. }
  3551. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
  3552. // Sema has checked that all uuid strings are of the form
  3553. // "12345678-1234-1234-1234-1234567890ab".
  3554. assert(Uuid.size() == 36);
  3555. for (unsigned i = 0; i < 36; ++i) {
  3556. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  3557. else assert(isHexDigit(Uuid[i]));
  3558. }
  3559. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  3560. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  3561. llvm::Constant *Field3[8];
  3562. for (unsigned Idx = 0; Idx < 8; ++Idx)
  3563. Field3[Idx] = llvm::ConstantInt::get(
  3564. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  3565. llvm::Constant *Fields[4] = {
  3566. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  3567. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  3568. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  3569. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  3570. };
  3571. return llvm::ConstantStruct::getAnon(Fields);
  3572. }
  3573. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  3574. bool ForEH) {
  3575. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  3576. // FIXME: should we even be calling this method if RTTI is disabled
  3577. // and it's not for EH?
  3578. if (!ForEH && !getLangOpts().RTTI)
  3579. return llvm::Constant::getNullValue(Int8PtrTy);
  3580. if (ForEH && Ty->isObjCObjectPointerType() &&
  3581. LangOpts.ObjCRuntime.isGNUFamily())
  3582. return ObjCRuntime->GetEHType(Ty);
  3583. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  3584. }
  3585. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  3586. for (auto RefExpr : D->varlists()) {
  3587. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  3588. bool PerformInit =
  3589. VD->getAnyInitializer() &&
  3590. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  3591. /*ForRef=*/false);
  3592. Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
  3593. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  3594. VD, Addr, RefExpr->getLocStart(), PerformInit))
  3595. CXXGlobalInits.push_back(InitFunction);
  3596. }
  3597. }
  3598. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
  3599. llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
  3600. if (InternalId)
  3601. return InternalId;
  3602. if (isExternallyVisible(T->getLinkage())) {
  3603. std::string OutName;
  3604. llvm::raw_string_ostream Out(OutName);
  3605. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  3606. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  3607. } else {
  3608. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  3609. llvm::ArrayRef<llvm::Metadata *>());
  3610. }
  3611. return InternalId;
  3612. }
  3613. /// Returns whether this module needs the "all-vtables" bitset.
  3614. bool CodeGenModule::NeedAllVtablesBitSet() const {
  3615. // Returns true if at least one of vtable-based CFI checkers is enabled and
  3616. // is not in the trapping mode.
  3617. return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
  3618. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
  3619. (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
  3620. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
  3621. (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
  3622. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
  3623. (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
  3624. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
  3625. }
  3626. void CodeGenModule::CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD,
  3627. llvm::GlobalVariable *VTable,
  3628. CharUnits Offset,
  3629. const CXXRecordDecl *RD) {
  3630. llvm::Metadata *MD =
  3631. CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  3632. llvm::Metadata *BitsetOps[] = {
  3633. MD, llvm::ConstantAsMetadata::get(VTable),
  3634. llvm::ConstantAsMetadata::get(
  3635. llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
  3636. BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps));
  3637. if (CodeGenOpts.SanitizeCfiCrossDso) {
  3638. if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) {
  3639. llvm::Metadata *BitsetOps2[] = {
  3640. llvm::ConstantAsMetadata::get(TypeId),
  3641. llvm::ConstantAsMetadata::get(VTable),
  3642. llvm::ConstantAsMetadata::get(
  3643. llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
  3644. BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2));
  3645. }
  3646. }
  3647. if (NeedAllVtablesBitSet()) {
  3648. llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
  3649. llvm::Metadata *BitsetOps[] = {
  3650. MD, llvm::ConstantAsMetadata::get(VTable),
  3651. llvm::ConstantAsMetadata::get(
  3652. llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
  3653. // Avoid adding a node to BitsetsMD twice.
  3654. if (!llvm::MDTuple::getIfExists(getLLVMContext(), BitsetOps))
  3655. BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps));
  3656. }
  3657. }
  3658. // Fills in the supplied string map with the set of target features for the
  3659. // passed in function.
  3660. void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  3661. const FunctionDecl *FD) {
  3662. StringRef TargetCPU = Target.getTargetOpts().CPU;
  3663. if (const auto *TD = FD->getAttr<TargetAttr>()) {
  3664. // If we have a TargetAttr build up the feature map based on that.
  3665. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  3666. // Make a copy of the features as passed on the command line into the
  3667. // beginning of the additional features from the function to override.
  3668. ParsedAttr.first.insert(ParsedAttr.first.begin(),
  3669. Target.getTargetOpts().FeaturesAsWritten.begin(),
  3670. Target.getTargetOpts().FeaturesAsWritten.end());
  3671. if (ParsedAttr.second != "")
  3672. TargetCPU = ParsedAttr.second;
  3673. // Now populate the feature map, first with the TargetCPU which is either
  3674. // the default or a new one from the target attribute string. Then we'll use
  3675. // the passed in features (FeaturesAsWritten) along with the new ones from
  3676. // the attribute.
  3677. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
  3678. } else {
  3679. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  3680. Target.getTargetOpts().Features);
  3681. }
  3682. }
  3683. llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
  3684. if (!SanStats)
  3685. SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
  3686. return *SanStats;
  3687. }