CodeGenModule.cpp 209 KB

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