CodeGenModule.cpp 173 KB

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