CodeGenModule.cpp 205 KB

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