CodeGenModule.cpp 207 KB

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