CodeGenModule.cpp 208 KB

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