CGExpr.cpp 197 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010
  1. //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This contains code to emit Expr nodes as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGCXXABI.h"
  13. #include "CGCall.h"
  14. #include "CGCleanup.h"
  15. #include "CGDebugInfo.h"
  16. #include "CGObjCRuntime.h"
  17. #include "CGOpenMPRuntime.h"
  18. #include "CGRecordLayout.h"
  19. #include "CodeGenFunction.h"
  20. #include "CodeGenModule.h"
  21. #include "ConstantEmitter.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/Attr.h"
  25. #include "clang/AST/DeclObjC.h"
  26. #include "clang/AST/NSAPI.h"
  27. #include "clang/Basic/CodeGenOptions.h"
  28. #include "llvm/ADT/Hashing.h"
  29. #include "llvm/ADT/StringExtras.h"
  30. #include "llvm/IR/DataLayout.h"
  31. #include "llvm/IR/Intrinsics.h"
  32. #include "llvm/IR/LLVMContext.h"
  33. #include "llvm/IR/MDBuilder.h"
  34. #include "llvm/Support/ConvertUTF.h"
  35. #include "llvm/Support/MathExtras.h"
  36. #include "llvm/Support/Path.h"
  37. #include "llvm/Transforms/Utils/SanitizerStats.h"
  38. #include <string>
  39. using namespace clang;
  40. using namespace CodeGen;
  41. //===--------------------------------------------------------------------===//
  42. // Miscellaneous Helper Methods
  43. //===--------------------------------------------------------------------===//
  44. llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
  45. unsigned addressSpace =
  46. cast<llvm::PointerType>(value->getType())->getAddressSpace();
  47. llvm::PointerType *destType = Int8PtrTy;
  48. if (addressSpace)
  49. destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
  50. if (value->getType() == destType) return value;
  51. return Builder.CreateBitCast(value, destType);
  52. }
  53. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  54. /// block.
  55. Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
  56. CharUnits Align,
  57. const Twine &Name,
  58. llvm::Value *ArraySize) {
  59. auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
  60. Alloca->setAlignment(Align.getQuantity());
  61. return Address(Alloca, Align);
  62. }
  63. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  64. /// block. The alloca is casted to default address space if necessary.
  65. Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
  66. const Twine &Name,
  67. llvm::Value *ArraySize,
  68. Address *AllocaAddr) {
  69. auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
  70. if (AllocaAddr)
  71. *AllocaAddr = Alloca;
  72. llvm::Value *V = Alloca.getPointer();
  73. // Alloca always returns a pointer in alloca address space, which may
  74. // be different from the type defined by the language. For example,
  75. // in C++ the auto variables are in the default address space. Therefore
  76. // cast alloca to the default address space when necessary.
  77. if (getASTAllocaAddressSpace() != LangAS::Default) {
  78. auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
  79. llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
  80. // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
  81. // otherwise alloca is inserted at the current insertion point of the
  82. // builder.
  83. if (!ArraySize)
  84. Builder.SetInsertPoint(AllocaInsertPt);
  85. V = getTargetHooks().performAddrSpaceCast(
  86. *this, V, getASTAllocaAddressSpace(), LangAS::Default,
  87. Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
  88. }
  89. return Address(V, Align);
  90. }
  91. /// CreateTempAlloca - This creates an alloca and inserts it into the entry
  92. /// block if \p ArraySize is nullptr, otherwise inserts it at the current
  93. /// insertion point of the builder.
  94. llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
  95. const Twine &Name,
  96. llvm::Value *ArraySize) {
  97. if (ArraySize)
  98. return Builder.CreateAlloca(Ty, ArraySize, Name);
  99. return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
  100. ArraySize, Name, AllocaInsertPt);
  101. }
  102. /// CreateDefaultAlignTempAlloca - This creates an alloca with the
  103. /// default alignment of the corresponding LLVM type, which is *not*
  104. /// guaranteed to be related in any way to the expected alignment of
  105. /// an AST type that might have been lowered to Ty.
  106. Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
  107. const Twine &Name) {
  108. CharUnits Align =
  109. CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
  110. return CreateTempAlloca(Ty, Align, Name);
  111. }
  112. void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
  113. assert(isa<llvm::AllocaInst>(Var.getPointer()));
  114. auto *Store = new llvm::StoreInst(Init, Var.getPointer());
  115. Store->setAlignment(Var.getAlignment().getQuantity());
  116. llvm::BasicBlock *Block = AllocaInsertPt->getParent();
  117. Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
  118. }
  119. Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
  120. CharUnits Align = getContext().getTypeAlignInChars(Ty);
  121. return CreateTempAlloca(ConvertType(Ty), Align, Name);
  122. }
  123. Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
  124. Address *Alloca) {
  125. // FIXME: Should we prefer the preferred type alignment here?
  126. return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
  127. }
  128. Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
  129. const Twine &Name, Address *Alloca) {
  130. return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
  131. /*ArraySize=*/nullptr, Alloca);
  132. }
  133. Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
  134. const Twine &Name) {
  135. return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
  136. }
  137. Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
  138. const Twine &Name) {
  139. return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
  140. Name);
  141. }
  142. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  143. /// expression and compare the result against zero, returning an Int1Ty value.
  144. llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
  145. PGO.setCurrentStmt(E);
  146. if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
  147. llvm::Value *MemPtr = EmitScalarExpr(E);
  148. return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
  149. }
  150. QualType BoolTy = getContext().BoolTy;
  151. SourceLocation Loc = E->getExprLoc();
  152. if (!E->getType()->isAnyComplexType())
  153. return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
  154. return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
  155. Loc);
  156. }
  157. /// EmitIgnoredExpr - Emit code to compute the specified expression,
  158. /// ignoring the result.
  159. void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
  160. if (E->isRValue())
  161. return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
  162. // Just emit it as an l-value and drop the result.
  163. EmitLValue(E);
  164. }
  165. /// EmitAnyExpr - Emit code to compute the specified expression which
  166. /// can have any type. The result is returned as an RValue struct.
  167. /// If this is an aggregate expression, AggSlot indicates where the
  168. /// result should be returned.
  169. RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
  170. AggValueSlot aggSlot,
  171. bool ignoreResult) {
  172. switch (getEvaluationKind(E->getType())) {
  173. case TEK_Scalar:
  174. return RValue::get(EmitScalarExpr(E, ignoreResult));
  175. case TEK_Complex:
  176. return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
  177. case TEK_Aggregate:
  178. if (!ignoreResult && aggSlot.isIgnored())
  179. aggSlot = CreateAggTemp(E->getType(), "agg-temp");
  180. EmitAggExpr(E, aggSlot);
  181. return aggSlot.asRValue();
  182. }
  183. llvm_unreachable("bad evaluation kind");
  184. }
  185. /// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
  186. /// always be accessible even if no aggregate location is provided.
  187. RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
  188. AggValueSlot AggSlot = AggValueSlot::ignored();
  189. if (hasAggregateEvaluationKind(E->getType()))
  190. AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
  191. return EmitAnyExpr(E, AggSlot);
  192. }
  193. /// EmitAnyExprToMem - Evaluate an expression into a given memory
  194. /// location.
  195. void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
  196. Address Location,
  197. Qualifiers Quals,
  198. bool IsInit) {
  199. // FIXME: This function should take an LValue as an argument.
  200. switch (getEvaluationKind(E->getType())) {
  201. case TEK_Complex:
  202. EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
  203. /*isInit*/ false);
  204. return;
  205. case TEK_Aggregate: {
  206. EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
  207. AggValueSlot::IsDestructed_t(IsInit),
  208. AggValueSlot::DoesNotNeedGCBarriers,
  209. AggValueSlot::IsAliased_t(!IsInit),
  210. AggValueSlot::MayOverlap));
  211. return;
  212. }
  213. case TEK_Scalar: {
  214. RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
  215. LValue LV = MakeAddrLValue(Location, E->getType());
  216. EmitStoreThroughLValue(RV, LV);
  217. return;
  218. }
  219. }
  220. llvm_unreachable("bad evaluation kind");
  221. }
  222. static void
  223. pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
  224. const Expr *E, Address ReferenceTemporary) {
  225. // Objective-C++ ARC:
  226. // If we are binding a reference to a temporary that has ownership, we
  227. // need to perform retain/release operations on the temporary.
  228. //
  229. // FIXME: This should be looking at E, not M.
  230. if (auto Lifetime = M->getType().getObjCLifetime()) {
  231. switch (Lifetime) {
  232. case Qualifiers::OCL_None:
  233. case Qualifiers::OCL_ExplicitNone:
  234. // Carry on to normal cleanup handling.
  235. break;
  236. case Qualifiers::OCL_Autoreleasing:
  237. // Nothing to do; cleaned up by an autorelease pool.
  238. return;
  239. case Qualifiers::OCL_Strong:
  240. case Qualifiers::OCL_Weak:
  241. switch (StorageDuration Duration = M->getStorageDuration()) {
  242. case SD_Static:
  243. // Note: we intentionally do not register a cleanup to release
  244. // the object on program termination.
  245. return;
  246. case SD_Thread:
  247. // FIXME: We should probably register a cleanup in this case.
  248. return;
  249. case SD_Automatic:
  250. case SD_FullExpression:
  251. CodeGenFunction::Destroyer *Destroy;
  252. CleanupKind CleanupKind;
  253. if (Lifetime == Qualifiers::OCL_Strong) {
  254. const ValueDecl *VD = M->getExtendingDecl();
  255. bool Precise =
  256. VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
  257. CleanupKind = CGF.getARCCleanupKind();
  258. Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
  259. : &CodeGenFunction::destroyARCStrongImprecise;
  260. } else {
  261. // __weak objects always get EH cleanups; otherwise, exceptions
  262. // could cause really nasty crashes instead of mere leaks.
  263. CleanupKind = NormalAndEHCleanup;
  264. Destroy = &CodeGenFunction::destroyARCWeak;
  265. }
  266. if (Duration == SD_FullExpression)
  267. CGF.pushDestroy(CleanupKind, ReferenceTemporary,
  268. M->getType(), *Destroy,
  269. CleanupKind & EHCleanup);
  270. else
  271. CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
  272. M->getType(),
  273. *Destroy, CleanupKind & EHCleanup);
  274. return;
  275. case SD_Dynamic:
  276. llvm_unreachable("temporary cannot have dynamic storage duration");
  277. }
  278. llvm_unreachable("unknown storage duration");
  279. }
  280. }
  281. CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
  282. if (const RecordType *RT =
  283. E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
  284. // Get the destructor for the reference temporary.
  285. auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  286. if (!ClassDecl->hasTrivialDestructor())
  287. ReferenceTemporaryDtor = ClassDecl->getDestructor();
  288. }
  289. if (!ReferenceTemporaryDtor)
  290. return;
  291. // Call the destructor for the temporary.
  292. switch (M->getStorageDuration()) {
  293. case SD_Static:
  294. case SD_Thread: {
  295. llvm::FunctionCallee CleanupFn;
  296. llvm::Constant *CleanupArg;
  297. if (E->getType()->isArrayType()) {
  298. CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
  299. ReferenceTemporary, E->getType(),
  300. CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
  301. dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
  302. CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
  303. } else {
  304. CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
  305. GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
  306. CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
  307. }
  308. CGF.CGM.getCXXABI().registerGlobalDtor(
  309. CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
  310. break;
  311. }
  312. case SD_FullExpression:
  313. CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
  314. CodeGenFunction::destroyCXXObject,
  315. CGF.getLangOpts().Exceptions);
  316. break;
  317. case SD_Automatic:
  318. CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
  319. ReferenceTemporary, E->getType(),
  320. CodeGenFunction::destroyCXXObject,
  321. CGF.getLangOpts().Exceptions);
  322. break;
  323. case SD_Dynamic:
  324. llvm_unreachable("temporary cannot have dynamic storage duration");
  325. }
  326. }
  327. static Address createReferenceTemporary(CodeGenFunction &CGF,
  328. const MaterializeTemporaryExpr *M,
  329. const Expr *Inner,
  330. Address *Alloca = nullptr) {
  331. auto &TCG = CGF.getTargetHooks();
  332. switch (M->getStorageDuration()) {
  333. case SD_FullExpression:
  334. case SD_Automatic: {
  335. // If we have a constant temporary array or record try to promote it into a
  336. // constant global under the same rules a normal constant would've been
  337. // promoted. This is easier on the optimizer and generally emits fewer
  338. // instructions.
  339. QualType Ty = Inner->getType();
  340. if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
  341. (Ty->isArrayType() || Ty->isRecordType()) &&
  342. CGF.CGM.isTypeConstant(Ty, true))
  343. if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
  344. if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
  345. auto AS = AddrSpace.getValue();
  346. auto *GV = new llvm::GlobalVariable(
  347. CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
  348. llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
  349. llvm::GlobalValue::NotThreadLocal,
  350. CGF.getContext().getTargetAddressSpace(AS));
  351. CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
  352. GV->setAlignment(alignment.getQuantity());
  353. llvm::Constant *C = GV;
  354. if (AS != LangAS::Default)
  355. C = TCG.performAddrSpaceCast(
  356. CGF.CGM, GV, AS, LangAS::Default,
  357. GV->getValueType()->getPointerTo(
  358. CGF.getContext().getTargetAddressSpace(LangAS::Default)));
  359. // FIXME: Should we put the new global into a COMDAT?
  360. return Address(C, alignment);
  361. }
  362. }
  363. return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
  364. }
  365. case SD_Thread:
  366. case SD_Static:
  367. return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
  368. case SD_Dynamic:
  369. llvm_unreachable("temporary can't have dynamic storage duration");
  370. }
  371. llvm_unreachable("unknown storage duration");
  372. }
  373. LValue CodeGenFunction::
  374. EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
  375. const Expr *E = M->GetTemporaryExpr();
  376. assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
  377. !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
  378. "Reference should never be pseudo-strong!");
  379. // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
  380. // as that will cause the lifetime adjustment to be lost for ARC
  381. auto ownership = M->getType().getObjCLifetime();
  382. if (ownership != Qualifiers::OCL_None &&
  383. ownership != Qualifiers::OCL_ExplicitNone) {
  384. Address Object = createReferenceTemporary(*this, M, E);
  385. if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
  386. Object = Address(llvm::ConstantExpr::getBitCast(Var,
  387. ConvertTypeForMem(E->getType())
  388. ->getPointerTo(Object.getAddressSpace())),
  389. Object.getAlignment());
  390. // createReferenceTemporary will promote the temporary to a global with a
  391. // constant initializer if it can. It can only do this to a value of
  392. // ARC-manageable type if the value is global and therefore "immune" to
  393. // ref-counting operations. Therefore we have no need to emit either a
  394. // dynamic initialization or a cleanup and we can just return the address
  395. // of the temporary.
  396. if (Var->hasInitializer())
  397. return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
  398. Var->setInitializer(CGM.EmitNullConstant(E->getType()));
  399. }
  400. LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
  401. AlignmentSource::Decl);
  402. switch (getEvaluationKind(E->getType())) {
  403. default: llvm_unreachable("expected scalar or aggregate expression");
  404. case TEK_Scalar:
  405. EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
  406. break;
  407. case TEK_Aggregate: {
  408. EmitAggExpr(E, AggValueSlot::forAddr(Object,
  409. E->getType().getQualifiers(),
  410. AggValueSlot::IsDestructed,
  411. AggValueSlot::DoesNotNeedGCBarriers,
  412. AggValueSlot::IsNotAliased,
  413. AggValueSlot::DoesNotOverlap));
  414. break;
  415. }
  416. }
  417. pushTemporaryCleanup(*this, M, E, Object);
  418. return RefTempDst;
  419. }
  420. SmallVector<const Expr *, 2> CommaLHSs;
  421. SmallVector<SubobjectAdjustment, 2> Adjustments;
  422. E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  423. for (const auto &Ignored : CommaLHSs)
  424. EmitIgnoredExpr(Ignored);
  425. if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
  426. if (opaque->getType()->isRecordType()) {
  427. assert(Adjustments.empty());
  428. return EmitOpaqueValueLValue(opaque);
  429. }
  430. }
  431. // Create and initialize the reference temporary.
  432. Address Alloca = Address::invalid();
  433. Address Object = createReferenceTemporary(*this, M, E, &Alloca);
  434. if (auto *Var = dyn_cast<llvm::GlobalVariable>(
  435. Object.getPointer()->stripPointerCasts())) {
  436. Object = Address(llvm::ConstantExpr::getBitCast(
  437. cast<llvm::Constant>(Object.getPointer()),
  438. ConvertTypeForMem(E->getType())->getPointerTo()),
  439. Object.getAlignment());
  440. // If the temporary is a global and has a constant initializer or is a
  441. // constant temporary that we promoted to a global, we may have already
  442. // initialized it.
  443. if (!Var->hasInitializer()) {
  444. Var->setInitializer(CGM.EmitNullConstant(E->getType()));
  445. EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
  446. }
  447. } else {
  448. switch (M->getStorageDuration()) {
  449. case SD_Automatic:
  450. if (auto *Size = EmitLifetimeStart(
  451. CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
  452. Alloca.getPointer())) {
  453. pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
  454. Alloca, Size);
  455. }
  456. break;
  457. case SD_FullExpression: {
  458. if (!ShouldEmitLifetimeMarkers)
  459. break;
  460. // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
  461. // marker. Instead, start the lifetime of a conditional temporary earlier
  462. // so that it's unconditional. Don't do this in ASan's use-after-scope
  463. // mode so that it gets the more precise lifetime marks. If the type has
  464. // a non-trivial destructor, we'll have a cleanup block for it anyway,
  465. // so this typically doesn't help; skip it in that case.
  466. ConditionalEvaluation *OldConditional = nullptr;
  467. CGBuilderTy::InsertPoint OldIP;
  468. if (isInConditionalBranch() && !E->getType().isDestructedType() &&
  469. !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) {
  470. OldConditional = OutermostConditional;
  471. OutermostConditional = nullptr;
  472. OldIP = Builder.saveIP();
  473. llvm::BasicBlock *Block = OldConditional->getStartingBlock();
  474. Builder.restoreIP(CGBuilderTy::InsertPoint(
  475. Block, llvm::BasicBlock::iterator(Block->back())));
  476. }
  477. if (auto *Size = EmitLifetimeStart(
  478. CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
  479. Alloca.getPointer())) {
  480. pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
  481. Size);
  482. }
  483. if (OldConditional) {
  484. OutermostConditional = OldConditional;
  485. Builder.restoreIP(OldIP);
  486. }
  487. break;
  488. }
  489. default:
  490. break;
  491. }
  492. EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
  493. }
  494. pushTemporaryCleanup(*this, M, E, Object);
  495. // Perform derived-to-base casts and/or field accesses, to get from the
  496. // temporary object we created (and, potentially, for which we extended
  497. // the lifetime) to the subobject we're binding the reference to.
  498. for (unsigned I = Adjustments.size(); I != 0; --I) {
  499. SubobjectAdjustment &Adjustment = Adjustments[I-1];
  500. switch (Adjustment.Kind) {
  501. case SubobjectAdjustment::DerivedToBaseAdjustment:
  502. Object =
  503. GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
  504. Adjustment.DerivedToBase.BasePath->path_begin(),
  505. Adjustment.DerivedToBase.BasePath->path_end(),
  506. /*NullCheckValue=*/ false, E->getExprLoc());
  507. break;
  508. case SubobjectAdjustment::FieldAdjustment: {
  509. LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
  510. LV = EmitLValueForField(LV, Adjustment.Field);
  511. assert(LV.isSimple() &&
  512. "materialized temporary field is not a simple lvalue");
  513. Object = LV.getAddress();
  514. break;
  515. }
  516. case SubobjectAdjustment::MemberPointerAdjustment: {
  517. llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
  518. Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
  519. Adjustment.Ptr.MPT);
  520. break;
  521. }
  522. }
  523. }
  524. return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
  525. }
  526. RValue
  527. CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
  528. // Emit the expression as an lvalue.
  529. LValue LV = EmitLValue(E);
  530. assert(LV.isSimple());
  531. llvm::Value *Value = LV.getPointer();
  532. if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
  533. // C++11 [dcl.ref]p5 (as amended by core issue 453):
  534. // If a glvalue to which a reference is directly bound designates neither
  535. // an existing object or function of an appropriate type nor a region of
  536. // storage of suitable size and alignment to contain an object of the
  537. // reference's type, the behavior is undefined.
  538. QualType Ty = E->getType();
  539. EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
  540. }
  541. return RValue::get(Value);
  542. }
  543. /// getAccessedFieldNo - Given an encoded value and a result number, return the
  544. /// input field number being accessed.
  545. unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
  546. const llvm::Constant *Elts) {
  547. return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
  548. ->getZExtValue();
  549. }
  550. /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
  551. static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
  552. llvm::Value *High) {
  553. llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
  554. llvm::Value *K47 = Builder.getInt64(47);
  555. llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
  556. llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
  557. llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
  558. llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
  559. return Builder.CreateMul(B1, KMul);
  560. }
  561. bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
  562. return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
  563. TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
  564. }
  565. bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
  566. CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  567. return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
  568. (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
  569. TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
  570. TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
  571. }
  572. bool CodeGenFunction::sanitizePerformTypeCheck() const {
  573. return SanOpts.has(SanitizerKind::Null) |
  574. SanOpts.has(SanitizerKind::Alignment) |
  575. SanOpts.has(SanitizerKind::ObjectSize) |
  576. SanOpts.has(SanitizerKind::Vptr);
  577. }
  578. void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
  579. llvm::Value *Ptr, QualType Ty,
  580. CharUnits Alignment,
  581. SanitizerSet SkippedChecks,
  582. llvm::Value *ArraySize) {
  583. if (!sanitizePerformTypeCheck())
  584. return;
  585. // Don't check pointers outside the default address space. The null check
  586. // isn't correct, the object-size check isn't supported by LLVM, and we can't
  587. // communicate the addresses to the runtime handler for the vptr check.
  588. if (Ptr->getType()->getPointerAddressSpace())
  589. return;
  590. // Don't check pointers to volatile data. The behavior here is implementation-
  591. // defined.
  592. if (Ty.isVolatileQualified())
  593. return;
  594. SanitizerScope SanScope(this);
  595. SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
  596. llvm::BasicBlock *Done = nullptr;
  597. // Quickly determine whether we have a pointer to an alloca. It's possible
  598. // to skip null checks, and some alignment checks, for these pointers. This
  599. // can reduce compile-time significantly.
  600. auto PtrToAlloca =
  601. dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
  602. llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
  603. llvm::Value *IsNonNull = nullptr;
  604. bool IsGuaranteedNonNull =
  605. SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
  606. bool AllowNullPointers = isNullPointerAllowed(TCK);
  607. if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
  608. !IsGuaranteedNonNull) {
  609. // The glvalue must not be an empty glvalue.
  610. IsNonNull = Builder.CreateIsNotNull(Ptr);
  611. // The IR builder can constant-fold the null check if the pointer points to
  612. // a constant.
  613. IsGuaranteedNonNull = IsNonNull == True;
  614. // Skip the null check if the pointer is known to be non-null.
  615. if (!IsGuaranteedNonNull) {
  616. if (AllowNullPointers) {
  617. // When performing pointer casts, it's OK if the value is null.
  618. // Skip the remaining checks in that case.
  619. Done = createBasicBlock("null");
  620. llvm::BasicBlock *Rest = createBasicBlock("not.null");
  621. Builder.CreateCondBr(IsNonNull, Rest, Done);
  622. EmitBlock(Rest);
  623. } else {
  624. Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
  625. }
  626. }
  627. }
  628. if (SanOpts.has(SanitizerKind::ObjectSize) &&
  629. !SkippedChecks.has(SanitizerKind::ObjectSize) &&
  630. !Ty->isIncompleteType()) {
  631. uint64_t TySize = getContext().getTypeSizeInChars(Ty).getQuantity();
  632. llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
  633. if (ArraySize)
  634. Size = Builder.CreateMul(Size, ArraySize);
  635. // Degenerate case: new X[0] does not need an objectsize check.
  636. llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
  637. if (!ConstantSize || !ConstantSize->isNullValue()) {
  638. // The glvalue must refer to a large enough storage region.
  639. // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
  640. // to check this.
  641. // FIXME: Get object address space
  642. llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
  643. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
  644. llvm::Value *Min = Builder.getFalse();
  645. llvm::Value *NullIsUnknown = Builder.getFalse();
  646. llvm::Value *Dynamic = Builder.getFalse();
  647. llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
  648. llvm::Value *LargeEnough = Builder.CreateICmpUGE(
  649. Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown, Dynamic}), Size);
  650. Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
  651. }
  652. }
  653. uint64_t AlignVal = 0;
  654. llvm::Value *PtrAsInt = nullptr;
  655. if (SanOpts.has(SanitizerKind::Alignment) &&
  656. !SkippedChecks.has(SanitizerKind::Alignment)) {
  657. AlignVal = Alignment.getQuantity();
  658. if (!Ty->isIncompleteType() && !AlignVal)
  659. AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
  660. // The glvalue must be suitably aligned.
  661. if (AlignVal > 1 &&
  662. (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
  663. PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
  664. llvm::Value *Align = Builder.CreateAnd(
  665. PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
  666. llvm::Value *Aligned =
  667. Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
  668. if (Aligned != True)
  669. Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
  670. }
  671. }
  672. if (Checks.size() > 0) {
  673. // Make sure we're not losing information. Alignment needs to be a power of
  674. // 2
  675. assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
  676. llvm::Constant *StaticData[] = {
  677. EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
  678. llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
  679. llvm::ConstantInt::get(Int8Ty, TCK)};
  680. EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
  681. PtrAsInt ? PtrAsInt : Ptr);
  682. }
  683. // If possible, check that the vptr indicates that there is a subobject of
  684. // type Ty at offset zero within this object.
  685. //
  686. // C++11 [basic.life]p5,6:
  687. // [For storage which does not refer to an object within its lifetime]
  688. // The program has undefined behavior if:
  689. // -- the [pointer or glvalue] is used to access a non-static data member
  690. // or call a non-static member function
  691. if (SanOpts.has(SanitizerKind::Vptr) &&
  692. !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
  693. // Ensure that the pointer is non-null before loading it. If there is no
  694. // compile-time guarantee, reuse the run-time null check or emit a new one.
  695. if (!IsGuaranteedNonNull) {
  696. if (!IsNonNull)
  697. IsNonNull = Builder.CreateIsNotNull(Ptr);
  698. if (!Done)
  699. Done = createBasicBlock("vptr.null");
  700. llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
  701. Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
  702. EmitBlock(VptrNotNull);
  703. }
  704. // Compute a hash of the mangled name of the type.
  705. //
  706. // FIXME: This is not guaranteed to be deterministic! Move to a
  707. // fingerprinting mechanism once LLVM provides one. For the time
  708. // being the implementation happens to be deterministic.
  709. SmallString<64> MangledName;
  710. llvm::raw_svector_ostream Out(MangledName);
  711. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
  712. Out);
  713. // Blacklist based on the mangled type.
  714. if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
  715. SanitizerKind::Vptr, Out.str())) {
  716. llvm::hash_code TypeHash = hash_value(Out.str());
  717. // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
  718. llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
  719. llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
  720. Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
  721. llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
  722. llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
  723. llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
  724. Hash = Builder.CreateTrunc(Hash, IntPtrTy);
  725. // Look the hash up in our cache.
  726. const int CacheSize = 128;
  727. llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
  728. llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
  729. "__ubsan_vptr_type_cache");
  730. llvm::Value *Slot = Builder.CreateAnd(Hash,
  731. llvm::ConstantInt::get(IntPtrTy,
  732. CacheSize-1));
  733. llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
  734. llvm::Value *CacheVal =
  735. Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
  736. getPointerAlign());
  737. // If the hash isn't in the cache, call a runtime handler to perform the
  738. // hard work of checking whether the vptr is for an object of the right
  739. // type. This will either fill in the cache and return, or produce a
  740. // diagnostic.
  741. llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
  742. llvm::Constant *StaticData[] = {
  743. EmitCheckSourceLocation(Loc),
  744. EmitCheckTypeDescriptor(Ty),
  745. CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
  746. llvm::ConstantInt::get(Int8Ty, TCK)
  747. };
  748. llvm::Value *DynamicData[] = { Ptr, Hash };
  749. EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
  750. SanitizerHandler::DynamicTypeCacheMiss, StaticData,
  751. DynamicData);
  752. }
  753. }
  754. if (Done) {
  755. Builder.CreateBr(Done);
  756. EmitBlock(Done);
  757. }
  758. }
  759. /// Determine whether this expression refers to a flexible array member in a
  760. /// struct. We disable array bounds checks for such members.
  761. static bool isFlexibleArrayMemberExpr(const Expr *E) {
  762. // For compatibility with existing code, we treat arrays of length 0 or
  763. // 1 as flexible array members.
  764. const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
  765. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  766. if (CAT->getSize().ugt(1))
  767. return false;
  768. } else if (!isa<IncompleteArrayType>(AT))
  769. return false;
  770. E = E->IgnoreParens();
  771. // A flexible array member must be the last member in the class.
  772. if (const auto *ME = dyn_cast<MemberExpr>(E)) {
  773. // FIXME: If the base type of the member expr is not FD->getParent(),
  774. // this should not be treated as a flexible array member access.
  775. if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  776. RecordDecl::field_iterator FI(
  777. DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
  778. return ++FI == FD->getParent()->field_end();
  779. }
  780. } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
  781. return IRE->getDecl()->getNextIvar() == nullptr;
  782. }
  783. return false;
  784. }
  785. llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
  786. QualType EltTy) {
  787. ASTContext &C = getContext();
  788. uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
  789. if (!EltSize)
  790. return nullptr;
  791. auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  792. if (!ArrayDeclRef)
  793. return nullptr;
  794. auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
  795. if (!ParamDecl)
  796. return nullptr;
  797. auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
  798. if (!POSAttr)
  799. return nullptr;
  800. // Don't load the size if it's a lower bound.
  801. int POSType = POSAttr->getType();
  802. if (POSType != 0 && POSType != 1)
  803. return nullptr;
  804. // Find the implicit size parameter.
  805. auto PassedSizeIt = SizeArguments.find(ParamDecl);
  806. if (PassedSizeIt == SizeArguments.end())
  807. return nullptr;
  808. const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
  809. assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
  810. Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
  811. llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
  812. C.getSizeType(), E->getExprLoc());
  813. llvm::Value *SizeOfElement =
  814. llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
  815. return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
  816. }
  817. /// If Base is known to point to the start of an array, return the length of
  818. /// that array. Return 0 if the length cannot be determined.
  819. static llvm::Value *getArrayIndexingBound(
  820. CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
  821. // For the vector indexing extension, the bound is the number of elements.
  822. if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
  823. IndexedType = Base->getType();
  824. return CGF.Builder.getInt32(VT->getNumElements());
  825. }
  826. Base = Base->IgnoreParens();
  827. if (const auto *CE = dyn_cast<CastExpr>(Base)) {
  828. if (CE->getCastKind() == CK_ArrayToPointerDecay &&
  829. !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
  830. IndexedType = CE->getSubExpr()->getType();
  831. const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
  832. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
  833. return CGF.Builder.getInt(CAT->getSize());
  834. else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
  835. return CGF.getVLASize(VAT).NumElts;
  836. // Ignore pass_object_size here. It's not applicable on decayed pointers.
  837. }
  838. }
  839. QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
  840. if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
  841. IndexedType = Base->getType();
  842. return POS;
  843. }
  844. return nullptr;
  845. }
  846. void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
  847. llvm::Value *Index, QualType IndexType,
  848. bool Accessed) {
  849. assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
  850. "should not be called unless adding bounds checks");
  851. SanitizerScope SanScope(this);
  852. QualType IndexedType;
  853. llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
  854. if (!Bound)
  855. return;
  856. bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
  857. llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
  858. llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
  859. llvm::Constant *StaticData[] = {
  860. EmitCheckSourceLocation(E->getExprLoc()),
  861. EmitCheckTypeDescriptor(IndexedType),
  862. EmitCheckTypeDescriptor(IndexType)
  863. };
  864. llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
  865. : Builder.CreateICmpULE(IndexVal, BoundVal);
  866. EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
  867. SanitizerHandler::OutOfBounds, StaticData, Index);
  868. }
  869. CodeGenFunction::ComplexPairTy CodeGenFunction::
  870. EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  871. bool isInc, bool isPre) {
  872. ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
  873. llvm::Value *NextVal;
  874. if (isa<llvm::IntegerType>(InVal.first->getType())) {
  875. uint64_t AmountVal = isInc ? 1 : -1;
  876. NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
  877. // Add the inc/dec to the real part.
  878. NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
  879. } else {
  880. QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
  881. llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
  882. if (!isInc)
  883. FVal.changeSign();
  884. NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
  885. // Add the inc/dec to the real part.
  886. NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
  887. }
  888. ComplexPairTy IncVal(NextVal, InVal.second);
  889. // Store the updated result through the lvalue.
  890. EmitStoreOfComplex(IncVal, LV, /*init*/ false);
  891. // If this is a postinc, return the value read from memory, otherwise use the
  892. // updated value.
  893. return isPre ? IncVal : InVal;
  894. }
  895. void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
  896. CodeGenFunction *CGF) {
  897. // Bind VLAs in the cast type.
  898. if (CGF && E->getType()->isVariablyModifiedType())
  899. CGF->EmitVariablyModifiedType(E->getType());
  900. if (CGDebugInfo *DI = getModuleDebugInfo())
  901. DI->EmitExplicitCastType(E->getType());
  902. }
  903. //===----------------------------------------------------------------------===//
  904. // LValue Expression Emission
  905. //===----------------------------------------------------------------------===//
  906. /// EmitPointerWithAlignment - Given an expression of pointer type, try to
  907. /// derive a more accurate bound on the alignment of the pointer.
  908. Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
  909. LValueBaseInfo *BaseInfo,
  910. TBAAAccessInfo *TBAAInfo) {
  911. // We allow this with ObjC object pointers because of fragile ABIs.
  912. assert(E->getType()->isPointerType() ||
  913. E->getType()->isObjCObjectPointerType());
  914. E = E->IgnoreParens();
  915. // Casts:
  916. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  917. if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
  918. CGM.EmitExplicitCastExprType(ECE, this);
  919. switch (CE->getCastKind()) {
  920. // Non-converting casts (but not C's implicit conversion from void*).
  921. case CK_BitCast:
  922. case CK_NoOp:
  923. case CK_AddressSpaceConversion:
  924. if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
  925. if (PtrTy->getPointeeType()->isVoidType())
  926. break;
  927. LValueBaseInfo InnerBaseInfo;
  928. TBAAAccessInfo InnerTBAAInfo;
  929. Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
  930. &InnerBaseInfo,
  931. &InnerTBAAInfo);
  932. if (BaseInfo) *BaseInfo = InnerBaseInfo;
  933. if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
  934. if (isa<ExplicitCastExpr>(CE)) {
  935. LValueBaseInfo TargetTypeBaseInfo;
  936. TBAAAccessInfo TargetTypeTBAAInfo;
  937. CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
  938. &TargetTypeBaseInfo,
  939. &TargetTypeTBAAInfo);
  940. if (TBAAInfo)
  941. *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
  942. TargetTypeTBAAInfo);
  943. // If the source l-value is opaque, honor the alignment of the
  944. // casted-to type.
  945. if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
  946. if (BaseInfo)
  947. BaseInfo->mergeForCast(TargetTypeBaseInfo);
  948. Addr = Address(Addr.getPointer(), Align);
  949. }
  950. }
  951. if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
  952. CE->getCastKind() == CK_BitCast) {
  953. if (auto PT = E->getType()->getAs<PointerType>())
  954. EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
  955. /*MayBeNull=*/true,
  956. CodeGenFunction::CFITCK_UnrelatedCast,
  957. CE->getBeginLoc());
  958. }
  959. return CE->getCastKind() != CK_AddressSpaceConversion
  960. ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
  961. : Builder.CreateAddrSpaceCast(Addr,
  962. ConvertType(E->getType()));
  963. }
  964. break;
  965. // Array-to-pointer decay.
  966. case CK_ArrayToPointerDecay:
  967. return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
  968. // Derived-to-base conversions.
  969. case CK_UncheckedDerivedToBase:
  970. case CK_DerivedToBase: {
  971. // TODO: Support accesses to members of base classes in TBAA. For now, we
  972. // conservatively pretend that the complete object is of the base class
  973. // type.
  974. if (TBAAInfo)
  975. *TBAAInfo = CGM.getTBAAAccessInfo(E->getType());
  976. Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
  977. auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
  978. return GetAddressOfBaseClass(Addr, Derived,
  979. CE->path_begin(), CE->path_end(),
  980. ShouldNullCheckClassCastValue(CE),
  981. CE->getExprLoc());
  982. }
  983. // TODO: Is there any reason to treat base-to-derived conversions
  984. // specially?
  985. default:
  986. break;
  987. }
  988. }
  989. // Unary &.
  990. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  991. if (UO->getOpcode() == UO_AddrOf) {
  992. LValue LV = EmitLValue(UO->getSubExpr());
  993. if (BaseInfo) *BaseInfo = LV.getBaseInfo();
  994. if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
  995. return LV.getAddress();
  996. }
  997. }
  998. // TODO: conditional operators, comma.
  999. // Otherwise, use the alignment of the type.
  1000. CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo,
  1001. TBAAInfo);
  1002. return Address(EmitScalarExpr(E), Align);
  1003. }
  1004. RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
  1005. if (Ty->isVoidType())
  1006. return RValue::get(nullptr);
  1007. switch (getEvaluationKind(Ty)) {
  1008. case TEK_Complex: {
  1009. llvm::Type *EltTy =
  1010. ConvertType(Ty->castAs<ComplexType>()->getElementType());
  1011. llvm::Value *U = llvm::UndefValue::get(EltTy);
  1012. return RValue::getComplex(std::make_pair(U, U));
  1013. }
  1014. // If this is a use of an undefined aggregate type, the aggregate must have an
  1015. // identifiable address. Just because the contents of the value are undefined
  1016. // doesn't mean that the address can't be taken and compared.
  1017. case TEK_Aggregate: {
  1018. Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
  1019. return RValue::getAggregate(DestPtr);
  1020. }
  1021. case TEK_Scalar:
  1022. return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
  1023. }
  1024. llvm_unreachable("bad evaluation kind");
  1025. }
  1026. RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
  1027. const char *Name) {
  1028. ErrorUnsupported(E, Name);
  1029. return GetUndefRValue(E->getType());
  1030. }
  1031. LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
  1032. const char *Name) {
  1033. ErrorUnsupported(E, Name);
  1034. llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
  1035. return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
  1036. E->getType());
  1037. }
  1038. bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
  1039. const Expr *Base = Obj;
  1040. while (!isa<CXXThisExpr>(Base)) {
  1041. // The result of a dynamic_cast can be null.
  1042. if (isa<CXXDynamicCastExpr>(Base))
  1043. return false;
  1044. if (const auto *CE = dyn_cast<CastExpr>(Base)) {
  1045. Base = CE->getSubExpr();
  1046. } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
  1047. Base = PE->getSubExpr();
  1048. } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
  1049. if (UO->getOpcode() == UO_Extension)
  1050. Base = UO->getSubExpr();
  1051. else
  1052. return false;
  1053. } else {
  1054. return false;
  1055. }
  1056. }
  1057. return true;
  1058. }
  1059. LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
  1060. LValue LV;
  1061. if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
  1062. LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
  1063. else
  1064. LV = EmitLValue(E);
  1065. if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
  1066. SanitizerSet SkippedChecks;
  1067. if (const auto *ME = dyn_cast<MemberExpr>(E)) {
  1068. bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
  1069. if (IsBaseCXXThis)
  1070. SkippedChecks.set(SanitizerKind::Alignment, true);
  1071. if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
  1072. SkippedChecks.set(SanitizerKind::Null, true);
  1073. }
  1074. EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
  1075. E->getType(), LV.getAlignment(), SkippedChecks);
  1076. }
  1077. return LV;
  1078. }
  1079. /// EmitLValue - Emit code to compute a designator that specifies the location
  1080. /// of the expression.
  1081. ///
  1082. /// This can return one of two things: a simple address or a bitfield reference.
  1083. /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
  1084. /// an LLVM pointer type.
  1085. ///
  1086. /// If this returns a bitfield reference, nothing about the pointee type of the
  1087. /// LLVM value is known: For example, it may not be a pointer to an integer.
  1088. ///
  1089. /// If this returns a normal address, and if the lvalue's C type is fixed size,
  1090. /// this method guarantees that the returned pointer type will point to an LLVM
  1091. /// type of the same size of the lvalue's type. If the lvalue has a variable
  1092. /// length type, this is not possible.
  1093. ///
  1094. LValue CodeGenFunction::EmitLValue(const Expr *E) {
  1095. ApplyDebugLocation DL(*this, E);
  1096. switch (E->getStmtClass()) {
  1097. default: return EmitUnsupportedLValue(E, "l-value expression");
  1098. case Expr::ObjCPropertyRefExprClass:
  1099. llvm_unreachable("cannot emit a property reference directly");
  1100. case Expr::ObjCSelectorExprClass:
  1101. return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
  1102. case Expr::ObjCIsaExprClass:
  1103. return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
  1104. case Expr::BinaryOperatorClass:
  1105. return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
  1106. case Expr::CompoundAssignOperatorClass: {
  1107. QualType Ty = E->getType();
  1108. if (const AtomicType *AT = Ty->getAs<AtomicType>())
  1109. Ty = AT->getValueType();
  1110. if (!Ty->isAnyComplexType())
  1111. return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
  1112. return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
  1113. }
  1114. case Expr::CallExprClass:
  1115. case Expr::CXXMemberCallExprClass:
  1116. case Expr::CXXOperatorCallExprClass:
  1117. case Expr::UserDefinedLiteralClass:
  1118. return EmitCallExprLValue(cast<CallExpr>(E));
  1119. case Expr::VAArgExprClass:
  1120. return EmitVAArgExprLValue(cast<VAArgExpr>(E));
  1121. case Expr::DeclRefExprClass:
  1122. return EmitDeclRefLValue(cast<DeclRefExpr>(E));
  1123. case Expr::ConstantExprClass:
  1124. return EmitLValue(cast<ConstantExpr>(E)->getSubExpr());
  1125. case Expr::ParenExprClass:
  1126. return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
  1127. case Expr::GenericSelectionExprClass:
  1128. return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
  1129. case Expr::PredefinedExprClass:
  1130. return EmitPredefinedLValue(cast<PredefinedExpr>(E));
  1131. case Expr::StringLiteralClass:
  1132. return EmitStringLiteralLValue(cast<StringLiteral>(E));
  1133. case Expr::ObjCEncodeExprClass:
  1134. return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
  1135. case Expr::PseudoObjectExprClass:
  1136. return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
  1137. case Expr::InitListExprClass:
  1138. return EmitInitListLValue(cast<InitListExpr>(E));
  1139. case Expr::CXXTemporaryObjectExprClass:
  1140. case Expr::CXXConstructExprClass:
  1141. return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
  1142. case Expr::CXXBindTemporaryExprClass:
  1143. return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
  1144. case Expr::CXXUuidofExprClass:
  1145. return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
  1146. case Expr::LambdaExprClass:
  1147. return EmitAggExprToLValue(E);
  1148. case Expr::ExprWithCleanupsClass: {
  1149. const auto *cleanups = cast<ExprWithCleanups>(E);
  1150. enterFullExpression(cleanups);
  1151. RunCleanupsScope Scope(*this);
  1152. LValue LV = EmitLValue(cleanups->getSubExpr());
  1153. if (LV.isSimple()) {
  1154. // Defend against branches out of gnu statement expressions surrounded by
  1155. // cleanups.
  1156. llvm::Value *V = LV.getPointer();
  1157. Scope.ForceCleanup({&V});
  1158. return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
  1159. getContext(), LV.getBaseInfo(), LV.getTBAAInfo());
  1160. }
  1161. // FIXME: Is it possible to create an ExprWithCleanups that produces a
  1162. // bitfield lvalue or some other non-simple lvalue?
  1163. return LV;
  1164. }
  1165. case Expr::CXXDefaultArgExprClass: {
  1166. auto *DAE = cast<CXXDefaultArgExpr>(E);
  1167. CXXDefaultArgExprScope Scope(*this, DAE);
  1168. return EmitLValue(DAE->getExpr());
  1169. }
  1170. case Expr::CXXDefaultInitExprClass: {
  1171. auto *DIE = cast<CXXDefaultInitExpr>(E);
  1172. CXXDefaultInitExprScope Scope(*this, DIE);
  1173. return EmitLValue(DIE->getExpr());
  1174. }
  1175. case Expr::CXXTypeidExprClass:
  1176. return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
  1177. case Expr::ObjCMessageExprClass:
  1178. return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
  1179. case Expr::ObjCIvarRefExprClass:
  1180. return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
  1181. case Expr::StmtExprClass:
  1182. return EmitStmtExprLValue(cast<StmtExpr>(E));
  1183. case Expr::UnaryOperatorClass:
  1184. return EmitUnaryOpLValue(cast<UnaryOperator>(E));
  1185. case Expr::ArraySubscriptExprClass:
  1186. return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
  1187. case Expr::OMPArraySectionExprClass:
  1188. return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
  1189. case Expr::ExtVectorElementExprClass:
  1190. return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
  1191. case Expr::MemberExprClass:
  1192. return EmitMemberExpr(cast<MemberExpr>(E));
  1193. case Expr::CompoundLiteralExprClass:
  1194. return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
  1195. case Expr::ConditionalOperatorClass:
  1196. return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
  1197. case Expr::BinaryConditionalOperatorClass:
  1198. return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
  1199. case Expr::ChooseExprClass:
  1200. return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
  1201. case Expr::OpaqueValueExprClass:
  1202. return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
  1203. case Expr::SubstNonTypeTemplateParmExprClass:
  1204. return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
  1205. case Expr::ImplicitCastExprClass:
  1206. case Expr::CStyleCastExprClass:
  1207. case Expr::CXXFunctionalCastExprClass:
  1208. case Expr::CXXStaticCastExprClass:
  1209. case Expr::CXXDynamicCastExprClass:
  1210. case Expr::CXXReinterpretCastExprClass:
  1211. case Expr::CXXConstCastExprClass:
  1212. case Expr::ObjCBridgedCastExprClass:
  1213. return EmitCastLValue(cast<CastExpr>(E));
  1214. case Expr::MaterializeTemporaryExprClass:
  1215. return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
  1216. case Expr::CoawaitExprClass:
  1217. return EmitCoawaitLValue(cast<CoawaitExpr>(E));
  1218. case Expr::CoyieldExprClass:
  1219. return EmitCoyieldLValue(cast<CoyieldExpr>(E));
  1220. }
  1221. }
  1222. /// Given an object of the given canonical type, can we safely copy a
  1223. /// value out of it based on its initializer?
  1224. static bool isConstantEmittableObjectType(QualType type) {
  1225. assert(type.isCanonical());
  1226. assert(!type->isReferenceType());
  1227. // Must be const-qualified but non-volatile.
  1228. Qualifiers qs = type.getLocalQualifiers();
  1229. if (!qs.hasConst() || qs.hasVolatile()) return false;
  1230. // Otherwise, all object types satisfy this except C++ classes with
  1231. // mutable subobjects or non-trivial copy/destroy behavior.
  1232. if (const auto *RT = dyn_cast<RecordType>(type))
  1233. if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1234. if (RD->hasMutableFields() || !RD->isTrivial())
  1235. return false;
  1236. return true;
  1237. }
  1238. /// Can we constant-emit a load of a reference to a variable of the
  1239. /// given type? This is different from predicates like
  1240. /// Decl::mightBeUsableInConstantExpressions because we do want it to apply
  1241. /// in situations that don't necessarily satisfy the language's rules
  1242. /// for this (e.g. C++'s ODR-use rules). For example, we want to able
  1243. /// to do this with const float variables even if those variables
  1244. /// aren't marked 'constexpr'.
  1245. enum ConstantEmissionKind {
  1246. CEK_None,
  1247. CEK_AsReferenceOnly,
  1248. CEK_AsValueOrReference,
  1249. CEK_AsValueOnly
  1250. };
  1251. static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
  1252. type = type.getCanonicalType();
  1253. if (const auto *ref = dyn_cast<ReferenceType>(type)) {
  1254. if (isConstantEmittableObjectType(ref->getPointeeType()))
  1255. return CEK_AsValueOrReference;
  1256. return CEK_AsReferenceOnly;
  1257. }
  1258. if (isConstantEmittableObjectType(type))
  1259. return CEK_AsValueOnly;
  1260. return CEK_None;
  1261. }
  1262. /// Try to emit a reference to the given value without producing it as
  1263. /// an l-value. This is just an optimization, but it avoids us needing
  1264. /// to emit global copies of variables if they're named without triggering
  1265. /// a formal use in a context where we can't emit a direct reference to them,
  1266. /// for instance if a block or lambda or a member of a local class uses a
  1267. /// const int variable or constexpr variable from an enclosing function.
  1268. CodeGenFunction::ConstantEmission
  1269. CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
  1270. ValueDecl *value = refExpr->getDecl();
  1271. // The value needs to be an enum constant or a constant variable.
  1272. ConstantEmissionKind CEK;
  1273. if (isa<ParmVarDecl>(value)) {
  1274. CEK = CEK_None;
  1275. } else if (auto *var = dyn_cast<VarDecl>(value)) {
  1276. CEK = checkVarTypeForConstantEmission(var->getType());
  1277. } else if (isa<EnumConstantDecl>(value)) {
  1278. CEK = CEK_AsValueOnly;
  1279. } else {
  1280. CEK = CEK_None;
  1281. }
  1282. if (CEK == CEK_None) return ConstantEmission();
  1283. Expr::EvalResult result;
  1284. bool resultIsReference;
  1285. QualType resultType;
  1286. // It's best to evaluate all the way as an r-value if that's permitted.
  1287. if (CEK != CEK_AsReferenceOnly &&
  1288. refExpr->EvaluateAsRValue(result, getContext())) {
  1289. resultIsReference = false;
  1290. resultType = refExpr->getType();
  1291. // Otherwise, try to evaluate as an l-value.
  1292. } else if (CEK != CEK_AsValueOnly &&
  1293. refExpr->EvaluateAsLValue(result, getContext())) {
  1294. resultIsReference = true;
  1295. resultType = value->getType();
  1296. // Failure.
  1297. } else {
  1298. return ConstantEmission();
  1299. }
  1300. // In any case, if the initializer has side-effects, abandon ship.
  1301. if (result.HasSideEffects)
  1302. return ConstantEmission();
  1303. // Emit as a constant.
  1304. auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
  1305. result.Val, resultType);
  1306. // Make sure we emit a debug reference to the global variable.
  1307. // This should probably fire even for
  1308. if (isa<VarDecl>(value)) {
  1309. if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
  1310. EmitDeclRefExprDbgValue(refExpr, result.Val);
  1311. } else {
  1312. assert(isa<EnumConstantDecl>(value));
  1313. EmitDeclRefExprDbgValue(refExpr, result.Val);
  1314. }
  1315. // If we emitted a reference constant, we need to dereference that.
  1316. if (resultIsReference)
  1317. return ConstantEmission::forReference(C);
  1318. return ConstantEmission::forValue(C);
  1319. }
  1320. static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
  1321. const MemberExpr *ME) {
  1322. if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
  1323. // Try to emit static variable member expressions as DREs.
  1324. return DeclRefExpr::Create(
  1325. CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
  1326. /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
  1327. ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
  1328. }
  1329. return nullptr;
  1330. }
  1331. CodeGenFunction::ConstantEmission
  1332. CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
  1333. if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
  1334. return tryEmitAsConstant(DRE);
  1335. return ConstantEmission();
  1336. }
  1337. llvm::Value *CodeGenFunction::emitScalarConstant(
  1338. const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
  1339. assert(Constant && "not a constant");
  1340. if (Constant.isReference())
  1341. return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
  1342. E->getExprLoc())
  1343. .getScalarVal();
  1344. return Constant.getValue();
  1345. }
  1346. llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
  1347. SourceLocation Loc) {
  1348. return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
  1349. lvalue.getType(), Loc, lvalue.getBaseInfo(),
  1350. lvalue.getTBAAInfo(), lvalue.isNontemporal());
  1351. }
  1352. static bool hasBooleanRepresentation(QualType Ty) {
  1353. if (Ty->isBooleanType())
  1354. return true;
  1355. if (const EnumType *ET = Ty->getAs<EnumType>())
  1356. return ET->getDecl()->getIntegerType()->isBooleanType();
  1357. if (const AtomicType *AT = Ty->getAs<AtomicType>())
  1358. return hasBooleanRepresentation(AT->getValueType());
  1359. return false;
  1360. }
  1361. static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
  1362. llvm::APInt &Min, llvm::APInt &End,
  1363. bool StrictEnums, bool IsBool) {
  1364. const EnumType *ET = Ty->getAs<EnumType>();
  1365. bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
  1366. ET && !ET->getDecl()->isFixed();
  1367. if (!IsBool && !IsRegularCPlusPlusEnum)
  1368. return false;
  1369. if (IsBool) {
  1370. Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
  1371. End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
  1372. } else {
  1373. const EnumDecl *ED = ET->getDecl();
  1374. llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
  1375. unsigned Bitwidth = LTy->getScalarSizeInBits();
  1376. unsigned NumNegativeBits = ED->getNumNegativeBits();
  1377. unsigned NumPositiveBits = ED->getNumPositiveBits();
  1378. if (NumNegativeBits) {
  1379. unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
  1380. assert(NumBits <= Bitwidth);
  1381. End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
  1382. Min = -End;
  1383. } else {
  1384. assert(NumPositiveBits <= Bitwidth);
  1385. End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
  1386. Min = llvm::APInt(Bitwidth, 0);
  1387. }
  1388. }
  1389. return true;
  1390. }
  1391. llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
  1392. llvm::APInt Min, End;
  1393. if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
  1394. hasBooleanRepresentation(Ty)))
  1395. return nullptr;
  1396. llvm::MDBuilder MDHelper(getLLVMContext());
  1397. return MDHelper.createRange(Min, End);
  1398. }
  1399. bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
  1400. SourceLocation Loc) {
  1401. bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
  1402. bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
  1403. if (!HasBoolCheck && !HasEnumCheck)
  1404. return false;
  1405. bool IsBool = hasBooleanRepresentation(Ty) ||
  1406. NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
  1407. bool NeedsBoolCheck = HasBoolCheck && IsBool;
  1408. bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
  1409. if (!NeedsBoolCheck && !NeedsEnumCheck)
  1410. return false;
  1411. // Single-bit booleans don't need to be checked. Special-case this to avoid
  1412. // a bit width mismatch when handling bitfield values. This is handled by
  1413. // EmitFromMemory for the non-bitfield case.
  1414. if (IsBool &&
  1415. cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
  1416. return false;
  1417. llvm::APInt Min, End;
  1418. if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
  1419. return true;
  1420. auto &Ctx = getLLVMContext();
  1421. SanitizerScope SanScope(this);
  1422. llvm::Value *Check;
  1423. --End;
  1424. if (!Min) {
  1425. Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
  1426. } else {
  1427. llvm::Value *Upper =
  1428. Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
  1429. llvm::Value *Lower =
  1430. Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
  1431. Check = Builder.CreateAnd(Upper, Lower);
  1432. }
  1433. llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
  1434. EmitCheckTypeDescriptor(Ty)};
  1435. SanitizerMask Kind =
  1436. NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
  1437. EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
  1438. StaticArgs, EmitCheckValue(Value));
  1439. return true;
  1440. }
  1441. llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
  1442. QualType Ty,
  1443. SourceLocation Loc,
  1444. LValueBaseInfo BaseInfo,
  1445. TBAAAccessInfo TBAAInfo,
  1446. bool isNontemporal) {
  1447. if (!CGM.getCodeGenOpts().PreserveVec3Type) {
  1448. // For better performance, handle vector loads differently.
  1449. if (Ty->isVectorType()) {
  1450. const llvm::Type *EltTy = Addr.getElementType();
  1451. const auto *VTy = cast<llvm::VectorType>(EltTy);
  1452. // Handle vectors of size 3 like size 4 for better performance.
  1453. if (VTy->getNumElements() == 3) {
  1454. // Bitcast to vec4 type.
  1455. llvm::VectorType *vec4Ty =
  1456. llvm::VectorType::get(VTy->getElementType(), 4);
  1457. Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
  1458. // Now load value.
  1459. llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
  1460. // Shuffle vector to get vec3.
  1461. V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
  1462. {0, 1, 2}, "extractVec");
  1463. return EmitFromMemory(V, Ty);
  1464. }
  1465. }
  1466. }
  1467. // Atomic operations have to be done on integral types.
  1468. LValue AtomicLValue =
  1469. LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
  1470. if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
  1471. return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
  1472. }
  1473. llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
  1474. if (isNontemporal) {
  1475. llvm::MDNode *Node = llvm::MDNode::get(
  1476. Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
  1477. Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
  1478. }
  1479. CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
  1480. if (EmitScalarRangeCheck(Load, Ty, Loc)) {
  1481. // In order to prevent the optimizer from throwing away the check, don't
  1482. // attach range metadata to the load.
  1483. } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
  1484. if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
  1485. Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
  1486. return EmitFromMemory(Load, Ty);
  1487. }
  1488. llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
  1489. // Bool has a different representation in memory than in registers.
  1490. if (hasBooleanRepresentation(Ty)) {
  1491. // This should really always be an i1, but sometimes it's already
  1492. // an i8, and it's awkward to track those cases down.
  1493. if (Value->getType()->isIntegerTy(1))
  1494. return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
  1495. assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
  1496. "wrong value rep of bool");
  1497. }
  1498. return Value;
  1499. }
  1500. llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
  1501. // Bool has a different representation in memory than in registers.
  1502. if (hasBooleanRepresentation(Ty)) {
  1503. assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
  1504. "wrong value rep of bool");
  1505. return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
  1506. }
  1507. return Value;
  1508. }
  1509. void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
  1510. bool Volatile, QualType Ty,
  1511. LValueBaseInfo BaseInfo,
  1512. TBAAAccessInfo TBAAInfo,
  1513. bool isInit, bool isNontemporal) {
  1514. if (!CGM.getCodeGenOpts().PreserveVec3Type) {
  1515. // Handle vectors differently to get better performance.
  1516. if (Ty->isVectorType()) {
  1517. llvm::Type *SrcTy = Value->getType();
  1518. auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
  1519. // Handle vec3 special.
  1520. if (VecTy && VecTy->getNumElements() == 3) {
  1521. // Our source is a vec3, do a shuffle vector to make it a vec4.
  1522. llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
  1523. Builder.getInt32(2),
  1524. llvm::UndefValue::get(Builder.getInt32Ty())};
  1525. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1526. Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
  1527. MaskV, "extractVec");
  1528. SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
  1529. }
  1530. if (Addr.getElementType() != SrcTy) {
  1531. Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
  1532. }
  1533. }
  1534. }
  1535. Value = EmitToMemory(Value, Ty);
  1536. LValue AtomicLValue =
  1537. LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
  1538. if (Ty->isAtomicType() ||
  1539. (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
  1540. EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
  1541. return;
  1542. }
  1543. llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
  1544. if (isNontemporal) {
  1545. llvm::MDNode *Node =
  1546. llvm::MDNode::get(Store->getContext(),
  1547. llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
  1548. Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
  1549. }
  1550. CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
  1551. }
  1552. void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
  1553. bool isInit) {
  1554. EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
  1555. lvalue.getType(), lvalue.getBaseInfo(),
  1556. lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
  1557. }
  1558. /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
  1559. /// method emits the address of the lvalue, then loads the result as an rvalue,
  1560. /// returning the rvalue.
  1561. RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
  1562. if (LV.isObjCWeak()) {
  1563. // load of a __weak object.
  1564. Address AddrWeakObj = LV.getAddress();
  1565. return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
  1566. AddrWeakObj));
  1567. }
  1568. if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
  1569. // In MRC mode, we do a load+autorelease.
  1570. if (!getLangOpts().ObjCAutoRefCount) {
  1571. return RValue::get(EmitARCLoadWeak(LV.getAddress()));
  1572. }
  1573. // In ARC mode, we load retained and then consume the value.
  1574. llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
  1575. Object = EmitObjCConsumeObject(LV.getType(), Object);
  1576. return RValue::get(Object);
  1577. }
  1578. if (LV.isSimple()) {
  1579. assert(!LV.getType()->isFunctionType());
  1580. // Everything needs a load.
  1581. return RValue::get(EmitLoadOfScalar(LV, Loc));
  1582. }
  1583. if (LV.isVectorElt()) {
  1584. llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
  1585. LV.isVolatileQualified());
  1586. return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
  1587. "vecext"));
  1588. }
  1589. // If this is a reference to a subset of the elements of a vector, either
  1590. // shuffle the input or extract/insert them as appropriate.
  1591. if (LV.isExtVectorElt())
  1592. return EmitLoadOfExtVectorElementLValue(LV);
  1593. // Global Register variables always invoke intrinsics
  1594. if (LV.isGlobalReg())
  1595. return EmitLoadOfGlobalRegLValue(LV);
  1596. assert(LV.isBitField() && "Unknown LValue type!");
  1597. return EmitLoadOfBitfieldLValue(LV, Loc);
  1598. }
  1599. RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
  1600. SourceLocation Loc) {
  1601. const CGBitFieldInfo &Info = LV.getBitFieldInfo();
  1602. // Get the output type.
  1603. llvm::Type *ResLTy = ConvertType(LV.getType());
  1604. Address Ptr = LV.getBitFieldAddress();
  1605. llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
  1606. if (Info.IsSigned) {
  1607. assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
  1608. unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
  1609. if (HighBits)
  1610. Val = Builder.CreateShl(Val, HighBits, "bf.shl");
  1611. if (Info.Offset + HighBits)
  1612. Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
  1613. } else {
  1614. if (Info.Offset)
  1615. Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
  1616. if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
  1617. Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
  1618. Info.Size),
  1619. "bf.clear");
  1620. }
  1621. Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
  1622. EmitScalarRangeCheck(Val, LV.getType(), Loc);
  1623. return RValue::get(Val);
  1624. }
  1625. // If this is a reference to a subset of the elements of a vector, create an
  1626. // appropriate shufflevector.
  1627. RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
  1628. llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
  1629. LV.isVolatileQualified());
  1630. const llvm::Constant *Elts = LV.getExtVectorElts();
  1631. // If the result of the expression is a non-vector type, we must be extracting
  1632. // a single element. Just codegen as an extractelement.
  1633. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  1634. if (!ExprVT) {
  1635. unsigned InIdx = getAccessedFieldNo(0, Elts);
  1636. llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
  1637. return RValue::get(Builder.CreateExtractElement(Vec, Elt));
  1638. }
  1639. // Always use shuffle vector to try to retain the original program structure
  1640. unsigned NumResultElts = ExprVT->getNumElements();
  1641. SmallVector<llvm::Constant*, 4> Mask;
  1642. for (unsigned i = 0; i != NumResultElts; ++i)
  1643. Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
  1644. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1645. Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
  1646. MaskV);
  1647. return RValue::get(Vec);
  1648. }
  1649. /// Generates lvalue for partial ext_vector access.
  1650. Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
  1651. Address VectorAddress = LV.getExtVectorAddress();
  1652. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  1653. QualType EQT = ExprVT->getElementType();
  1654. llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
  1655. Address CastToPointerElement =
  1656. Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
  1657. "conv.ptr.element");
  1658. const llvm::Constant *Elts = LV.getExtVectorElts();
  1659. unsigned ix = getAccessedFieldNo(0, Elts);
  1660. Address VectorBasePtrPlusIx =
  1661. Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
  1662. "vector.elt");
  1663. return VectorBasePtrPlusIx;
  1664. }
  1665. /// Load of global gamed gegisters are always calls to intrinsics.
  1666. RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
  1667. assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
  1668. "Bad type for register variable");
  1669. llvm::MDNode *RegName = cast<llvm::MDNode>(
  1670. cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
  1671. // We accept integer and pointer types only
  1672. llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
  1673. llvm::Type *Ty = OrigTy;
  1674. if (OrigTy->isPointerTy())
  1675. Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
  1676. llvm::Type *Types[] = { Ty };
  1677. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
  1678. llvm::Value *Call = Builder.CreateCall(
  1679. F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
  1680. if (OrigTy->isPointerTy())
  1681. Call = Builder.CreateIntToPtr(Call, OrigTy);
  1682. return RValue::get(Call);
  1683. }
  1684. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  1685. /// lvalue, where both are guaranteed to the have the same type, and that type
  1686. /// is 'Ty'.
  1687. void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
  1688. bool isInit) {
  1689. if (!Dst.isSimple()) {
  1690. if (Dst.isVectorElt()) {
  1691. // Read/modify/write the vector, inserting the new element.
  1692. llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
  1693. Dst.isVolatileQualified());
  1694. Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
  1695. Dst.getVectorIdx(), "vecins");
  1696. Builder.CreateStore(Vec, Dst.getVectorAddress(),
  1697. Dst.isVolatileQualified());
  1698. return;
  1699. }
  1700. // If this is an update of extended vector elements, insert them as
  1701. // appropriate.
  1702. if (Dst.isExtVectorElt())
  1703. return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
  1704. if (Dst.isGlobalReg())
  1705. return EmitStoreThroughGlobalRegLValue(Src, Dst);
  1706. assert(Dst.isBitField() && "Unknown LValue type");
  1707. return EmitStoreThroughBitfieldLValue(Src, Dst);
  1708. }
  1709. // There's special magic for assigning into an ARC-qualified l-value.
  1710. if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
  1711. switch (Lifetime) {
  1712. case Qualifiers::OCL_None:
  1713. llvm_unreachable("present but none");
  1714. case Qualifiers::OCL_ExplicitNone:
  1715. // nothing special
  1716. break;
  1717. case Qualifiers::OCL_Strong:
  1718. if (isInit) {
  1719. Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
  1720. break;
  1721. }
  1722. EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
  1723. return;
  1724. case Qualifiers::OCL_Weak:
  1725. if (isInit)
  1726. // Initialize and then skip the primitive store.
  1727. EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
  1728. else
  1729. EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
  1730. return;
  1731. case Qualifiers::OCL_Autoreleasing:
  1732. Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
  1733. Src.getScalarVal()));
  1734. // fall into the normal path
  1735. break;
  1736. }
  1737. }
  1738. if (Dst.isObjCWeak() && !Dst.isNonGC()) {
  1739. // load of a __weak object.
  1740. Address LvalueDst = Dst.getAddress();
  1741. llvm::Value *src = Src.getScalarVal();
  1742. CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
  1743. return;
  1744. }
  1745. if (Dst.isObjCStrong() && !Dst.isNonGC()) {
  1746. // load of a __strong object.
  1747. Address LvalueDst = Dst.getAddress();
  1748. llvm::Value *src = Src.getScalarVal();
  1749. if (Dst.isObjCIvar()) {
  1750. assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
  1751. llvm::Type *ResultType = IntPtrTy;
  1752. Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
  1753. llvm::Value *RHS = dst.getPointer();
  1754. RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
  1755. llvm::Value *LHS =
  1756. Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
  1757. "sub.ptr.lhs.cast");
  1758. llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
  1759. CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
  1760. BytesBetween);
  1761. } else if (Dst.isGlobalObjCRef()) {
  1762. CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
  1763. Dst.isThreadLocalRef());
  1764. }
  1765. else
  1766. CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
  1767. return;
  1768. }
  1769. assert(Src.isScalar() && "Can't emit an agg store with this method");
  1770. EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
  1771. }
  1772. void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  1773. llvm::Value **Result) {
  1774. const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
  1775. llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
  1776. Address Ptr = Dst.getBitFieldAddress();
  1777. // Get the source value, truncated to the width of the bit-field.
  1778. llvm::Value *SrcVal = Src.getScalarVal();
  1779. // Cast the source to the storage type and shift it into place.
  1780. SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
  1781. /*IsSigned=*/false);
  1782. llvm::Value *MaskedVal = SrcVal;
  1783. // See if there are other bits in the bitfield's storage we'll need to load
  1784. // and mask together with source before storing.
  1785. if (Info.StorageSize != Info.Size) {
  1786. assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
  1787. llvm::Value *Val =
  1788. Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
  1789. // Mask the source value as needed.
  1790. if (!hasBooleanRepresentation(Dst.getType()))
  1791. SrcVal = Builder.CreateAnd(SrcVal,
  1792. llvm::APInt::getLowBitsSet(Info.StorageSize,
  1793. Info.Size),
  1794. "bf.value");
  1795. MaskedVal = SrcVal;
  1796. if (Info.Offset)
  1797. SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
  1798. // Mask out the original value.
  1799. Val = Builder.CreateAnd(Val,
  1800. ~llvm::APInt::getBitsSet(Info.StorageSize,
  1801. Info.Offset,
  1802. Info.Offset + Info.Size),
  1803. "bf.clear");
  1804. // Or together the unchanged values and the source value.
  1805. SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
  1806. } else {
  1807. assert(Info.Offset == 0);
  1808. }
  1809. // Write the new value back out.
  1810. Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
  1811. // Return the new value of the bit-field, if requested.
  1812. if (Result) {
  1813. llvm::Value *ResultVal = MaskedVal;
  1814. // Sign extend the value if needed.
  1815. if (Info.IsSigned) {
  1816. assert(Info.Size <= Info.StorageSize);
  1817. unsigned HighBits = Info.StorageSize - Info.Size;
  1818. if (HighBits) {
  1819. ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
  1820. ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
  1821. }
  1822. }
  1823. ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
  1824. "bf.result.cast");
  1825. *Result = EmitFromMemory(ResultVal, Dst.getType());
  1826. }
  1827. }
  1828. void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
  1829. LValue Dst) {
  1830. // This access turns into a read/modify/write of the vector. Load the input
  1831. // value now.
  1832. llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
  1833. Dst.isVolatileQualified());
  1834. const llvm::Constant *Elts = Dst.getExtVectorElts();
  1835. llvm::Value *SrcVal = Src.getScalarVal();
  1836. if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
  1837. unsigned NumSrcElts = VTy->getNumElements();
  1838. unsigned NumDstElts = Vec->getType()->getVectorNumElements();
  1839. if (NumDstElts == NumSrcElts) {
  1840. // Use shuffle vector is the src and destination are the same number of
  1841. // elements and restore the vector mask since it is on the side it will be
  1842. // stored.
  1843. SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
  1844. for (unsigned i = 0; i != NumSrcElts; ++i)
  1845. Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
  1846. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1847. Vec = Builder.CreateShuffleVector(SrcVal,
  1848. llvm::UndefValue::get(Vec->getType()),
  1849. MaskV);
  1850. } else if (NumDstElts > NumSrcElts) {
  1851. // Extended the source vector to the same length and then shuffle it
  1852. // into the destination.
  1853. // FIXME: since we're shuffling with undef, can we just use the indices
  1854. // into that? This could be simpler.
  1855. SmallVector<llvm::Constant*, 4> ExtMask;
  1856. for (unsigned i = 0; i != NumSrcElts; ++i)
  1857. ExtMask.push_back(Builder.getInt32(i));
  1858. ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
  1859. llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
  1860. llvm::Value *ExtSrcVal =
  1861. Builder.CreateShuffleVector(SrcVal,
  1862. llvm::UndefValue::get(SrcVal->getType()),
  1863. ExtMaskV);
  1864. // build identity
  1865. SmallVector<llvm::Constant*, 4> Mask;
  1866. for (unsigned i = 0; i != NumDstElts; ++i)
  1867. Mask.push_back(Builder.getInt32(i));
  1868. // When the vector size is odd and .odd or .hi is used, the last element
  1869. // of the Elts constant array will be one past the size of the vector.
  1870. // Ignore the last element here, if it is greater than the mask size.
  1871. if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
  1872. NumSrcElts--;
  1873. // modify when what gets shuffled in
  1874. for (unsigned i = 0; i != NumSrcElts; ++i)
  1875. Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
  1876. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1877. Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
  1878. } else {
  1879. // We should never shorten the vector
  1880. llvm_unreachable("unexpected shorten vector length");
  1881. }
  1882. } else {
  1883. // If the Src is a scalar (not a vector) it must be updating one element.
  1884. unsigned InIdx = getAccessedFieldNo(0, Elts);
  1885. llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
  1886. Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
  1887. }
  1888. Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
  1889. Dst.isVolatileQualified());
  1890. }
  1891. /// Store of global named registers are always calls to intrinsics.
  1892. void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
  1893. assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
  1894. "Bad type for register variable");
  1895. llvm::MDNode *RegName = cast<llvm::MDNode>(
  1896. cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
  1897. assert(RegName && "Register LValue is not metadata");
  1898. // We accept integer and pointer types only
  1899. llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
  1900. llvm::Type *Ty = OrigTy;
  1901. if (OrigTy->isPointerTy())
  1902. Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
  1903. llvm::Type *Types[] = { Ty };
  1904. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
  1905. llvm::Value *Value = Src.getScalarVal();
  1906. if (OrigTy->isPointerTy())
  1907. Value = Builder.CreatePtrToInt(Value, Ty);
  1908. Builder.CreateCall(
  1909. F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
  1910. }
  1911. // setObjCGCLValueClass - sets class of the lvalue for the purpose of
  1912. // generating write-barries API. It is currently a global, ivar,
  1913. // or neither.
  1914. static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
  1915. LValue &LV,
  1916. bool IsMemberAccess=false) {
  1917. if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
  1918. return;
  1919. if (isa<ObjCIvarRefExpr>(E)) {
  1920. QualType ExpTy = E->getType();
  1921. if (IsMemberAccess && ExpTy->isPointerType()) {
  1922. // If ivar is a structure pointer, assigning to field of
  1923. // this struct follows gcc's behavior and makes it a non-ivar
  1924. // writer-barrier conservatively.
  1925. ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
  1926. if (ExpTy->isRecordType()) {
  1927. LV.setObjCIvar(false);
  1928. return;
  1929. }
  1930. }
  1931. LV.setObjCIvar(true);
  1932. auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
  1933. LV.setBaseIvarExp(Exp->getBase());
  1934. LV.setObjCArray(E->getType()->isArrayType());
  1935. return;
  1936. }
  1937. if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
  1938. if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
  1939. if (VD->hasGlobalStorage()) {
  1940. LV.setGlobalObjCRef(true);
  1941. LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
  1942. }
  1943. }
  1944. LV.setObjCArray(E->getType()->isArrayType());
  1945. return;
  1946. }
  1947. if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
  1948. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1949. return;
  1950. }
  1951. if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
  1952. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1953. if (LV.isObjCIvar()) {
  1954. // If cast is to a structure pointer, follow gcc's behavior and make it
  1955. // a non-ivar write-barrier.
  1956. QualType ExpTy = E->getType();
  1957. if (ExpTy->isPointerType())
  1958. ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
  1959. if (ExpTy->isRecordType())
  1960. LV.setObjCIvar(false);
  1961. }
  1962. return;
  1963. }
  1964. if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
  1965. setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
  1966. return;
  1967. }
  1968. if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
  1969. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1970. return;
  1971. }
  1972. if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
  1973. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1974. return;
  1975. }
  1976. if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
  1977. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1978. return;
  1979. }
  1980. if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
  1981. setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
  1982. if (LV.isObjCIvar() && !LV.isObjCArray())
  1983. // Using array syntax to assigning to what an ivar points to is not
  1984. // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
  1985. LV.setObjCIvar(false);
  1986. else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
  1987. // Using array syntax to assigning to what global points to is not
  1988. // same as assigning to the global itself. {id *G;} G[i] = 0;
  1989. LV.setGlobalObjCRef(false);
  1990. return;
  1991. }
  1992. if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
  1993. setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
  1994. // We don't know if member is an 'ivar', but this flag is looked at
  1995. // only in the context of LV.isObjCIvar().
  1996. LV.setObjCArray(E->getType()->isArrayType());
  1997. return;
  1998. }
  1999. }
  2000. static llvm::Value *
  2001. EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
  2002. llvm::Value *V, llvm::Type *IRType,
  2003. StringRef Name = StringRef()) {
  2004. unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
  2005. return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
  2006. }
  2007. static LValue EmitThreadPrivateVarDeclLValue(
  2008. CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
  2009. llvm::Type *RealVarTy, SourceLocation Loc) {
  2010. Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
  2011. Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
  2012. return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
  2013. }
  2014. static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
  2015. const VarDecl *VD, QualType T) {
  2016. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2017. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2018. // Return an invalid address if variable is MT_To and unified
  2019. // memory is not enabled. For all other cases: MT_Link and
  2020. // MT_To with unified memory, return a valid address.
  2021. if (!Res || (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2022. !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
  2023. return Address::invalid();
  2024. assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
  2025. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2026. CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
  2027. "Expected link clause OR to clause with unified memory enabled.");
  2028. QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
  2029. Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
  2030. return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
  2031. }
  2032. Address
  2033. CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
  2034. LValueBaseInfo *PointeeBaseInfo,
  2035. TBAAAccessInfo *PointeeTBAAInfo) {
  2036. llvm::LoadInst *Load = Builder.CreateLoad(RefLVal.getAddress(),
  2037. RefLVal.isVolatile());
  2038. CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
  2039. CharUnits Align = getNaturalTypeAlignment(RefLVal.getType()->getPointeeType(),
  2040. PointeeBaseInfo, PointeeTBAAInfo,
  2041. /* forPointeeType= */ true);
  2042. return Address(Load, Align);
  2043. }
  2044. LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
  2045. LValueBaseInfo PointeeBaseInfo;
  2046. TBAAAccessInfo PointeeTBAAInfo;
  2047. Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
  2048. &PointeeTBAAInfo);
  2049. return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
  2050. PointeeBaseInfo, PointeeTBAAInfo);
  2051. }
  2052. Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
  2053. const PointerType *PtrTy,
  2054. LValueBaseInfo *BaseInfo,
  2055. TBAAAccessInfo *TBAAInfo) {
  2056. llvm::Value *Addr = Builder.CreateLoad(Ptr);
  2057. return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
  2058. BaseInfo, TBAAInfo,
  2059. /*forPointeeType=*/true));
  2060. }
  2061. LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
  2062. const PointerType *PtrTy) {
  2063. LValueBaseInfo BaseInfo;
  2064. TBAAAccessInfo TBAAInfo;
  2065. Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
  2066. return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
  2067. }
  2068. static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
  2069. const Expr *E, const VarDecl *VD) {
  2070. QualType T = E->getType();
  2071. // If it's thread_local, emit a call to its wrapper function instead.
  2072. if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
  2073. CGF.CGM.getCXXABI().usesThreadWrapperFunction())
  2074. return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
  2075. // Check if the variable is marked as declare target with link clause in
  2076. // device codegen.
  2077. if (CGF.getLangOpts().OpenMPIsDevice) {
  2078. Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
  2079. if (Addr.isValid())
  2080. return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
  2081. }
  2082. llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
  2083. llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
  2084. V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
  2085. CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
  2086. Address Addr(V, Alignment);
  2087. // Emit reference to the private copy of the variable if it is an OpenMP
  2088. // threadprivate variable.
  2089. if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
  2090. VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  2091. return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
  2092. E->getExprLoc());
  2093. }
  2094. LValue LV = VD->getType()->isReferenceType() ?
  2095. CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
  2096. AlignmentSource::Decl) :
  2097. CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
  2098. setObjCGCLValueClass(CGF.getContext(), E, LV);
  2099. return LV;
  2100. }
  2101. static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
  2102. const FunctionDecl *FD) {
  2103. if (FD->hasAttr<WeakRefAttr>()) {
  2104. ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
  2105. return aliasee.getPointer();
  2106. }
  2107. llvm::Constant *V = CGM.GetAddrOfFunction(FD);
  2108. if (!FD->hasPrototype()) {
  2109. if (const FunctionProtoType *Proto =
  2110. FD->getType()->getAs<FunctionProtoType>()) {
  2111. // Ugly case: for a K&R-style definition, the type of the definition
  2112. // isn't the same as the type of a use. Correct for this with a
  2113. // bitcast.
  2114. QualType NoProtoType =
  2115. CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
  2116. NoProtoType = CGM.getContext().getPointerType(NoProtoType);
  2117. V = llvm::ConstantExpr::getBitCast(V,
  2118. CGM.getTypes().ConvertType(NoProtoType));
  2119. }
  2120. }
  2121. return V;
  2122. }
  2123. static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
  2124. const Expr *E, const FunctionDecl *FD) {
  2125. llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
  2126. CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
  2127. return CGF.MakeAddrLValue(V, E->getType(), Alignment,
  2128. AlignmentSource::Decl);
  2129. }
  2130. static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
  2131. llvm::Value *ThisValue) {
  2132. QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
  2133. LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
  2134. return CGF.EmitLValueForField(LV, FD);
  2135. }
  2136. /// Named Registers are named metadata pointing to the register name
  2137. /// which will be read from/written to as an argument to the intrinsic
  2138. /// @llvm.read/write_register.
  2139. /// So far, only the name is being passed down, but other options such as
  2140. /// register type, allocation type or even optimization options could be
  2141. /// passed down via the metadata node.
  2142. static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
  2143. SmallString<64> Name("llvm.named.register.");
  2144. AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
  2145. assert(Asm->getLabel().size() < 64-Name.size() &&
  2146. "Register name too big");
  2147. Name.append(Asm->getLabel());
  2148. llvm::NamedMDNode *M =
  2149. CGM.getModule().getOrInsertNamedMetadata(Name);
  2150. if (M->getNumOperands() == 0) {
  2151. llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
  2152. Asm->getLabel());
  2153. llvm::Metadata *Ops[] = {Str};
  2154. M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  2155. }
  2156. CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
  2157. llvm::Value *Ptr =
  2158. llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
  2159. return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
  2160. }
  2161. /// Determine whether we can emit a reference to \p VD from the current
  2162. /// context, despite not necessarily having seen an odr-use of the variable in
  2163. /// this context.
  2164. static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
  2165. const DeclRefExpr *E,
  2166. const VarDecl *VD,
  2167. bool IsConstant) {
  2168. // For a variable declared in an enclosing scope, do not emit a spurious
  2169. // reference even if we have a capture, as that will emit an unwarranted
  2170. // reference to our capture state, and will likely generate worse code than
  2171. // emitting a local copy.
  2172. if (E->refersToEnclosingVariableOrCapture())
  2173. return false;
  2174. // For a local declaration declared in this function, we can always reference
  2175. // it even if we don't have an odr-use.
  2176. if (VD->hasLocalStorage()) {
  2177. return VD->getDeclContext() ==
  2178. dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
  2179. }
  2180. // For a global declaration, we can emit a reference to it if we know
  2181. // for sure that we are able to emit a definition of it.
  2182. VD = VD->getDefinition(CGF.getContext());
  2183. if (!VD)
  2184. return false;
  2185. // Don't emit a spurious reference if it might be to a variable that only
  2186. // exists on a different device / target.
  2187. // FIXME: This is unnecessarily broad. Check whether this would actually be a
  2188. // cross-target reference.
  2189. if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
  2190. CGF.getLangOpts().OpenCL) {
  2191. return false;
  2192. }
  2193. // We can emit a spurious reference only if the linkage implies that we'll
  2194. // be emitting a non-interposable symbol that will be retained until link
  2195. // time.
  2196. switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) {
  2197. case llvm::GlobalValue::ExternalLinkage:
  2198. case llvm::GlobalValue::LinkOnceODRLinkage:
  2199. case llvm::GlobalValue::WeakODRLinkage:
  2200. case llvm::GlobalValue::InternalLinkage:
  2201. case llvm::GlobalValue::PrivateLinkage:
  2202. return true;
  2203. default:
  2204. return false;
  2205. }
  2206. }
  2207. LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
  2208. const NamedDecl *ND = E->getDecl();
  2209. QualType T = E->getType();
  2210. assert(E->isNonOdrUse() != NOUR_Unevaluated &&
  2211. "should not emit an unevaluated operand");
  2212. if (const auto *VD = dyn_cast<VarDecl>(ND)) {
  2213. // Global Named registers access via intrinsics only
  2214. if (VD->getStorageClass() == SC_Register &&
  2215. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
  2216. return EmitGlobalNamedRegister(VD, CGM);
  2217. // If this DeclRefExpr does not constitute an odr-use of the variable,
  2218. // we're not permitted to emit a reference to it in general, and it might
  2219. // not be captured if capture would be necessary for a use. Emit the
  2220. // constant value directly instead.
  2221. if (E->isNonOdrUse() == NOUR_Constant &&
  2222. (VD->getType()->isReferenceType() ||
  2223. !canEmitSpuriousReferenceToVariable(*this, E, VD, true))) {
  2224. VD->getAnyInitializer(VD);
  2225. llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
  2226. E->getLocation(), *VD->evaluateValue(), VD->getType());
  2227. assert(Val && "failed to emit constant expression");
  2228. Address Addr = Address::invalid();
  2229. if (!VD->getType()->isReferenceType()) {
  2230. // Spill the constant value to a global.
  2231. Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
  2232. getContext().getDeclAlign(VD));
  2233. } else {
  2234. // Should we be using the alignment of the constant pointer we emitted?
  2235. CharUnits Alignment =
  2236. getNaturalTypeAlignment(E->getType(),
  2237. /* BaseInfo= */ nullptr,
  2238. /* TBAAInfo= */ nullptr,
  2239. /* forPointeeType= */ true);
  2240. Addr = Address(Val, Alignment);
  2241. }
  2242. return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
  2243. }
  2244. // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
  2245. // Check for captured variables.
  2246. if (E->refersToEnclosingVariableOrCapture()) {
  2247. VD = VD->getCanonicalDecl();
  2248. if (auto *FD = LambdaCaptureFields.lookup(VD))
  2249. return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
  2250. else if (CapturedStmtInfo) {
  2251. auto I = LocalDeclMap.find(VD);
  2252. if (I != LocalDeclMap.end()) {
  2253. if (VD->getType()->isReferenceType())
  2254. return EmitLoadOfReferenceLValue(I->second, VD->getType(),
  2255. AlignmentSource::Decl);
  2256. return MakeAddrLValue(I->second, T);
  2257. }
  2258. LValue CapLVal =
  2259. EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
  2260. CapturedStmtInfo->getContextValue());
  2261. return MakeAddrLValue(
  2262. Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
  2263. CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
  2264. CapLVal.getTBAAInfo());
  2265. }
  2266. assert(isa<BlockDecl>(CurCodeDecl));
  2267. Address addr = GetAddrOfBlockDecl(VD);
  2268. return MakeAddrLValue(addr, T, AlignmentSource::Decl);
  2269. }
  2270. }
  2271. // FIXME: We should be able to assert this for FunctionDecls as well!
  2272. // FIXME: We should be able to assert this for all DeclRefExprs, not just
  2273. // those with a valid source location.
  2274. assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
  2275. !E->getLocation().isValid()) &&
  2276. "Should not use decl without marking it used!");
  2277. if (ND->hasAttr<WeakRefAttr>()) {
  2278. const auto *VD = cast<ValueDecl>(ND);
  2279. ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
  2280. return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
  2281. }
  2282. if (const auto *VD = dyn_cast<VarDecl>(ND)) {
  2283. // Check if this is a global variable.
  2284. if (VD->hasLinkage() || VD->isStaticDataMember())
  2285. return EmitGlobalVarDeclLValue(*this, E, VD);
  2286. Address addr = Address::invalid();
  2287. // The variable should generally be present in the local decl map.
  2288. auto iter = LocalDeclMap.find(VD);
  2289. if (iter != LocalDeclMap.end()) {
  2290. addr = iter->second;
  2291. // Otherwise, it might be static local we haven't emitted yet for
  2292. // some reason; most likely, because it's in an outer function.
  2293. } else if (VD->isStaticLocal()) {
  2294. addr = Address(CGM.getOrCreateStaticVarDecl(
  2295. *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
  2296. getContext().getDeclAlign(VD));
  2297. // No other cases for now.
  2298. } else {
  2299. llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
  2300. }
  2301. // Check for OpenMP threadprivate variables.
  2302. if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
  2303. VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  2304. return EmitThreadPrivateVarDeclLValue(
  2305. *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
  2306. E->getExprLoc());
  2307. }
  2308. // Drill into block byref variables.
  2309. bool isBlockByref = VD->isEscapingByref();
  2310. if (isBlockByref) {
  2311. addr = emitBlockByrefAddress(addr, VD);
  2312. }
  2313. // Drill into reference types.
  2314. LValue LV = VD->getType()->isReferenceType() ?
  2315. EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
  2316. MakeAddrLValue(addr, T, AlignmentSource::Decl);
  2317. bool isLocalStorage = VD->hasLocalStorage();
  2318. bool NonGCable = isLocalStorage &&
  2319. !VD->getType()->isReferenceType() &&
  2320. !isBlockByref;
  2321. if (NonGCable) {
  2322. LV.getQuals().removeObjCGCAttr();
  2323. LV.setNonGC(true);
  2324. }
  2325. bool isImpreciseLifetime =
  2326. (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
  2327. if (isImpreciseLifetime)
  2328. LV.setARCPreciseLifetime(ARCImpreciseLifetime);
  2329. setObjCGCLValueClass(getContext(), E, LV);
  2330. return LV;
  2331. }
  2332. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  2333. return EmitFunctionDeclLValue(*this, E, FD);
  2334. // FIXME: While we're emitting a binding from an enclosing scope, all other
  2335. // DeclRefExprs we see should be implicitly treated as if they also refer to
  2336. // an enclosing scope.
  2337. if (const auto *BD = dyn_cast<BindingDecl>(ND))
  2338. return EmitLValue(BD->getBinding());
  2339. llvm_unreachable("Unhandled DeclRefExpr");
  2340. }
  2341. LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
  2342. // __extension__ doesn't affect lvalue-ness.
  2343. if (E->getOpcode() == UO_Extension)
  2344. return EmitLValue(E->getSubExpr());
  2345. QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
  2346. switch (E->getOpcode()) {
  2347. default: llvm_unreachable("Unknown unary operator lvalue!");
  2348. case UO_Deref: {
  2349. QualType T = E->getSubExpr()->getType()->getPointeeType();
  2350. assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
  2351. LValueBaseInfo BaseInfo;
  2352. TBAAAccessInfo TBAAInfo;
  2353. Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
  2354. &TBAAInfo);
  2355. LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
  2356. LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
  2357. // We should not generate __weak write barrier on indirect reference
  2358. // of a pointer to object; as in void foo (__weak id *param); *param = 0;
  2359. // But, we continue to generate __strong write barrier on indirect write
  2360. // into a pointer to object.
  2361. if (getLangOpts().ObjC &&
  2362. getLangOpts().getGC() != LangOptions::NonGC &&
  2363. LV.isObjCWeak())
  2364. LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
  2365. return LV;
  2366. }
  2367. case UO_Real:
  2368. case UO_Imag: {
  2369. LValue LV = EmitLValue(E->getSubExpr());
  2370. assert(LV.isSimple() && "real/imag on non-ordinary l-value");
  2371. // __real is valid on scalars. This is a faster way of testing that.
  2372. // __imag can only produce an rvalue on scalars.
  2373. if (E->getOpcode() == UO_Real &&
  2374. !LV.getAddress().getElementType()->isStructTy()) {
  2375. assert(E->getSubExpr()->getType()->isArithmeticType());
  2376. return LV;
  2377. }
  2378. QualType T = ExprTy->castAs<ComplexType>()->getElementType();
  2379. Address Component =
  2380. (E->getOpcode() == UO_Real
  2381. ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
  2382. : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
  2383. LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
  2384. CGM.getTBAAInfoForSubobject(LV, T));
  2385. ElemLV.getQuals().addQualifiers(LV.getQuals());
  2386. return ElemLV;
  2387. }
  2388. case UO_PreInc:
  2389. case UO_PreDec: {
  2390. LValue LV = EmitLValue(E->getSubExpr());
  2391. bool isInc = E->getOpcode() == UO_PreInc;
  2392. if (E->getType()->isAnyComplexType())
  2393. EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
  2394. else
  2395. EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
  2396. return LV;
  2397. }
  2398. }
  2399. }
  2400. LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
  2401. return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
  2402. E->getType(), AlignmentSource::Decl);
  2403. }
  2404. LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
  2405. return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
  2406. E->getType(), AlignmentSource::Decl);
  2407. }
  2408. LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
  2409. auto SL = E->getFunctionName();
  2410. assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
  2411. StringRef FnName = CurFn->getName();
  2412. if (FnName.startswith("\01"))
  2413. FnName = FnName.substr(1);
  2414. StringRef NameItems[] = {
  2415. PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
  2416. std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
  2417. if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
  2418. std::string Name = SL->getString();
  2419. if (!Name.empty()) {
  2420. unsigned Discriminator =
  2421. CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
  2422. if (Discriminator)
  2423. Name += "_" + Twine(Discriminator + 1).str();
  2424. auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
  2425. return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
  2426. } else {
  2427. auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
  2428. return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
  2429. }
  2430. }
  2431. auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
  2432. return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
  2433. }
  2434. /// Emit a type description suitable for use by a runtime sanitizer library. The
  2435. /// format of a type descriptor is
  2436. ///
  2437. /// \code
  2438. /// { i16 TypeKind, i16 TypeInfo }
  2439. /// \endcode
  2440. ///
  2441. /// followed by an array of i8 containing the type name. TypeKind is 0 for an
  2442. /// integer, 1 for a floating point value, and -1 for anything else.
  2443. llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
  2444. // Only emit each type's descriptor once.
  2445. if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
  2446. return C;
  2447. uint16_t TypeKind = -1;
  2448. uint16_t TypeInfo = 0;
  2449. if (T->isIntegerType()) {
  2450. TypeKind = 0;
  2451. TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
  2452. (T->isSignedIntegerType() ? 1 : 0);
  2453. } else if (T->isFloatingType()) {
  2454. TypeKind = 1;
  2455. TypeInfo = getContext().getTypeSize(T);
  2456. }
  2457. // Format the type name as if for a diagnostic, including quotes and
  2458. // optionally an 'aka'.
  2459. SmallString<32> Buffer;
  2460. CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
  2461. (intptr_t)T.getAsOpaquePtr(),
  2462. StringRef(), StringRef(), None, Buffer,
  2463. None);
  2464. llvm::Constant *Components[] = {
  2465. Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
  2466. llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
  2467. };
  2468. llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
  2469. auto *GV = new llvm::GlobalVariable(
  2470. CGM.getModule(), Descriptor->getType(),
  2471. /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
  2472. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2473. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
  2474. // Remember the descriptor for this type.
  2475. CGM.setTypeDescriptorInMap(T, GV);
  2476. return GV;
  2477. }
  2478. llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
  2479. llvm::Type *TargetTy = IntPtrTy;
  2480. if (V->getType() == TargetTy)
  2481. return V;
  2482. // Floating-point types which fit into intptr_t are bitcast to integers
  2483. // and then passed directly (after zero-extension, if necessary).
  2484. if (V->getType()->isFloatingPointTy()) {
  2485. unsigned Bits = V->getType()->getPrimitiveSizeInBits();
  2486. if (Bits <= TargetTy->getIntegerBitWidth())
  2487. V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
  2488. Bits));
  2489. }
  2490. // Integers which fit in intptr_t are zero-extended and passed directly.
  2491. if (V->getType()->isIntegerTy() &&
  2492. V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
  2493. return Builder.CreateZExt(V, TargetTy);
  2494. // Pointers are passed directly, everything else is passed by address.
  2495. if (!V->getType()->isPointerTy()) {
  2496. Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
  2497. Builder.CreateStore(V, Ptr);
  2498. V = Ptr.getPointer();
  2499. }
  2500. return Builder.CreatePtrToInt(V, TargetTy);
  2501. }
  2502. /// Emit a representation of a SourceLocation for passing to a handler
  2503. /// in a sanitizer runtime library. The format for this data is:
  2504. /// \code
  2505. /// struct SourceLocation {
  2506. /// const char *Filename;
  2507. /// int32_t Line, Column;
  2508. /// };
  2509. /// \endcode
  2510. /// For an invalid SourceLocation, the Filename pointer is null.
  2511. llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
  2512. llvm::Constant *Filename;
  2513. int Line, Column;
  2514. PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
  2515. if (PLoc.isValid()) {
  2516. StringRef FilenameString = PLoc.getFilename();
  2517. int PathComponentsToStrip =
  2518. CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
  2519. if (PathComponentsToStrip < 0) {
  2520. assert(PathComponentsToStrip != INT_MIN);
  2521. int PathComponentsToKeep = -PathComponentsToStrip;
  2522. auto I = llvm::sys::path::rbegin(FilenameString);
  2523. auto E = llvm::sys::path::rend(FilenameString);
  2524. while (I != E && --PathComponentsToKeep)
  2525. ++I;
  2526. FilenameString = FilenameString.substr(I - E);
  2527. } else if (PathComponentsToStrip > 0) {
  2528. auto I = llvm::sys::path::begin(FilenameString);
  2529. auto E = llvm::sys::path::end(FilenameString);
  2530. while (I != E && PathComponentsToStrip--)
  2531. ++I;
  2532. if (I != E)
  2533. FilenameString =
  2534. FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
  2535. else
  2536. FilenameString = llvm::sys::path::filename(FilenameString);
  2537. }
  2538. auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
  2539. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
  2540. cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
  2541. Filename = FilenameGV.getPointer();
  2542. Line = PLoc.getLine();
  2543. Column = PLoc.getColumn();
  2544. } else {
  2545. Filename = llvm::Constant::getNullValue(Int8PtrTy);
  2546. Line = Column = 0;
  2547. }
  2548. llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
  2549. Builder.getInt32(Column)};
  2550. return llvm::ConstantStruct::getAnon(Data);
  2551. }
  2552. namespace {
  2553. /// Specify under what conditions this check can be recovered
  2554. enum class CheckRecoverableKind {
  2555. /// Always terminate program execution if this check fails.
  2556. Unrecoverable,
  2557. /// Check supports recovering, runtime has both fatal (noreturn) and
  2558. /// non-fatal handlers for this check.
  2559. Recoverable,
  2560. /// Runtime conditionally aborts, always need to support recovery.
  2561. AlwaysRecoverable
  2562. };
  2563. }
  2564. static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
  2565. assert(Kind.countPopulation() == 1);
  2566. if (Kind == SanitizerKind::Vptr)
  2567. return CheckRecoverableKind::AlwaysRecoverable;
  2568. else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable)
  2569. return CheckRecoverableKind::Unrecoverable;
  2570. else
  2571. return CheckRecoverableKind::Recoverable;
  2572. }
  2573. namespace {
  2574. struct SanitizerHandlerInfo {
  2575. char const *const Name;
  2576. unsigned Version;
  2577. };
  2578. }
  2579. const SanitizerHandlerInfo SanitizerHandlers[] = {
  2580. #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
  2581. LIST_SANITIZER_CHECKS
  2582. #undef SANITIZER_CHECK
  2583. };
  2584. static void emitCheckHandlerCall(CodeGenFunction &CGF,
  2585. llvm::FunctionType *FnType,
  2586. ArrayRef<llvm::Value *> FnArgs,
  2587. SanitizerHandler CheckHandler,
  2588. CheckRecoverableKind RecoverKind, bool IsFatal,
  2589. llvm::BasicBlock *ContBB) {
  2590. assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
  2591. Optional<ApplyDebugLocation> DL;
  2592. if (!CGF.Builder.getCurrentDebugLocation()) {
  2593. // Ensure that the call has at least an artificial debug location.
  2594. DL.emplace(CGF, SourceLocation());
  2595. }
  2596. bool NeedsAbortSuffix =
  2597. IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
  2598. bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
  2599. const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
  2600. const StringRef CheckName = CheckInfo.Name;
  2601. std::string FnName = "__ubsan_handle_" + CheckName.str();
  2602. if (CheckInfo.Version && !MinimalRuntime)
  2603. FnName += "_v" + llvm::utostr(CheckInfo.Version);
  2604. if (MinimalRuntime)
  2605. FnName += "_minimal";
  2606. if (NeedsAbortSuffix)
  2607. FnName += "_abort";
  2608. bool MayReturn =
  2609. !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
  2610. llvm::AttrBuilder B;
  2611. if (!MayReturn) {
  2612. B.addAttribute(llvm::Attribute::NoReturn)
  2613. .addAttribute(llvm::Attribute::NoUnwind);
  2614. }
  2615. B.addAttribute(llvm::Attribute::UWTable);
  2616. llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
  2617. FnType, FnName,
  2618. llvm::AttributeList::get(CGF.getLLVMContext(),
  2619. llvm::AttributeList::FunctionIndex, B),
  2620. /*Local=*/true);
  2621. llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
  2622. if (!MayReturn) {
  2623. HandlerCall->setDoesNotReturn();
  2624. CGF.Builder.CreateUnreachable();
  2625. } else {
  2626. CGF.Builder.CreateBr(ContBB);
  2627. }
  2628. }
  2629. void CodeGenFunction::EmitCheck(
  2630. ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
  2631. SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
  2632. ArrayRef<llvm::Value *> DynamicArgs) {
  2633. assert(IsSanitizerScope);
  2634. assert(Checked.size() > 0);
  2635. assert(CheckHandler >= 0 &&
  2636. size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
  2637. const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
  2638. llvm::Value *FatalCond = nullptr;
  2639. llvm::Value *RecoverableCond = nullptr;
  2640. llvm::Value *TrapCond = nullptr;
  2641. for (int i = 0, n = Checked.size(); i < n; ++i) {
  2642. llvm::Value *Check = Checked[i].first;
  2643. // -fsanitize-trap= overrides -fsanitize-recover=.
  2644. llvm::Value *&Cond =
  2645. CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
  2646. ? TrapCond
  2647. : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
  2648. ? RecoverableCond
  2649. : FatalCond;
  2650. Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
  2651. }
  2652. if (TrapCond)
  2653. EmitTrapCheck(TrapCond);
  2654. if (!FatalCond && !RecoverableCond)
  2655. return;
  2656. llvm::Value *JointCond;
  2657. if (FatalCond && RecoverableCond)
  2658. JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
  2659. else
  2660. JointCond = FatalCond ? FatalCond : RecoverableCond;
  2661. assert(JointCond);
  2662. CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
  2663. assert(SanOpts.has(Checked[0].second));
  2664. #ifndef NDEBUG
  2665. for (int i = 1, n = Checked.size(); i < n; ++i) {
  2666. assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
  2667. "All recoverable kinds in a single check must be same!");
  2668. assert(SanOpts.has(Checked[i].second));
  2669. }
  2670. #endif
  2671. llvm::BasicBlock *Cont = createBasicBlock("cont");
  2672. llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
  2673. llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
  2674. // Give hint that we very much don't expect to execute the handler
  2675. // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
  2676. llvm::MDBuilder MDHelper(getLLVMContext());
  2677. llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
  2678. Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
  2679. EmitBlock(Handlers);
  2680. // Handler functions take an i8* pointing to the (handler-specific) static
  2681. // information block, followed by a sequence of intptr_t arguments
  2682. // representing operand values.
  2683. SmallVector<llvm::Value *, 4> Args;
  2684. SmallVector<llvm::Type *, 4> ArgTypes;
  2685. if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
  2686. Args.reserve(DynamicArgs.size() + 1);
  2687. ArgTypes.reserve(DynamicArgs.size() + 1);
  2688. // Emit handler arguments and create handler function type.
  2689. if (!StaticArgs.empty()) {
  2690. llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
  2691. auto *InfoPtr =
  2692. new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
  2693. llvm::GlobalVariable::PrivateLinkage, Info);
  2694. InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2695. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
  2696. Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
  2697. ArgTypes.push_back(Int8PtrTy);
  2698. }
  2699. for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
  2700. Args.push_back(EmitCheckValue(DynamicArgs[i]));
  2701. ArgTypes.push_back(IntPtrTy);
  2702. }
  2703. }
  2704. llvm::FunctionType *FnType =
  2705. llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
  2706. if (!FatalCond || !RecoverableCond) {
  2707. // Simple case: we need to generate a single handler call, either
  2708. // fatal, or non-fatal.
  2709. emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
  2710. (FatalCond != nullptr), Cont);
  2711. } else {
  2712. // Emit two handler calls: first one for set of unrecoverable checks,
  2713. // another one for recoverable.
  2714. llvm::BasicBlock *NonFatalHandlerBB =
  2715. createBasicBlock("non_fatal." + CheckName);
  2716. llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
  2717. Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
  2718. EmitBlock(FatalHandlerBB);
  2719. emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
  2720. NonFatalHandlerBB);
  2721. EmitBlock(NonFatalHandlerBB);
  2722. emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
  2723. Cont);
  2724. }
  2725. EmitBlock(Cont);
  2726. }
  2727. void CodeGenFunction::EmitCfiSlowPathCheck(
  2728. SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
  2729. llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
  2730. llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
  2731. llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
  2732. llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
  2733. llvm::MDBuilder MDHelper(getLLVMContext());
  2734. llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
  2735. BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
  2736. EmitBlock(CheckBB);
  2737. bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
  2738. llvm::CallInst *CheckCall;
  2739. llvm::FunctionCallee SlowPathFn;
  2740. if (WithDiag) {
  2741. llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
  2742. auto *InfoPtr =
  2743. new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
  2744. llvm::GlobalVariable::PrivateLinkage, Info);
  2745. InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2746. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
  2747. SlowPathFn = CGM.getModule().getOrInsertFunction(
  2748. "__cfi_slowpath_diag",
  2749. llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
  2750. false));
  2751. CheckCall = Builder.CreateCall(
  2752. SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
  2753. } else {
  2754. SlowPathFn = CGM.getModule().getOrInsertFunction(
  2755. "__cfi_slowpath",
  2756. llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
  2757. CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
  2758. }
  2759. CGM.setDSOLocal(
  2760. cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
  2761. CheckCall->setDoesNotThrow();
  2762. EmitBlock(Cont);
  2763. }
  2764. // Emit a stub for __cfi_check function so that the linker knows about this
  2765. // symbol in LTO mode.
  2766. void CodeGenFunction::EmitCfiCheckStub() {
  2767. llvm::Module *M = &CGM.getModule();
  2768. auto &Ctx = M->getContext();
  2769. llvm::Function *F = llvm::Function::Create(
  2770. llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
  2771. llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
  2772. CGM.setDSOLocal(F);
  2773. llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
  2774. // FIXME: consider emitting an intrinsic call like
  2775. // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
  2776. // which can be lowered in CrossDSOCFI pass to the actual contents of
  2777. // __cfi_check. This would allow inlining of __cfi_check calls.
  2778. llvm::CallInst::Create(
  2779. llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
  2780. llvm::ReturnInst::Create(Ctx, nullptr, BB);
  2781. }
  2782. // This function is basically a switch over the CFI failure kind, which is
  2783. // extracted from CFICheckFailData (1st function argument). Each case is either
  2784. // llvm.trap or a call to one of the two runtime handlers, based on
  2785. // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
  2786. // failure kind) traps, but this should really never happen. CFICheckFailData
  2787. // can be nullptr if the calling module has -fsanitize-trap behavior for this
  2788. // check kind; in this case __cfi_check_fail traps as well.
  2789. void CodeGenFunction::EmitCfiCheckFail() {
  2790. SanitizerScope SanScope(this);
  2791. FunctionArgList Args;
  2792. ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
  2793. ImplicitParamDecl::Other);
  2794. ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
  2795. ImplicitParamDecl::Other);
  2796. Args.push_back(&ArgData);
  2797. Args.push_back(&ArgAddr);
  2798. const CGFunctionInfo &FI =
  2799. CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
  2800. llvm::Function *F = llvm::Function::Create(
  2801. llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
  2802. llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
  2803. F->setVisibility(llvm::GlobalValue::HiddenVisibility);
  2804. StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
  2805. SourceLocation());
  2806. // This function should not be affected by blacklist. This function does
  2807. // not have a source location, but "src:*" would still apply. Revert any
  2808. // changes to SanOpts made in StartFunction.
  2809. SanOpts = CGM.getLangOpts().Sanitize;
  2810. llvm::Value *Data =
  2811. EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
  2812. CGM.getContext().VoidPtrTy, ArgData.getLocation());
  2813. llvm::Value *Addr =
  2814. EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
  2815. CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
  2816. // Data == nullptr means the calling module has trap behaviour for this check.
  2817. llvm::Value *DataIsNotNullPtr =
  2818. Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
  2819. EmitTrapCheck(DataIsNotNullPtr);
  2820. llvm::StructType *SourceLocationTy =
  2821. llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
  2822. llvm::StructType *CfiCheckFailDataTy =
  2823. llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
  2824. llvm::Value *V = Builder.CreateConstGEP2_32(
  2825. CfiCheckFailDataTy,
  2826. Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
  2827. 0);
  2828. Address CheckKindAddr(V, getIntAlign());
  2829. llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
  2830. llvm::Value *AllVtables = llvm::MetadataAsValue::get(
  2831. CGM.getLLVMContext(),
  2832. llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
  2833. llvm::Value *ValidVtable = Builder.CreateZExt(
  2834. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
  2835. {Addr, AllVtables}),
  2836. IntPtrTy);
  2837. const std::pair<int, SanitizerMask> CheckKinds[] = {
  2838. {CFITCK_VCall, SanitizerKind::CFIVCall},
  2839. {CFITCK_NVCall, SanitizerKind::CFINVCall},
  2840. {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
  2841. {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
  2842. {CFITCK_ICall, SanitizerKind::CFIICall}};
  2843. SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
  2844. for (auto CheckKindMaskPair : CheckKinds) {
  2845. int Kind = CheckKindMaskPair.first;
  2846. SanitizerMask Mask = CheckKindMaskPair.second;
  2847. llvm::Value *Cond =
  2848. Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
  2849. if (CGM.getLangOpts().Sanitize.has(Mask))
  2850. EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
  2851. {Data, Addr, ValidVtable});
  2852. else
  2853. EmitTrapCheck(Cond);
  2854. }
  2855. FinishFunction();
  2856. // The only reference to this function will be created during LTO link.
  2857. // Make sure it survives until then.
  2858. CGM.addUsedGlobal(F);
  2859. }
  2860. void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
  2861. if (SanOpts.has(SanitizerKind::Unreachable)) {
  2862. SanitizerScope SanScope(this);
  2863. EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
  2864. SanitizerKind::Unreachable),
  2865. SanitizerHandler::BuiltinUnreachable,
  2866. EmitCheckSourceLocation(Loc), None);
  2867. }
  2868. Builder.CreateUnreachable();
  2869. }
  2870. void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
  2871. llvm::BasicBlock *Cont = createBasicBlock("cont");
  2872. // If we're optimizing, collapse all calls to trap down to just one per
  2873. // function to save on code size.
  2874. if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
  2875. TrapBB = createBasicBlock("trap");
  2876. Builder.CreateCondBr(Checked, Cont, TrapBB);
  2877. EmitBlock(TrapBB);
  2878. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  2879. TrapCall->setDoesNotReturn();
  2880. TrapCall->setDoesNotThrow();
  2881. Builder.CreateUnreachable();
  2882. } else {
  2883. Builder.CreateCondBr(Checked, Cont, TrapBB);
  2884. }
  2885. EmitBlock(Cont);
  2886. }
  2887. llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
  2888. llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
  2889. if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
  2890. auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
  2891. CGM.getCodeGenOpts().TrapFuncName);
  2892. TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
  2893. }
  2894. return TrapCall;
  2895. }
  2896. Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
  2897. LValueBaseInfo *BaseInfo,
  2898. TBAAAccessInfo *TBAAInfo) {
  2899. assert(E->getType()->isArrayType() &&
  2900. "Array to pointer decay must have array source type!");
  2901. // Expressions of array type can't be bitfields or vector elements.
  2902. LValue LV = EmitLValue(E);
  2903. Address Addr = LV.getAddress();
  2904. // If the array type was an incomplete type, we need to make sure
  2905. // the decay ends up being the right type.
  2906. llvm::Type *NewTy = ConvertType(E->getType());
  2907. Addr = Builder.CreateElementBitCast(Addr, NewTy);
  2908. // Note that VLA pointers are always decayed, so we don't need to do
  2909. // anything here.
  2910. if (!E->getType()->isVariableArrayType()) {
  2911. assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
  2912. "Expected pointer to array");
  2913. Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
  2914. }
  2915. // The result of this decay conversion points to an array element within the
  2916. // base lvalue. However, since TBAA currently does not support representing
  2917. // accesses to elements of member arrays, we conservatively represent accesses
  2918. // to the pointee object as if it had no any base lvalue specified.
  2919. // TODO: Support TBAA for member arrays.
  2920. QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
  2921. if (BaseInfo) *BaseInfo = LV.getBaseInfo();
  2922. if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
  2923. return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
  2924. }
  2925. /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
  2926. /// array to pointer, return the array subexpression.
  2927. static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
  2928. // If this isn't just an array->pointer decay, bail out.
  2929. const auto *CE = dyn_cast<CastExpr>(E);
  2930. if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
  2931. return nullptr;
  2932. // If this is a decay from variable width array, bail out.
  2933. const Expr *SubExpr = CE->getSubExpr();
  2934. if (SubExpr->getType()->isVariableArrayType())
  2935. return nullptr;
  2936. return SubExpr;
  2937. }
  2938. static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
  2939. llvm::Value *ptr,
  2940. ArrayRef<llvm::Value*> indices,
  2941. bool inbounds,
  2942. bool signedIndices,
  2943. SourceLocation loc,
  2944. const llvm::Twine &name = "arrayidx") {
  2945. if (inbounds) {
  2946. return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
  2947. CodeGenFunction::NotSubtraction, loc,
  2948. name);
  2949. } else {
  2950. return CGF.Builder.CreateGEP(ptr, indices, name);
  2951. }
  2952. }
  2953. static CharUnits getArrayElementAlign(CharUnits arrayAlign,
  2954. llvm::Value *idx,
  2955. CharUnits eltSize) {
  2956. // If we have a constant index, we can use the exact offset of the
  2957. // element we're accessing.
  2958. if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
  2959. CharUnits offset = constantIdx->getZExtValue() * eltSize;
  2960. return arrayAlign.alignmentAtOffset(offset);
  2961. // Otherwise, use the worst-case alignment for any element.
  2962. } else {
  2963. return arrayAlign.alignmentOfArrayElement(eltSize);
  2964. }
  2965. }
  2966. static QualType getFixedSizeElementType(const ASTContext &ctx,
  2967. const VariableArrayType *vla) {
  2968. QualType eltType;
  2969. do {
  2970. eltType = vla->getElementType();
  2971. } while ((vla = ctx.getAsVariableArrayType(eltType)));
  2972. return eltType;
  2973. }
  2974. static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
  2975. ArrayRef<llvm::Value *> indices,
  2976. QualType eltType, bool inbounds,
  2977. bool signedIndices, SourceLocation loc,
  2978. const llvm::Twine &name = "arrayidx") {
  2979. // All the indices except that last must be zero.
  2980. #ifndef NDEBUG
  2981. for (auto idx : indices.drop_back())
  2982. assert(isa<llvm::ConstantInt>(idx) &&
  2983. cast<llvm::ConstantInt>(idx)->isZero());
  2984. #endif
  2985. // Determine the element size of the statically-sized base. This is
  2986. // the thing that the indices are expressed in terms of.
  2987. if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
  2988. eltType = getFixedSizeElementType(CGF.getContext(), vla);
  2989. }
  2990. // We can use that to compute the best alignment of the element.
  2991. CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
  2992. CharUnits eltAlign =
  2993. getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
  2994. llvm::Value *eltPtr = emitArraySubscriptGEP(
  2995. CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
  2996. return Address(eltPtr, eltAlign);
  2997. }
  2998. LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  2999. bool Accessed) {
  3000. // The index must always be an integer, which is not an aggregate. Emit it
  3001. // in lexical order (this complexity is, sadly, required by C++17).
  3002. llvm::Value *IdxPre =
  3003. (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
  3004. bool SignedIndices = false;
  3005. auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
  3006. auto *Idx = IdxPre;
  3007. if (E->getLHS() != E->getIdx()) {
  3008. assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
  3009. Idx = EmitScalarExpr(E->getIdx());
  3010. }
  3011. QualType IdxTy = E->getIdx()->getType();
  3012. bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
  3013. SignedIndices |= IdxSigned;
  3014. if (SanOpts.has(SanitizerKind::ArrayBounds))
  3015. EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
  3016. // Extend or truncate the index type to 32 or 64-bits.
  3017. if (Promote && Idx->getType() != IntPtrTy)
  3018. Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
  3019. return Idx;
  3020. };
  3021. IdxPre = nullptr;
  3022. // If the base is a vector type, then we are forming a vector element lvalue
  3023. // with this subscript.
  3024. if (E->getBase()->getType()->isVectorType() &&
  3025. !isa<ExtVectorElementExpr>(E->getBase())) {
  3026. // Emit the vector as an lvalue to get its address.
  3027. LValue LHS = EmitLValue(E->getBase());
  3028. auto *Idx = EmitIdxAfterBase(/*Promote*/false);
  3029. assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
  3030. return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
  3031. LHS.getBaseInfo(), TBAAAccessInfo());
  3032. }
  3033. // All the other cases basically behave like simple offsetting.
  3034. // Handle the extvector case we ignored above.
  3035. if (isa<ExtVectorElementExpr>(E->getBase())) {
  3036. LValue LV = EmitLValue(E->getBase());
  3037. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3038. Address Addr = EmitExtVectorElementLValue(LV);
  3039. QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
  3040. Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
  3041. SignedIndices, E->getExprLoc());
  3042. return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
  3043. CGM.getTBAAInfoForSubobject(LV, EltType));
  3044. }
  3045. LValueBaseInfo EltBaseInfo;
  3046. TBAAAccessInfo EltTBAAInfo;
  3047. Address Addr = Address::invalid();
  3048. if (const VariableArrayType *vla =
  3049. getContext().getAsVariableArrayType(E->getType())) {
  3050. // The base must be a pointer, which is not an aggregate. Emit
  3051. // it. It needs to be emitted first in case it's what captures
  3052. // the VLA bounds.
  3053. Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
  3054. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3055. // The element count here is the total number of non-VLA elements.
  3056. llvm::Value *numElements = getVLASize(vla).NumElts;
  3057. // Effectively, the multiply by the VLA size is part of the GEP.
  3058. // GEP indexes are signed, and scaling an index isn't permitted to
  3059. // signed-overflow, so we use the same semantics for our explicit
  3060. // multiply. We suppress this if overflow is not undefined behavior.
  3061. if (getLangOpts().isSignedOverflowDefined()) {
  3062. Idx = Builder.CreateMul(Idx, numElements);
  3063. } else {
  3064. Idx = Builder.CreateNSWMul(Idx, numElements);
  3065. }
  3066. Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
  3067. !getLangOpts().isSignedOverflowDefined(),
  3068. SignedIndices, E->getExprLoc());
  3069. } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
  3070. // Indexing over an interface, as in "NSString *P; P[4];"
  3071. // Emit the base pointer.
  3072. Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
  3073. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3074. CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
  3075. llvm::Value *InterfaceSizeVal =
  3076. llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
  3077. llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
  3078. // We don't necessarily build correct LLVM struct types for ObjC
  3079. // interfaces, so we can't rely on GEP to do this scaling
  3080. // correctly, so we need to cast to i8*. FIXME: is this actually
  3081. // true? A lot of other things in the fragile ABI would break...
  3082. llvm::Type *OrigBaseTy = Addr.getType();
  3083. Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
  3084. // Do the GEP.
  3085. CharUnits EltAlign =
  3086. getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
  3087. llvm::Value *EltPtr =
  3088. emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
  3089. SignedIndices, E->getExprLoc());
  3090. Addr = Address(EltPtr, EltAlign);
  3091. // Cast back.
  3092. Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
  3093. } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
  3094. // If this is A[i] where A is an array, the frontend will have decayed the
  3095. // base to be a ArrayToPointerDecay implicit cast. While correct, it is
  3096. // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
  3097. // "gep x, i" here. Emit one "gep A, 0, i".
  3098. assert(Array->getType()->isArrayType() &&
  3099. "Array to pointer decay must have array source type!");
  3100. LValue ArrayLV;
  3101. // For simple multidimensional array indexing, set the 'accessed' flag for
  3102. // better bounds-checking of the base expression.
  3103. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
  3104. ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
  3105. else
  3106. ArrayLV = EmitLValue(Array);
  3107. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3108. // Propagate the alignment from the array itself to the result.
  3109. Addr = emitArraySubscriptGEP(
  3110. *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
  3111. E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
  3112. E->getExprLoc());
  3113. EltBaseInfo = ArrayLV.getBaseInfo();
  3114. EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
  3115. } else {
  3116. // The base must be a pointer; emit it with an estimate of its alignment.
  3117. Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
  3118. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3119. Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
  3120. !getLangOpts().isSignedOverflowDefined(),
  3121. SignedIndices, E->getExprLoc());
  3122. }
  3123. LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
  3124. if (getLangOpts().ObjC &&
  3125. getLangOpts().getGC() != LangOptions::NonGC) {
  3126. LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
  3127. setObjCGCLValueClass(getContext(), E, LV);
  3128. }
  3129. return LV;
  3130. }
  3131. static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
  3132. LValueBaseInfo &BaseInfo,
  3133. TBAAAccessInfo &TBAAInfo,
  3134. QualType BaseTy, QualType ElTy,
  3135. bool IsLowerBound) {
  3136. LValue BaseLVal;
  3137. if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
  3138. BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
  3139. if (BaseTy->isArrayType()) {
  3140. Address Addr = BaseLVal.getAddress();
  3141. BaseInfo = BaseLVal.getBaseInfo();
  3142. // If the array type was an incomplete type, we need to make sure
  3143. // the decay ends up being the right type.
  3144. llvm::Type *NewTy = CGF.ConvertType(BaseTy);
  3145. Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
  3146. // Note that VLA pointers are always decayed, so we don't need to do
  3147. // anything here.
  3148. if (!BaseTy->isVariableArrayType()) {
  3149. assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
  3150. "Expected pointer to array");
  3151. Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
  3152. }
  3153. return CGF.Builder.CreateElementBitCast(Addr,
  3154. CGF.ConvertTypeForMem(ElTy));
  3155. }
  3156. LValueBaseInfo TypeBaseInfo;
  3157. TBAAAccessInfo TypeTBAAInfo;
  3158. CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeBaseInfo,
  3159. &TypeTBAAInfo);
  3160. BaseInfo.mergeForCast(TypeBaseInfo);
  3161. TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
  3162. return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
  3163. }
  3164. return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
  3165. }
  3166. LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
  3167. bool IsLowerBound) {
  3168. QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
  3169. QualType ResultExprTy;
  3170. if (auto *AT = getContext().getAsArrayType(BaseTy))
  3171. ResultExprTy = AT->getElementType();
  3172. else
  3173. ResultExprTy = BaseTy->getPointeeType();
  3174. llvm::Value *Idx = nullptr;
  3175. if (IsLowerBound || E->getColonLoc().isInvalid()) {
  3176. // Requesting lower bound or upper bound, but without provided length and
  3177. // without ':' symbol for the default length -> length = 1.
  3178. // Idx = LowerBound ?: 0;
  3179. if (auto *LowerBound = E->getLowerBound()) {
  3180. Idx = Builder.CreateIntCast(
  3181. EmitScalarExpr(LowerBound), IntPtrTy,
  3182. LowerBound->getType()->hasSignedIntegerRepresentation());
  3183. } else
  3184. Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
  3185. } else {
  3186. // Try to emit length or lower bound as constant. If this is possible, 1
  3187. // is subtracted from constant length or lower bound. Otherwise, emit LLVM
  3188. // IR (LB + Len) - 1.
  3189. auto &C = CGM.getContext();
  3190. auto *Length = E->getLength();
  3191. llvm::APSInt ConstLength;
  3192. if (Length) {
  3193. // Idx = LowerBound + Length - 1;
  3194. if (Length->isIntegerConstantExpr(ConstLength, C)) {
  3195. ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
  3196. Length = nullptr;
  3197. }
  3198. auto *LowerBound = E->getLowerBound();
  3199. llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
  3200. if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
  3201. ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
  3202. LowerBound = nullptr;
  3203. }
  3204. if (!Length)
  3205. --ConstLength;
  3206. else if (!LowerBound)
  3207. --ConstLowerBound;
  3208. if (Length || LowerBound) {
  3209. auto *LowerBoundVal =
  3210. LowerBound
  3211. ? Builder.CreateIntCast(
  3212. EmitScalarExpr(LowerBound), IntPtrTy,
  3213. LowerBound->getType()->hasSignedIntegerRepresentation())
  3214. : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
  3215. auto *LengthVal =
  3216. Length
  3217. ? Builder.CreateIntCast(
  3218. EmitScalarExpr(Length), IntPtrTy,
  3219. Length->getType()->hasSignedIntegerRepresentation())
  3220. : llvm::ConstantInt::get(IntPtrTy, ConstLength);
  3221. Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
  3222. /*HasNUW=*/false,
  3223. !getLangOpts().isSignedOverflowDefined());
  3224. if (Length && LowerBound) {
  3225. Idx = Builder.CreateSub(
  3226. Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
  3227. /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
  3228. }
  3229. } else
  3230. Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
  3231. } else {
  3232. // Idx = ArraySize - 1;
  3233. QualType ArrayTy = BaseTy->isPointerType()
  3234. ? E->getBase()->IgnoreParenImpCasts()->getType()
  3235. : BaseTy;
  3236. if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
  3237. Length = VAT->getSizeExpr();
  3238. if (Length->isIntegerConstantExpr(ConstLength, C))
  3239. Length = nullptr;
  3240. } else {
  3241. auto *CAT = C.getAsConstantArrayType(ArrayTy);
  3242. ConstLength = CAT->getSize();
  3243. }
  3244. if (Length) {
  3245. auto *LengthVal = Builder.CreateIntCast(
  3246. EmitScalarExpr(Length), IntPtrTy,
  3247. Length->getType()->hasSignedIntegerRepresentation());
  3248. Idx = Builder.CreateSub(
  3249. LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
  3250. /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
  3251. } else {
  3252. ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
  3253. --ConstLength;
  3254. Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
  3255. }
  3256. }
  3257. }
  3258. assert(Idx);
  3259. Address EltPtr = Address::invalid();
  3260. LValueBaseInfo BaseInfo;
  3261. TBAAAccessInfo TBAAInfo;
  3262. if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
  3263. // The base must be a pointer, which is not an aggregate. Emit
  3264. // it. It needs to be emitted first in case it's what captures
  3265. // the VLA bounds.
  3266. Address Base =
  3267. emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
  3268. BaseTy, VLA->getElementType(), IsLowerBound);
  3269. // The element count here is the total number of non-VLA elements.
  3270. llvm::Value *NumElements = getVLASize(VLA).NumElts;
  3271. // Effectively, the multiply by the VLA size is part of the GEP.
  3272. // GEP indexes are signed, and scaling an index isn't permitted to
  3273. // signed-overflow, so we use the same semantics for our explicit
  3274. // multiply. We suppress this if overflow is not undefined behavior.
  3275. if (getLangOpts().isSignedOverflowDefined())
  3276. Idx = Builder.CreateMul(Idx, NumElements);
  3277. else
  3278. Idx = Builder.CreateNSWMul(Idx, NumElements);
  3279. EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
  3280. !getLangOpts().isSignedOverflowDefined(),
  3281. /*SignedIndices=*/false, E->getExprLoc());
  3282. } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
  3283. // If this is A[i] where A is an array, the frontend will have decayed the
  3284. // base to be a ArrayToPointerDecay implicit cast. While correct, it is
  3285. // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
  3286. // "gep x, i" here. Emit one "gep A, 0, i".
  3287. assert(Array->getType()->isArrayType() &&
  3288. "Array to pointer decay must have array source type!");
  3289. LValue ArrayLV;
  3290. // For simple multidimensional array indexing, set the 'accessed' flag for
  3291. // better bounds-checking of the base expression.
  3292. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
  3293. ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
  3294. else
  3295. ArrayLV = EmitLValue(Array);
  3296. // Propagate the alignment from the array itself to the result.
  3297. EltPtr = emitArraySubscriptGEP(
  3298. *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
  3299. ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
  3300. /*SignedIndices=*/false, E->getExprLoc());
  3301. BaseInfo = ArrayLV.getBaseInfo();
  3302. TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
  3303. } else {
  3304. Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
  3305. TBAAInfo, BaseTy, ResultExprTy,
  3306. IsLowerBound);
  3307. EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
  3308. !getLangOpts().isSignedOverflowDefined(),
  3309. /*SignedIndices=*/false, E->getExprLoc());
  3310. }
  3311. return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
  3312. }
  3313. LValue CodeGenFunction::
  3314. EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
  3315. // Emit the base vector as an l-value.
  3316. LValue Base;
  3317. // ExtVectorElementExpr's base can either be a vector or pointer to vector.
  3318. if (E->isArrow()) {
  3319. // If it is a pointer to a vector, emit the address and form an lvalue with
  3320. // it.
  3321. LValueBaseInfo BaseInfo;
  3322. TBAAAccessInfo TBAAInfo;
  3323. Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
  3324. const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
  3325. Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
  3326. Base.getQuals().removeObjCGCAttr();
  3327. } else if (E->getBase()->isGLValue()) {
  3328. // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
  3329. // emit the base as an lvalue.
  3330. assert(E->getBase()->getType()->isVectorType());
  3331. Base = EmitLValue(E->getBase());
  3332. } else {
  3333. // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
  3334. assert(E->getBase()->getType()->isVectorType() &&
  3335. "Result must be a vector");
  3336. llvm::Value *Vec = EmitScalarExpr(E->getBase());
  3337. // Store the vector to memory (because LValue wants an address).
  3338. Address VecMem = CreateMemTemp(E->getBase()->getType());
  3339. Builder.CreateStore(Vec, VecMem);
  3340. Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
  3341. AlignmentSource::Decl);
  3342. }
  3343. QualType type =
  3344. E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
  3345. // Encode the element access list into a vector of unsigned indices.
  3346. SmallVector<uint32_t, 4> Indices;
  3347. E->getEncodedElementAccess(Indices);
  3348. if (Base.isSimple()) {
  3349. llvm::Constant *CV =
  3350. llvm::ConstantDataVector::get(getLLVMContext(), Indices);
  3351. return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
  3352. Base.getBaseInfo(), TBAAAccessInfo());
  3353. }
  3354. assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
  3355. llvm::Constant *BaseElts = Base.getExtVectorElts();
  3356. SmallVector<llvm::Constant *, 4> CElts;
  3357. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  3358. CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
  3359. llvm::Constant *CV = llvm::ConstantVector::get(CElts);
  3360. return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
  3361. Base.getBaseInfo(), TBAAAccessInfo());
  3362. }
  3363. LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
  3364. if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
  3365. EmitIgnoredExpr(E->getBase());
  3366. return EmitDeclRefLValue(DRE);
  3367. }
  3368. Expr *BaseExpr = E->getBase();
  3369. // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
  3370. LValue BaseLV;
  3371. if (E->isArrow()) {
  3372. LValueBaseInfo BaseInfo;
  3373. TBAAAccessInfo TBAAInfo;
  3374. Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
  3375. QualType PtrTy = BaseExpr->getType()->getPointeeType();
  3376. SanitizerSet SkippedChecks;
  3377. bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
  3378. if (IsBaseCXXThis)
  3379. SkippedChecks.set(SanitizerKind::Alignment, true);
  3380. if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
  3381. SkippedChecks.set(SanitizerKind::Null, true);
  3382. EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
  3383. /*Alignment=*/CharUnits::Zero(), SkippedChecks);
  3384. BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
  3385. } else
  3386. BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
  3387. NamedDecl *ND = E->getMemberDecl();
  3388. if (auto *Field = dyn_cast<FieldDecl>(ND)) {
  3389. LValue LV = EmitLValueForField(BaseLV, Field);
  3390. setObjCGCLValueClass(getContext(), E, LV);
  3391. return LV;
  3392. }
  3393. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  3394. return EmitFunctionDeclLValue(*this, E, FD);
  3395. llvm_unreachable("Unhandled member declaration!");
  3396. }
  3397. /// Given that we are currently emitting a lambda, emit an l-value for
  3398. /// one of its members.
  3399. LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
  3400. assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
  3401. assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
  3402. QualType LambdaTagType =
  3403. getContext().getTagDeclType(Field->getParent());
  3404. LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
  3405. return EmitLValueForField(LambdaLV, Field);
  3406. }
  3407. /// Get the address of a zero-sized field within a record. The resulting
  3408. /// address doesn't necessarily have the right type.
  3409. static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
  3410. const FieldDecl *Field) {
  3411. CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
  3412. CGF.getContext().getFieldOffset(Field));
  3413. if (Offset.isZero())
  3414. return Base;
  3415. Base = CGF.Builder.CreateElementBitCast(Base, CGF.Int8Ty);
  3416. return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
  3417. }
  3418. /// Drill down to the storage of a field without walking into
  3419. /// reference types.
  3420. ///
  3421. /// The resulting address doesn't necessarily have the right type.
  3422. static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
  3423. const FieldDecl *field) {
  3424. if (field->isZeroSize(CGF.getContext()))
  3425. return emitAddrOfZeroSizeField(CGF, base, field);
  3426. const RecordDecl *rec = field->getParent();
  3427. unsigned idx =
  3428. CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
  3429. return CGF.Builder.CreateStructGEP(base, idx, field->getName());
  3430. }
  3431. static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
  3432. const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
  3433. if (!RD)
  3434. return false;
  3435. if (RD->isDynamicClass())
  3436. return true;
  3437. for (const auto &Base : RD->bases())
  3438. if (hasAnyVptr(Base.getType(), Context))
  3439. return true;
  3440. for (const FieldDecl *Field : RD->fields())
  3441. if (hasAnyVptr(Field->getType(), Context))
  3442. return true;
  3443. return false;
  3444. }
  3445. LValue CodeGenFunction::EmitLValueForField(LValue base,
  3446. const FieldDecl *field) {
  3447. LValueBaseInfo BaseInfo = base.getBaseInfo();
  3448. if (field->isBitField()) {
  3449. const CGRecordLayout &RL =
  3450. CGM.getTypes().getCGRecordLayout(field->getParent());
  3451. const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
  3452. Address Addr = base.getAddress();
  3453. unsigned Idx = RL.getLLVMFieldNo(field);
  3454. if (Idx != 0)
  3455. // For structs, we GEP to the field that the record layout suggests.
  3456. Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
  3457. // Get the access type.
  3458. llvm::Type *FieldIntTy =
  3459. llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
  3460. if (Addr.getElementType() != FieldIntTy)
  3461. Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
  3462. QualType fieldType =
  3463. field->getType().withCVRQualifiers(base.getVRQualifiers());
  3464. // TODO: Support TBAA for bit fields.
  3465. LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
  3466. return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
  3467. TBAAAccessInfo());
  3468. }
  3469. // Fields of may-alias structures are may-alias themselves.
  3470. // FIXME: this should get propagated down through anonymous structs
  3471. // and unions.
  3472. QualType FieldType = field->getType();
  3473. const RecordDecl *rec = field->getParent();
  3474. AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
  3475. LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
  3476. TBAAAccessInfo FieldTBAAInfo;
  3477. if (base.getTBAAInfo().isMayAlias() ||
  3478. rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
  3479. FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
  3480. } else if (rec->isUnion()) {
  3481. // TODO: Support TBAA for unions.
  3482. FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
  3483. } else {
  3484. // If no base type been assigned for the base access, then try to generate
  3485. // one for this base lvalue.
  3486. FieldTBAAInfo = base.getTBAAInfo();
  3487. if (!FieldTBAAInfo.BaseType) {
  3488. FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
  3489. assert(!FieldTBAAInfo.Offset &&
  3490. "Nonzero offset for an access with no base type!");
  3491. }
  3492. // Adjust offset to be relative to the base type.
  3493. const ASTRecordLayout &Layout =
  3494. getContext().getASTRecordLayout(field->getParent());
  3495. unsigned CharWidth = getContext().getCharWidth();
  3496. if (FieldTBAAInfo.BaseType)
  3497. FieldTBAAInfo.Offset +=
  3498. Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
  3499. // Update the final access type and size.
  3500. FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
  3501. FieldTBAAInfo.Size =
  3502. getContext().getTypeSizeInChars(FieldType).getQuantity();
  3503. }
  3504. Address addr = base.getAddress();
  3505. if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
  3506. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  3507. ClassDef->isDynamicClass()) {
  3508. // Getting to any field of dynamic object requires stripping dynamic
  3509. // information provided by invariant.group. This is because accessing
  3510. // fields may leak the real address of dynamic object, which could result
  3511. // in miscompilation when leaked pointer would be compared.
  3512. auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
  3513. addr = Address(stripped, addr.getAlignment());
  3514. }
  3515. }
  3516. unsigned RecordCVR = base.getVRQualifiers();
  3517. if (rec->isUnion()) {
  3518. // For unions, there is no pointer adjustment.
  3519. assert(!FieldType->isReferenceType() && "union has reference member");
  3520. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  3521. hasAnyVptr(FieldType, getContext()))
  3522. // Because unions can easily skip invariant.barriers, we need to add
  3523. // a barrier every time CXXRecord field with vptr is referenced.
  3524. addr = Address(Builder.CreateLaunderInvariantGroup(addr.getPointer()),
  3525. addr.getAlignment());
  3526. } else {
  3527. // For structs, we GEP to the field that the record layout suggests.
  3528. addr = emitAddrOfFieldStorage(*this, addr, field);
  3529. // If this is a reference field, load the reference right now.
  3530. if (FieldType->isReferenceType()) {
  3531. LValue RefLVal = MakeAddrLValue(addr, FieldType, FieldBaseInfo,
  3532. FieldTBAAInfo);
  3533. if (RecordCVR & Qualifiers::Volatile)
  3534. RefLVal.getQuals().addVolatile();
  3535. addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
  3536. // Qualifiers on the struct don't apply to the referencee.
  3537. RecordCVR = 0;
  3538. FieldType = FieldType->getPointeeType();
  3539. }
  3540. }
  3541. // Make sure that the address is pointing to the right type. This is critical
  3542. // for both unions and structs. A union needs a bitcast, a struct element
  3543. // will need a bitcast if the LLVM type laid out doesn't match the desired
  3544. // type.
  3545. addr = Builder.CreateElementBitCast(
  3546. addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
  3547. if (field->hasAttr<AnnotateAttr>())
  3548. addr = EmitFieldAnnotations(field, addr);
  3549. LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
  3550. LV.getQuals().addCVRQualifiers(RecordCVR);
  3551. // __weak attribute on a field is ignored.
  3552. if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
  3553. LV.getQuals().removeObjCGCAttr();
  3554. return LV;
  3555. }
  3556. LValue
  3557. CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
  3558. const FieldDecl *Field) {
  3559. QualType FieldType = Field->getType();
  3560. if (!FieldType->isReferenceType())
  3561. return EmitLValueForField(Base, Field);
  3562. Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
  3563. // Make sure that the address is pointing to the right type.
  3564. llvm::Type *llvmType = ConvertTypeForMem(FieldType);
  3565. V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
  3566. // TODO: Generate TBAA information that describes this access as a structure
  3567. // member access and not just an access to an object of the field's type. This
  3568. // should be similar to what we do in EmitLValueForField().
  3569. LValueBaseInfo BaseInfo = Base.getBaseInfo();
  3570. AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
  3571. LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
  3572. return MakeAddrLValue(V, FieldType, FieldBaseInfo,
  3573. CGM.getTBAAInfoForSubobject(Base, FieldType));
  3574. }
  3575. LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
  3576. if (E->isFileScope()) {
  3577. ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
  3578. return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
  3579. }
  3580. if (E->getType()->isVariablyModifiedType())
  3581. // make sure to emit the VLA size.
  3582. EmitVariablyModifiedType(E->getType());
  3583. Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
  3584. const Expr *InitExpr = E->getInitializer();
  3585. LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
  3586. EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
  3587. /*Init*/ true);
  3588. return Result;
  3589. }
  3590. LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
  3591. if (!E->isGLValue())
  3592. // Initializing an aggregate temporary in C++11: T{...}.
  3593. return EmitAggExprToLValue(E);
  3594. // An lvalue initializer list must be initializing a reference.
  3595. assert(E->isTransparent() && "non-transparent glvalue init list");
  3596. return EmitLValue(E->getInit(0));
  3597. }
  3598. /// Emit the operand of a glvalue conditional operator. This is either a glvalue
  3599. /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
  3600. /// LValue is returned and the current block has been terminated.
  3601. static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
  3602. const Expr *Operand) {
  3603. if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
  3604. CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
  3605. return None;
  3606. }
  3607. return CGF.EmitLValue(Operand);
  3608. }
  3609. LValue CodeGenFunction::
  3610. EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
  3611. if (!expr->isGLValue()) {
  3612. // ?: here should be an aggregate.
  3613. assert(hasAggregateEvaluationKind(expr->getType()) &&
  3614. "Unexpected conditional operator!");
  3615. return EmitAggExprToLValue(expr);
  3616. }
  3617. OpaqueValueMapping binding(*this, expr);
  3618. const Expr *condExpr = expr->getCond();
  3619. bool CondExprBool;
  3620. if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
  3621. const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
  3622. if (!CondExprBool) std::swap(live, dead);
  3623. if (!ContainsLabel(dead)) {
  3624. // If the true case is live, we need to track its region.
  3625. if (CondExprBool)
  3626. incrementProfileCounter(expr);
  3627. return EmitLValue(live);
  3628. }
  3629. }
  3630. llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
  3631. llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
  3632. llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
  3633. ConditionalEvaluation eval(*this);
  3634. EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
  3635. // Any temporaries created here are conditional.
  3636. EmitBlock(lhsBlock);
  3637. incrementProfileCounter(expr);
  3638. eval.begin(*this);
  3639. Optional<LValue> lhs =
  3640. EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
  3641. eval.end(*this);
  3642. if (lhs && !lhs->isSimple())
  3643. return EmitUnsupportedLValue(expr, "conditional operator");
  3644. lhsBlock = Builder.GetInsertBlock();
  3645. if (lhs)
  3646. Builder.CreateBr(contBlock);
  3647. // Any temporaries created here are conditional.
  3648. EmitBlock(rhsBlock);
  3649. eval.begin(*this);
  3650. Optional<LValue> rhs =
  3651. EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
  3652. eval.end(*this);
  3653. if (rhs && !rhs->isSimple())
  3654. return EmitUnsupportedLValue(expr, "conditional operator");
  3655. rhsBlock = Builder.GetInsertBlock();
  3656. EmitBlock(contBlock);
  3657. if (lhs && rhs) {
  3658. llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
  3659. 2, "cond-lvalue");
  3660. phi->addIncoming(lhs->getPointer(), lhsBlock);
  3661. phi->addIncoming(rhs->getPointer(), rhsBlock);
  3662. Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
  3663. AlignmentSource alignSource =
  3664. std::max(lhs->getBaseInfo().getAlignmentSource(),
  3665. rhs->getBaseInfo().getAlignmentSource());
  3666. TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
  3667. lhs->getTBAAInfo(), rhs->getTBAAInfo());
  3668. return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
  3669. TBAAInfo);
  3670. } else {
  3671. assert((lhs || rhs) &&
  3672. "both operands of glvalue conditional are throw-expressions?");
  3673. return lhs ? *lhs : *rhs;
  3674. }
  3675. }
  3676. /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
  3677. /// type. If the cast is to a reference, we can have the usual lvalue result,
  3678. /// otherwise if a cast is needed by the code generator in an lvalue context,
  3679. /// then it must mean that we need the address of an aggregate in order to
  3680. /// access one of its members. This can happen for all the reasons that casts
  3681. /// are permitted with aggregate result, including noop aggregate casts, and
  3682. /// cast from scalar to union.
  3683. LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
  3684. switch (E->getCastKind()) {
  3685. case CK_ToVoid:
  3686. case CK_BitCast:
  3687. case CK_ArrayToPointerDecay:
  3688. case CK_FunctionToPointerDecay:
  3689. case CK_NullToMemberPointer:
  3690. case CK_NullToPointer:
  3691. case CK_IntegralToPointer:
  3692. case CK_PointerToIntegral:
  3693. case CK_PointerToBoolean:
  3694. case CK_VectorSplat:
  3695. case CK_IntegralCast:
  3696. case CK_BooleanToSignedIntegral:
  3697. case CK_IntegralToBoolean:
  3698. case CK_IntegralToFloating:
  3699. case CK_FloatingToIntegral:
  3700. case CK_FloatingToBoolean:
  3701. case CK_FloatingCast:
  3702. case CK_FloatingRealToComplex:
  3703. case CK_FloatingComplexToReal:
  3704. case CK_FloatingComplexToBoolean:
  3705. case CK_FloatingComplexCast:
  3706. case CK_FloatingComplexToIntegralComplex:
  3707. case CK_IntegralRealToComplex:
  3708. case CK_IntegralComplexToReal:
  3709. case CK_IntegralComplexToBoolean:
  3710. case CK_IntegralComplexCast:
  3711. case CK_IntegralComplexToFloatingComplex:
  3712. case CK_DerivedToBaseMemberPointer:
  3713. case CK_BaseToDerivedMemberPointer:
  3714. case CK_MemberPointerToBoolean:
  3715. case CK_ReinterpretMemberPointer:
  3716. case CK_AnyPointerToBlockPointerCast:
  3717. case CK_ARCProduceObject:
  3718. case CK_ARCConsumeObject:
  3719. case CK_ARCReclaimReturnedObject:
  3720. case CK_ARCExtendBlockObject:
  3721. case CK_CopyAndAutoreleaseBlockObject:
  3722. case CK_IntToOCLSampler:
  3723. case CK_FixedPointCast:
  3724. case CK_FixedPointToBoolean:
  3725. case CK_FixedPointToIntegral:
  3726. case CK_IntegralToFixedPoint:
  3727. return EmitUnsupportedLValue(E, "unexpected cast lvalue");
  3728. case CK_Dependent:
  3729. llvm_unreachable("dependent cast kind in IR gen!");
  3730. case CK_BuiltinFnToFnPtr:
  3731. llvm_unreachable("builtin functions are handled elsewhere");
  3732. // These are never l-values; just use the aggregate emission code.
  3733. case CK_NonAtomicToAtomic:
  3734. case CK_AtomicToNonAtomic:
  3735. return EmitAggExprToLValue(E);
  3736. case CK_Dynamic: {
  3737. LValue LV = EmitLValue(E->getSubExpr());
  3738. Address V = LV.getAddress();
  3739. const auto *DCE = cast<CXXDynamicCastExpr>(E);
  3740. return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
  3741. }
  3742. case CK_ConstructorConversion:
  3743. case CK_UserDefinedConversion:
  3744. case CK_CPointerToObjCPointerCast:
  3745. case CK_BlockPointerToObjCPointerCast:
  3746. case CK_NoOp:
  3747. case CK_LValueToRValue:
  3748. return EmitLValue(E->getSubExpr());
  3749. case CK_UncheckedDerivedToBase:
  3750. case CK_DerivedToBase: {
  3751. const RecordType *DerivedClassTy =
  3752. E->getSubExpr()->getType()->getAs<RecordType>();
  3753. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  3754. LValue LV = EmitLValue(E->getSubExpr());
  3755. Address This = LV.getAddress();
  3756. // Perform the derived-to-base conversion
  3757. Address Base = GetAddressOfBaseClass(
  3758. This, DerivedClassDecl, E->path_begin(), E->path_end(),
  3759. /*NullCheckValue=*/false, E->getExprLoc());
  3760. // TODO: Support accesses to members of base classes in TBAA. For now, we
  3761. // conservatively pretend that the complete object is of the base class
  3762. // type.
  3763. return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
  3764. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  3765. }
  3766. case CK_ToUnion:
  3767. return EmitAggExprToLValue(E);
  3768. case CK_BaseToDerived: {
  3769. const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
  3770. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  3771. LValue LV = EmitLValue(E->getSubExpr());
  3772. // Perform the base-to-derived conversion
  3773. Address Derived =
  3774. GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
  3775. E->path_begin(), E->path_end(),
  3776. /*NullCheckValue=*/false);
  3777. // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
  3778. // performed and the object is not of the derived type.
  3779. if (sanitizePerformTypeCheck())
  3780. EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
  3781. Derived.getPointer(), E->getType());
  3782. if (SanOpts.has(SanitizerKind::CFIDerivedCast))
  3783. EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
  3784. /*MayBeNull=*/false, CFITCK_DerivedCast,
  3785. E->getBeginLoc());
  3786. return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
  3787. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  3788. }
  3789. case CK_LValueBitCast: {
  3790. // This must be a reinterpret_cast (or c-style equivalent).
  3791. const auto *CE = cast<ExplicitCastExpr>(E);
  3792. CGM.EmitExplicitCastExprType(CE, this);
  3793. LValue LV = EmitLValue(E->getSubExpr());
  3794. Address V = Builder.CreateBitCast(LV.getAddress(),
  3795. ConvertType(CE->getTypeAsWritten()));
  3796. if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
  3797. EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
  3798. /*MayBeNull=*/false, CFITCK_UnrelatedCast,
  3799. E->getBeginLoc());
  3800. return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
  3801. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  3802. }
  3803. case CK_AddressSpaceConversion: {
  3804. LValue LV = EmitLValue(E->getSubExpr());
  3805. QualType DestTy = getContext().getPointerType(E->getType());
  3806. llvm::Value *V = getTargetHooks().performAddrSpaceCast(
  3807. *this, LV.getPointer(), E->getSubExpr()->getType().getAddressSpace(),
  3808. E->getType().getAddressSpace(), ConvertType(DestTy));
  3809. return MakeAddrLValue(Address(V, LV.getAddress().getAlignment()),
  3810. E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
  3811. }
  3812. case CK_ObjCObjectLValueCast: {
  3813. LValue LV = EmitLValue(E->getSubExpr());
  3814. Address V = Builder.CreateElementBitCast(LV.getAddress(),
  3815. ConvertType(E->getType()));
  3816. return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
  3817. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  3818. }
  3819. case CK_ZeroToOCLOpaqueType:
  3820. llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
  3821. }
  3822. llvm_unreachable("Unhandled lvalue cast kind?");
  3823. }
  3824. LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
  3825. assert(OpaqueValueMappingData::shouldBindAsLValue(e));
  3826. return getOrCreateOpaqueLValueMapping(e);
  3827. }
  3828. LValue
  3829. CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
  3830. assert(OpaqueValueMapping::shouldBindAsLValue(e));
  3831. llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
  3832. it = OpaqueLValues.find(e);
  3833. if (it != OpaqueLValues.end())
  3834. return it->second;
  3835. assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
  3836. return EmitLValue(e->getSourceExpr());
  3837. }
  3838. RValue
  3839. CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
  3840. assert(!OpaqueValueMapping::shouldBindAsLValue(e));
  3841. llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
  3842. it = OpaqueRValues.find(e);
  3843. if (it != OpaqueRValues.end())
  3844. return it->second;
  3845. assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
  3846. return EmitAnyExpr(e->getSourceExpr());
  3847. }
  3848. RValue CodeGenFunction::EmitRValueForField(LValue LV,
  3849. const FieldDecl *FD,
  3850. SourceLocation Loc) {
  3851. QualType FT = FD->getType();
  3852. LValue FieldLV = EmitLValueForField(LV, FD);
  3853. switch (getEvaluationKind(FT)) {
  3854. case TEK_Complex:
  3855. return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
  3856. case TEK_Aggregate:
  3857. return FieldLV.asAggregateRValue();
  3858. case TEK_Scalar:
  3859. // This routine is used to load fields one-by-one to perform a copy, so
  3860. // don't load reference fields.
  3861. if (FD->getType()->isReferenceType())
  3862. return RValue::get(FieldLV.getPointer());
  3863. return EmitLoadOfLValue(FieldLV, Loc);
  3864. }
  3865. llvm_unreachable("bad evaluation kind");
  3866. }
  3867. //===--------------------------------------------------------------------===//
  3868. // Expression Emission
  3869. //===--------------------------------------------------------------------===//
  3870. RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
  3871. ReturnValueSlot ReturnValue) {
  3872. // Builtins never have block type.
  3873. if (E->getCallee()->getType()->isBlockPointerType())
  3874. return EmitBlockCallExpr(E, ReturnValue);
  3875. if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
  3876. return EmitCXXMemberCallExpr(CE, ReturnValue);
  3877. if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
  3878. return EmitCUDAKernelCallExpr(CE, ReturnValue);
  3879. if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
  3880. if (const CXXMethodDecl *MD =
  3881. dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
  3882. return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
  3883. CGCallee callee = EmitCallee(E->getCallee());
  3884. if (callee.isBuiltin()) {
  3885. return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
  3886. E, ReturnValue);
  3887. }
  3888. if (callee.isPseudoDestructor()) {
  3889. return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
  3890. }
  3891. return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
  3892. }
  3893. /// Emit a CallExpr without considering whether it might be a subclass.
  3894. RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
  3895. ReturnValueSlot ReturnValue) {
  3896. CGCallee Callee = EmitCallee(E->getCallee());
  3897. return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
  3898. }
  3899. static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
  3900. if (auto builtinID = FD->getBuiltinID()) {
  3901. return CGCallee::forBuiltin(builtinID, FD);
  3902. }
  3903. llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
  3904. return CGCallee::forDirect(calleePtr, GlobalDecl(FD));
  3905. }
  3906. CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
  3907. E = E->IgnoreParens();
  3908. // Look through function-to-pointer decay.
  3909. if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
  3910. if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
  3911. ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
  3912. return EmitCallee(ICE->getSubExpr());
  3913. }
  3914. // Resolve direct calls.
  3915. } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
  3916. if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
  3917. return EmitDirectCallee(*this, FD);
  3918. }
  3919. } else if (auto ME = dyn_cast<MemberExpr>(E)) {
  3920. if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
  3921. EmitIgnoredExpr(ME->getBase());
  3922. return EmitDirectCallee(*this, FD);
  3923. }
  3924. // Look through template substitutions.
  3925. } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
  3926. return EmitCallee(NTTP->getReplacement());
  3927. // Treat pseudo-destructor calls differently.
  3928. } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
  3929. return CGCallee::forPseudoDestructor(PDE);
  3930. }
  3931. // Otherwise, we have an indirect reference.
  3932. llvm::Value *calleePtr;
  3933. QualType functionType;
  3934. if (auto ptrType = E->getType()->getAs<PointerType>()) {
  3935. calleePtr = EmitScalarExpr(E);
  3936. functionType = ptrType->getPointeeType();
  3937. } else {
  3938. functionType = E->getType();
  3939. calleePtr = EmitLValue(E).getPointer();
  3940. }
  3941. assert(functionType->isFunctionType());
  3942. GlobalDecl GD;
  3943. if (const auto *VD =
  3944. dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
  3945. GD = GlobalDecl(VD);
  3946. CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
  3947. CGCallee callee(calleeInfo, calleePtr);
  3948. return callee;
  3949. }
  3950. LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
  3951. // Comma expressions just emit their LHS then their RHS as an l-value.
  3952. if (E->getOpcode() == BO_Comma) {
  3953. EmitIgnoredExpr(E->getLHS());
  3954. EnsureInsertPoint();
  3955. return EmitLValue(E->getRHS());
  3956. }
  3957. if (E->getOpcode() == BO_PtrMemD ||
  3958. E->getOpcode() == BO_PtrMemI)
  3959. return EmitPointerToDataMemberBinaryExpr(E);
  3960. assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
  3961. // Note that in all of these cases, __block variables need the RHS
  3962. // evaluated first just in case the variable gets moved by the RHS.
  3963. switch (getEvaluationKind(E->getType())) {
  3964. case TEK_Scalar: {
  3965. switch (E->getLHS()->getType().getObjCLifetime()) {
  3966. case Qualifiers::OCL_Strong:
  3967. return EmitARCStoreStrong(E, /*ignored*/ false).first;
  3968. case Qualifiers::OCL_Autoreleasing:
  3969. return EmitARCStoreAutoreleasing(E).first;
  3970. // No reason to do any of these differently.
  3971. case Qualifiers::OCL_None:
  3972. case Qualifiers::OCL_ExplicitNone:
  3973. case Qualifiers::OCL_Weak:
  3974. break;
  3975. }
  3976. RValue RV = EmitAnyExpr(E->getRHS());
  3977. LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
  3978. if (RV.isScalar())
  3979. EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
  3980. EmitStoreThroughLValue(RV, LV);
  3981. return LV;
  3982. }
  3983. case TEK_Complex:
  3984. return EmitComplexAssignmentLValue(E);
  3985. case TEK_Aggregate:
  3986. return EmitAggExprToLValue(E);
  3987. }
  3988. llvm_unreachable("bad evaluation kind");
  3989. }
  3990. LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
  3991. RValue RV = EmitCallExpr(E);
  3992. if (!RV.isScalar())
  3993. return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
  3994. AlignmentSource::Decl);
  3995. assert(E->getCallReturnType(getContext())->isReferenceType() &&
  3996. "Can't have a scalar return unless the return type is a "
  3997. "reference type!");
  3998. return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
  3999. }
  4000. LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
  4001. // FIXME: This shouldn't require another copy.
  4002. return EmitAggExprToLValue(E);
  4003. }
  4004. LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
  4005. assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
  4006. && "binding l-value to type which needs a temporary");
  4007. AggValueSlot Slot = CreateAggTemp(E->getType());
  4008. EmitCXXConstructExpr(E, Slot);
  4009. return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
  4010. }
  4011. LValue
  4012. CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
  4013. return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
  4014. }
  4015. Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
  4016. return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
  4017. ConvertType(E->getType()));
  4018. }
  4019. LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
  4020. return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
  4021. AlignmentSource::Decl);
  4022. }
  4023. LValue
  4024. CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
  4025. AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
  4026. Slot.setExternallyDestructed();
  4027. EmitAggExpr(E->getSubExpr(), Slot);
  4028. EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
  4029. return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
  4030. }
  4031. LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
  4032. RValue RV = EmitObjCMessageExpr(E);
  4033. if (!RV.isScalar())
  4034. return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
  4035. AlignmentSource::Decl);
  4036. assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
  4037. "Can't have a scalar return unless the return type is a "
  4038. "reference type!");
  4039. return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
  4040. }
  4041. LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
  4042. Address V =
  4043. CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
  4044. return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
  4045. }
  4046. llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  4047. const ObjCIvarDecl *Ivar) {
  4048. return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
  4049. }
  4050. LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
  4051. llvm::Value *BaseValue,
  4052. const ObjCIvarDecl *Ivar,
  4053. unsigned CVRQualifiers) {
  4054. return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
  4055. Ivar, CVRQualifiers);
  4056. }
  4057. LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
  4058. // FIXME: A lot of the code below could be shared with EmitMemberExpr.
  4059. llvm::Value *BaseValue = nullptr;
  4060. const Expr *BaseExpr = E->getBase();
  4061. Qualifiers BaseQuals;
  4062. QualType ObjectTy;
  4063. if (E->isArrow()) {
  4064. BaseValue = EmitScalarExpr(BaseExpr);
  4065. ObjectTy = BaseExpr->getType()->getPointeeType();
  4066. BaseQuals = ObjectTy.getQualifiers();
  4067. } else {
  4068. LValue BaseLV = EmitLValue(BaseExpr);
  4069. BaseValue = BaseLV.getPointer();
  4070. ObjectTy = BaseExpr->getType();
  4071. BaseQuals = ObjectTy.getQualifiers();
  4072. }
  4073. LValue LV =
  4074. EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
  4075. BaseQuals.getCVRQualifiers());
  4076. setObjCGCLValueClass(getContext(), E, LV);
  4077. return LV;
  4078. }
  4079. LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
  4080. // Can only get l-value for message expression returning aggregate type
  4081. RValue RV = EmitAnyExprToTemp(E);
  4082. return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
  4083. AlignmentSource::Decl);
  4084. }
  4085. RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
  4086. const CallExpr *E, ReturnValueSlot ReturnValue,
  4087. llvm::Value *Chain) {
  4088. // Get the actual function type. The callee type will always be a pointer to
  4089. // function type or a block pointer type.
  4090. assert(CalleeType->isFunctionPointerType() &&
  4091. "Call must have function pointer type!");
  4092. const Decl *TargetDecl =
  4093. OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
  4094. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  4095. // We can only guarantee that a function is called from the correct
  4096. // context/function based on the appropriate target attributes,
  4097. // so only check in the case where we have both always_inline and target
  4098. // since otherwise we could be making a conditional call after a check for
  4099. // the proper cpu features (and it won't cause code generation issues due to
  4100. // function based code generation).
  4101. if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
  4102. TargetDecl->hasAttr<TargetAttr>())
  4103. checkTargetFeatures(E, FD);
  4104. CalleeType = getContext().getCanonicalType(CalleeType);
  4105. auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
  4106. CGCallee Callee = OrigCallee;
  4107. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
  4108. (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
  4109. if (llvm::Constant *PrefixSig =
  4110. CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
  4111. SanitizerScope SanScope(this);
  4112. // Remove any (C++17) exception specifications, to allow calling e.g. a
  4113. // noexcept function through a non-noexcept pointer.
  4114. auto ProtoTy =
  4115. getContext().getFunctionTypeWithExceptionSpec(PointeeType, EST_None);
  4116. llvm::Constant *FTRTTIConst =
  4117. CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
  4118. llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
  4119. llvm::StructType *PrefixStructTy = llvm::StructType::get(
  4120. CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
  4121. llvm::Value *CalleePtr = Callee.getFunctionPointer();
  4122. llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
  4123. CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
  4124. llvm::Value *CalleeSigPtr =
  4125. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
  4126. llvm::Value *CalleeSig =
  4127. Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
  4128. llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
  4129. llvm::BasicBlock *Cont = createBasicBlock("cont");
  4130. llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
  4131. Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
  4132. EmitBlock(TypeCheck);
  4133. llvm::Value *CalleeRTTIPtr =
  4134. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
  4135. llvm::Value *CalleeRTTIEncoded =
  4136. Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
  4137. llvm::Value *CalleeRTTI =
  4138. DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
  4139. llvm::Value *CalleeRTTIMatch =
  4140. Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
  4141. llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
  4142. EmitCheckTypeDescriptor(CalleeType)};
  4143. EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
  4144. SanitizerHandler::FunctionTypeMismatch, StaticData,
  4145. {CalleePtr, CalleeRTTI, FTRTTIConst});
  4146. Builder.CreateBr(Cont);
  4147. EmitBlock(Cont);
  4148. }
  4149. }
  4150. const auto *FnType = cast<FunctionType>(PointeeType);
  4151. // If we are checking indirect calls and this call is indirect, check that the
  4152. // function pointer is a member of the bit set for the function type.
  4153. if (SanOpts.has(SanitizerKind::CFIICall) &&
  4154. (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
  4155. SanitizerScope SanScope(this);
  4156. EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
  4157. llvm::Metadata *MD;
  4158. if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
  4159. MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
  4160. else
  4161. MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
  4162. llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
  4163. llvm::Value *CalleePtr = Callee.getFunctionPointer();
  4164. llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
  4165. llvm::Value *TypeTest = Builder.CreateCall(
  4166. CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
  4167. auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
  4168. llvm::Constant *StaticData[] = {
  4169. llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
  4170. EmitCheckSourceLocation(E->getBeginLoc()),
  4171. EmitCheckTypeDescriptor(QualType(FnType, 0)),
  4172. };
  4173. if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
  4174. EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
  4175. CastedCallee, StaticData);
  4176. } else {
  4177. EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
  4178. SanitizerHandler::CFICheckFail, StaticData,
  4179. {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
  4180. }
  4181. }
  4182. CallArgList Args;
  4183. if (Chain)
  4184. Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
  4185. CGM.getContext().VoidPtrTy);
  4186. // C++17 requires that we evaluate arguments to a call using assignment syntax
  4187. // right-to-left, and that we evaluate arguments to certain other operators
  4188. // left-to-right. Note that we allow this to override the order dictated by
  4189. // the calling convention on the MS ABI, which means that parameter
  4190. // destruction order is not necessarily reverse construction order.
  4191. // FIXME: Revisit this based on C++ committee response to unimplementability.
  4192. EvaluationOrder Order = EvaluationOrder::Default;
  4193. if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
  4194. if (OCE->isAssignmentOp())
  4195. Order = EvaluationOrder::ForceRightToLeft;
  4196. else {
  4197. switch (OCE->getOperator()) {
  4198. case OO_LessLess:
  4199. case OO_GreaterGreater:
  4200. case OO_AmpAmp:
  4201. case OO_PipePipe:
  4202. case OO_Comma:
  4203. case OO_ArrowStar:
  4204. Order = EvaluationOrder::ForceLeftToRight;
  4205. break;
  4206. default:
  4207. break;
  4208. }
  4209. }
  4210. }
  4211. EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
  4212. E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
  4213. const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
  4214. Args, FnType, /*isChainCall=*/Chain);
  4215. // C99 6.5.2.2p6:
  4216. // If the expression that denotes the called function has a type
  4217. // that does not include a prototype, [the default argument
  4218. // promotions are performed]. If the number of arguments does not
  4219. // equal the number of parameters, the behavior is undefined. If
  4220. // the function is defined with a type that includes a prototype,
  4221. // and either the prototype ends with an ellipsis (, ...) or the
  4222. // types of the arguments after promotion are not compatible with
  4223. // the types of the parameters, the behavior is undefined. If the
  4224. // function is defined with a type that does not include a
  4225. // prototype, and the types of the arguments after promotion are
  4226. // not compatible with those of the parameters after promotion,
  4227. // the behavior is undefined [except in some trivial cases].
  4228. // That is, in the general case, we should assume that a call
  4229. // through an unprototyped function type works like a *non-variadic*
  4230. // call. The way we make this work is to cast to the exact type
  4231. // of the promoted arguments.
  4232. //
  4233. // Chain calls use this same code path to add the invisible chain parameter
  4234. // to the function type.
  4235. if (isa<FunctionNoProtoType>(FnType) || Chain) {
  4236. llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
  4237. CalleeTy = CalleeTy->getPointerTo();
  4238. llvm::Value *CalleePtr = Callee.getFunctionPointer();
  4239. CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
  4240. Callee.setFunctionPointer(CalleePtr);
  4241. }
  4242. return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr, E->getExprLoc());
  4243. }
  4244. LValue CodeGenFunction::
  4245. EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
  4246. Address BaseAddr = Address::invalid();
  4247. if (E->getOpcode() == BO_PtrMemI) {
  4248. BaseAddr = EmitPointerWithAlignment(E->getLHS());
  4249. } else {
  4250. BaseAddr = EmitLValue(E->getLHS()).getAddress();
  4251. }
  4252. llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
  4253. const MemberPointerType *MPT
  4254. = E->getRHS()->getType()->getAs<MemberPointerType>();
  4255. LValueBaseInfo BaseInfo;
  4256. TBAAAccessInfo TBAAInfo;
  4257. Address MemberAddr =
  4258. EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
  4259. &TBAAInfo);
  4260. return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
  4261. }
  4262. /// Given the address of a temporary variable, produce an r-value of
  4263. /// its type.
  4264. RValue CodeGenFunction::convertTempToRValue(Address addr,
  4265. QualType type,
  4266. SourceLocation loc) {
  4267. LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
  4268. switch (getEvaluationKind(type)) {
  4269. case TEK_Complex:
  4270. return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
  4271. case TEK_Aggregate:
  4272. return lvalue.asAggregateRValue();
  4273. case TEK_Scalar:
  4274. return RValue::get(EmitLoadOfScalar(lvalue, loc));
  4275. }
  4276. llvm_unreachable("bad evaluation kind");
  4277. }
  4278. void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
  4279. assert(Val->getType()->isFPOrFPVectorTy());
  4280. if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
  4281. return;
  4282. llvm::MDBuilder MDHelper(getLLVMContext());
  4283. llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
  4284. cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
  4285. }
  4286. namespace {
  4287. struct LValueOrRValue {
  4288. LValue LV;
  4289. RValue RV;
  4290. };
  4291. }
  4292. static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
  4293. const PseudoObjectExpr *E,
  4294. bool forLValue,
  4295. AggValueSlot slot) {
  4296. SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
  4297. // Find the result expression, if any.
  4298. const Expr *resultExpr = E->getResultExpr();
  4299. LValueOrRValue result;
  4300. for (PseudoObjectExpr::const_semantics_iterator
  4301. i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
  4302. const Expr *semantic = *i;
  4303. // If this semantic expression is an opaque value, bind it
  4304. // to the result of its source expression.
  4305. if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
  4306. // Skip unique OVEs.
  4307. if (ov->isUnique()) {
  4308. assert(ov != resultExpr &&
  4309. "A unique OVE cannot be used as the result expression");
  4310. continue;
  4311. }
  4312. // If this is the result expression, we may need to evaluate
  4313. // directly into the slot.
  4314. typedef CodeGenFunction::OpaqueValueMappingData OVMA;
  4315. OVMA opaqueData;
  4316. if (ov == resultExpr && ov->isRValue() && !forLValue &&
  4317. CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
  4318. CGF.EmitAggExpr(ov->getSourceExpr(), slot);
  4319. LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
  4320. AlignmentSource::Decl);
  4321. opaqueData = OVMA::bind(CGF, ov, LV);
  4322. result.RV = slot.asRValue();
  4323. // Otherwise, emit as normal.
  4324. } else {
  4325. opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
  4326. // If this is the result, also evaluate the result now.
  4327. if (ov == resultExpr) {
  4328. if (forLValue)
  4329. result.LV = CGF.EmitLValue(ov);
  4330. else
  4331. result.RV = CGF.EmitAnyExpr(ov, slot);
  4332. }
  4333. }
  4334. opaques.push_back(opaqueData);
  4335. // Otherwise, if the expression is the result, evaluate it
  4336. // and remember the result.
  4337. } else if (semantic == resultExpr) {
  4338. if (forLValue)
  4339. result.LV = CGF.EmitLValue(semantic);
  4340. else
  4341. result.RV = CGF.EmitAnyExpr(semantic, slot);
  4342. // Otherwise, evaluate the expression in an ignored context.
  4343. } else {
  4344. CGF.EmitIgnoredExpr(semantic);
  4345. }
  4346. }
  4347. // Unbind all the opaques now.
  4348. for (unsigned i = 0, e = opaques.size(); i != e; ++i)
  4349. opaques[i].unbind(CGF);
  4350. return result;
  4351. }
  4352. RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
  4353. AggValueSlot slot) {
  4354. return emitPseudoObjectExpr(*this, E, false, slot).RV;
  4355. }
  4356. LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
  4357. return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
  4358. }