CGExpr.cpp 196 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012
  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_LValueToRValueBitCast:
  3688. case CK_ArrayToPointerDecay:
  3689. case CK_FunctionToPointerDecay:
  3690. case CK_NullToMemberPointer:
  3691. case CK_NullToPointer:
  3692. case CK_IntegralToPointer:
  3693. case CK_PointerToIntegral:
  3694. case CK_PointerToBoolean:
  3695. case CK_VectorSplat:
  3696. case CK_IntegralCast:
  3697. case CK_BooleanToSignedIntegral:
  3698. case CK_IntegralToBoolean:
  3699. case CK_IntegralToFloating:
  3700. case CK_FloatingToIntegral:
  3701. case CK_FloatingToBoolean:
  3702. case CK_FloatingCast:
  3703. case CK_FloatingRealToComplex:
  3704. case CK_FloatingComplexToReal:
  3705. case CK_FloatingComplexToBoolean:
  3706. case CK_FloatingComplexCast:
  3707. case CK_FloatingComplexToIntegralComplex:
  3708. case CK_IntegralRealToComplex:
  3709. case CK_IntegralComplexToReal:
  3710. case CK_IntegralComplexToBoolean:
  3711. case CK_IntegralComplexCast:
  3712. case CK_IntegralComplexToFloatingComplex:
  3713. case CK_DerivedToBaseMemberPointer:
  3714. case CK_BaseToDerivedMemberPointer:
  3715. case CK_MemberPointerToBoolean:
  3716. case CK_ReinterpretMemberPointer:
  3717. case CK_AnyPointerToBlockPointerCast:
  3718. case CK_ARCProduceObject:
  3719. case CK_ARCConsumeObject:
  3720. case CK_ARCReclaimReturnedObject:
  3721. case CK_ARCExtendBlockObject:
  3722. case CK_CopyAndAutoreleaseBlockObject:
  3723. case CK_IntToOCLSampler:
  3724. case CK_FixedPointCast:
  3725. case CK_FixedPointToBoolean:
  3726. case CK_FixedPointToIntegral:
  3727. case CK_IntegralToFixedPoint:
  3728. return EmitUnsupportedLValue(E, "unexpected cast lvalue");
  3729. case CK_Dependent:
  3730. llvm_unreachable("dependent cast kind in IR gen!");
  3731. case CK_BuiltinFnToFnPtr:
  3732. llvm_unreachable("builtin functions are handled elsewhere");
  3733. // These are never l-values; just use the aggregate emission code.
  3734. case CK_NonAtomicToAtomic:
  3735. case CK_AtomicToNonAtomic:
  3736. return EmitAggExprToLValue(E);
  3737. case CK_Dynamic: {
  3738. LValue LV = EmitLValue(E->getSubExpr());
  3739. Address V = LV.getAddress();
  3740. const auto *DCE = cast<CXXDynamicCastExpr>(E);
  3741. return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
  3742. }
  3743. case CK_ConstructorConversion:
  3744. case CK_UserDefinedConversion:
  3745. case CK_CPointerToObjCPointerCast:
  3746. case CK_BlockPointerToObjCPointerCast:
  3747. case CK_NoOp:
  3748. case CK_LValueToRValue:
  3749. return EmitLValue(E->getSubExpr());
  3750. case CK_UncheckedDerivedToBase:
  3751. case CK_DerivedToBase: {
  3752. const RecordType *DerivedClassTy =
  3753. E->getSubExpr()->getType()->getAs<RecordType>();
  3754. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  3755. LValue LV = EmitLValue(E->getSubExpr());
  3756. Address This = LV.getAddress();
  3757. // Perform the derived-to-base conversion
  3758. Address Base = GetAddressOfBaseClass(
  3759. This, DerivedClassDecl, E->path_begin(), E->path_end(),
  3760. /*NullCheckValue=*/false, E->getExprLoc());
  3761. // TODO: Support accesses to members of base classes in TBAA. For now, we
  3762. // conservatively pretend that the complete object is of the base class
  3763. // type.
  3764. return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
  3765. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  3766. }
  3767. case CK_ToUnion:
  3768. return EmitAggExprToLValue(E);
  3769. case CK_BaseToDerived: {
  3770. const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
  3771. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  3772. LValue LV = EmitLValue(E->getSubExpr());
  3773. // Perform the base-to-derived conversion
  3774. Address Derived =
  3775. GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
  3776. E->path_begin(), E->path_end(),
  3777. /*NullCheckValue=*/false);
  3778. // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
  3779. // performed and the object is not of the derived type.
  3780. if (sanitizePerformTypeCheck())
  3781. EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
  3782. Derived.getPointer(), E->getType());
  3783. if (SanOpts.has(SanitizerKind::CFIDerivedCast))
  3784. EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
  3785. /*MayBeNull=*/false, CFITCK_DerivedCast,
  3786. E->getBeginLoc());
  3787. return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
  3788. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  3789. }
  3790. case CK_LValueBitCast: {
  3791. // This must be a reinterpret_cast (or c-style equivalent).
  3792. const auto *CE = cast<ExplicitCastExpr>(E);
  3793. CGM.EmitExplicitCastExprType(CE, this);
  3794. LValue LV = EmitLValue(E->getSubExpr());
  3795. Address V = Builder.CreateBitCast(LV.getAddress(),
  3796. ConvertType(CE->getTypeAsWritten()));
  3797. if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
  3798. EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
  3799. /*MayBeNull=*/false, CFITCK_UnrelatedCast,
  3800. E->getBeginLoc());
  3801. return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
  3802. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  3803. }
  3804. case CK_AddressSpaceConversion: {
  3805. LValue LV = EmitLValue(E->getSubExpr());
  3806. QualType DestTy = getContext().getPointerType(E->getType());
  3807. llvm::Value *V = getTargetHooks().performAddrSpaceCast(
  3808. *this, LV.getPointer(), E->getSubExpr()->getType().getAddressSpace(),
  3809. E->getType().getAddressSpace(), ConvertType(DestTy));
  3810. return MakeAddrLValue(Address(V, LV.getAddress().getAlignment()),
  3811. E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
  3812. }
  3813. case CK_ObjCObjectLValueCast: {
  3814. LValue LV = EmitLValue(E->getSubExpr());
  3815. Address V = Builder.CreateElementBitCast(LV.getAddress(),
  3816. ConvertType(E->getType()));
  3817. return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
  3818. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  3819. }
  3820. case CK_ZeroToOCLOpaqueType:
  3821. llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
  3822. }
  3823. llvm_unreachable("Unhandled lvalue cast kind?");
  3824. }
  3825. LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
  3826. assert(OpaqueValueMappingData::shouldBindAsLValue(e));
  3827. return getOrCreateOpaqueLValueMapping(e);
  3828. }
  3829. LValue
  3830. CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
  3831. assert(OpaqueValueMapping::shouldBindAsLValue(e));
  3832. llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
  3833. it = OpaqueLValues.find(e);
  3834. if (it != OpaqueLValues.end())
  3835. return it->second;
  3836. assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
  3837. return EmitLValue(e->getSourceExpr());
  3838. }
  3839. RValue
  3840. CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
  3841. assert(!OpaqueValueMapping::shouldBindAsLValue(e));
  3842. llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
  3843. it = OpaqueRValues.find(e);
  3844. if (it != OpaqueRValues.end())
  3845. return it->second;
  3846. assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
  3847. return EmitAnyExpr(e->getSourceExpr());
  3848. }
  3849. RValue CodeGenFunction::EmitRValueForField(LValue LV,
  3850. const FieldDecl *FD,
  3851. SourceLocation Loc) {
  3852. QualType FT = FD->getType();
  3853. LValue FieldLV = EmitLValueForField(LV, FD);
  3854. switch (getEvaluationKind(FT)) {
  3855. case TEK_Complex:
  3856. return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
  3857. case TEK_Aggregate:
  3858. return FieldLV.asAggregateRValue();
  3859. case TEK_Scalar:
  3860. // This routine is used to load fields one-by-one to perform a copy, so
  3861. // don't load reference fields.
  3862. if (FD->getType()->isReferenceType())
  3863. return RValue::get(FieldLV.getPointer());
  3864. return EmitLoadOfLValue(FieldLV, Loc);
  3865. }
  3866. llvm_unreachable("bad evaluation kind");
  3867. }
  3868. //===--------------------------------------------------------------------===//
  3869. // Expression Emission
  3870. //===--------------------------------------------------------------------===//
  3871. RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
  3872. ReturnValueSlot ReturnValue) {
  3873. // Builtins never have block type.
  3874. if (E->getCallee()->getType()->isBlockPointerType())
  3875. return EmitBlockCallExpr(E, ReturnValue);
  3876. if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
  3877. return EmitCXXMemberCallExpr(CE, ReturnValue);
  3878. if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
  3879. return EmitCUDAKernelCallExpr(CE, ReturnValue);
  3880. if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
  3881. if (const CXXMethodDecl *MD =
  3882. dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
  3883. return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
  3884. CGCallee callee = EmitCallee(E->getCallee());
  3885. if (callee.isBuiltin()) {
  3886. return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
  3887. E, ReturnValue);
  3888. }
  3889. if (callee.isPseudoDestructor()) {
  3890. return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
  3891. }
  3892. return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
  3893. }
  3894. /// Emit a CallExpr without considering whether it might be a subclass.
  3895. RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
  3896. ReturnValueSlot ReturnValue) {
  3897. CGCallee Callee = EmitCallee(E->getCallee());
  3898. return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
  3899. }
  3900. static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
  3901. if (auto builtinID = FD->getBuiltinID()) {
  3902. return CGCallee::forBuiltin(builtinID, FD);
  3903. }
  3904. llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
  3905. return CGCallee::forDirect(calleePtr, GlobalDecl(FD));
  3906. }
  3907. CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
  3908. E = E->IgnoreParens();
  3909. // Look through function-to-pointer decay.
  3910. if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
  3911. if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
  3912. ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
  3913. return EmitCallee(ICE->getSubExpr());
  3914. }
  3915. // Resolve direct calls.
  3916. } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
  3917. if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
  3918. return EmitDirectCallee(*this, FD);
  3919. }
  3920. } else if (auto ME = dyn_cast<MemberExpr>(E)) {
  3921. if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
  3922. EmitIgnoredExpr(ME->getBase());
  3923. return EmitDirectCallee(*this, FD);
  3924. }
  3925. // Look through template substitutions.
  3926. } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
  3927. return EmitCallee(NTTP->getReplacement());
  3928. // Treat pseudo-destructor calls differently.
  3929. } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
  3930. return CGCallee::forPseudoDestructor(PDE);
  3931. }
  3932. // Otherwise, we have an indirect reference.
  3933. llvm::Value *calleePtr;
  3934. QualType functionType;
  3935. if (auto ptrType = E->getType()->getAs<PointerType>()) {
  3936. calleePtr = EmitScalarExpr(E);
  3937. functionType = ptrType->getPointeeType();
  3938. } else {
  3939. functionType = E->getType();
  3940. calleePtr = EmitLValue(E).getPointer();
  3941. }
  3942. assert(functionType->isFunctionType());
  3943. GlobalDecl GD;
  3944. if (const auto *VD =
  3945. dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
  3946. GD = GlobalDecl(VD);
  3947. CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
  3948. CGCallee callee(calleeInfo, calleePtr);
  3949. return callee;
  3950. }
  3951. LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
  3952. // Comma expressions just emit their LHS then their RHS as an l-value.
  3953. if (E->getOpcode() == BO_Comma) {
  3954. EmitIgnoredExpr(E->getLHS());
  3955. EnsureInsertPoint();
  3956. return EmitLValue(E->getRHS());
  3957. }
  3958. if (E->getOpcode() == BO_PtrMemD ||
  3959. E->getOpcode() == BO_PtrMemI)
  3960. return EmitPointerToDataMemberBinaryExpr(E);
  3961. assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
  3962. // Note that in all of these cases, __block variables need the RHS
  3963. // evaluated first just in case the variable gets moved by the RHS.
  3964. switch (getEvaluationKind(E->getType())) {
  3965. case TEK_Scalar: {
  3966. switch (E->getLHS()->getType().getObjCLifetime()) {
  3967. case Qualifiers::OCL_Strong:
  3968. return EmitARCStoreStrong(E, /*ignored*/ false).first;
  3969. case Qualifiers::OCL_Autoreleasing:
  3970. return EmitARCStoreAutoreleasing(E).first;
  3971. // No reason to do any of these differently.
  3972. case Qualifiers::OCL_None:
  3973. case Qualifiers::OCL_ExplicitNone:
  3974. case Qualifiers::OCL_Weak:
  3975. break;
  3976. }
  3977. RValue RV = EmitAnyExpr(E->getRHS());
  3978. LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
  3979. if (RV.isScalar())
  3980. EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
  3981. EmitStoreThroughLValue(RV, LV);
  3982. return LV;
  3983. }
  3984. case TEK_Complex:
  3985. return EmitComplexAssignmentLValue(E);
  3986. case TEK_Aggregate:
  3987. return EmitAggExprToLValue(E);
  3988. }
  3989. llvm_unreachable("bad evaluation kind");
  3990. }
  3991. LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
  3992. RValue RV = EmitCallExpr(E);
  3993. if (!RV.isScalar())
  3994. return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
  3995. AlignmentSource::Decl);
  3996. assert(E->getCallReturnType(getContext())->isReferenceType() &&
  3997. "Can't have a scalar return unless the return type is a "
  3998. "reference type!");
  3999. return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
  4000. }
  4001. LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
  4002. // FIXME: This shouldn't require another copy.
  4003. return EmitAggExprToLValue(E);
  4004. }
  4005. LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
  4006. assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
  4007. && "binding l-value to type which needs a temporary");
  4008. AggValueSlot Slot = CreateAggTemp(E->getType());
  4009. EmitCXXConstructExpr(E, Slot);
  4010. return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
  4011. }
  4012. LValue
  4013. CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
  4014. return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
  4015. }
  4016. Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
  4017. return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
  4018. ConvertType(E->getType()));
  4019. }
  4020. LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
  4021. return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
  4022. AlignmentSource::Decl);
  4023. }
  4024. LValue
  4025. CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
  4026. AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
  4027. Slot.setExternallyDestructed();
  4028. EmitAggExpr(E->getSubExpr(), Slot);
  4029. EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
  4030. return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
  4031. }
  4032. LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
  4033. RValue RV = EmitObjCMessageExpr(E);
  4034. if (!RV.isScalar())
  4035. return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
  4036. AlignmentSource::Decl);
  4037. assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
  4038. "Can't have a scalar return unless the return type is a "
  4039. "reference type!");
  4040. return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
  4041. }
  4042. LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
  4043. Address V =
  4044. CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
  4045. return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
  4046. }
  4047. llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  4048. const ObjCIvarDecl *Ivar) {
  4049. return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
  4050. }
  4051. LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
  4052. llvm::Value *BaseValue,
  4053. const ObjCIvarDecl *Ivar,
  4054. unsigned CVRQualifiers) {
  4055. return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
  4056. Ivar, CVRQualifiers);
  4057. }
  4058. LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
  4059. // FIXME: A lot of the code below could be shared with EmitMemberExpr.
  4060. llvm::Value *BaseValue = nullptr;
  4061. const Expr *BaseExpr = E->getBase();
  4062. Qualifiers BaseQuals;
  4063. QualType ObjectTy;
  4064. if (E->isArrow()) {
  4065. BaseValue = EmitScalarExpr(BaseExpr);
  4066. ObjectTy = BaseExpr->getType()->getPointeeType();
  4067. BaseQuals = ObjectTy.getQualifiers();
  4068. } else {
  4069. LValue BaseLV = EmitLValue(BaseExpr);
  4070. BaseValue = BaseLV.getPointer();
  4071. ObjectTy = BaseExpr->getType();
  4072. BaseQuals = ObjectTy.getQualifiers();
  4073. }
  4074. LValue LV =
  4075. EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
  4076. BaseQuals.getCVRQualifiers());
  4077. setObjCGCLValueClass(getContext(), E, LV);
  4078. return LV;
  4079. }
  4080. LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
  4081. // Can only get l-value for message expression returning aggregate type
  4082. RValue RV = EmitAnyExprToTemp(E);
  4083. return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
  4084. AlignmentSource::Decl);
  4085. }
  4086. RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
  4087. const CallExpr *E, ReturnValueSlot ReturnValue,
  4088. llvm::Value *Chain) {
  4089. // Get the actual function type. The callee type will always be a pointer to
  4090. // function type or a block pointer type.
  4091. assert(CalleeType->isFunctionPointerType() &&
  4092. "Call must have function pointer type!");
  4093. const Decl *TargetDecl =
  4094. OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
  4095. CalleeType = getContext().getCanonicalType(CalleeType);
  4096. auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
  4097. CGCallee Callee = OrigCallee;
  4098. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
  4099. (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
  4100. if (llvm::Constant *PrefixSig =
  4101. CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
  4102. SanitizerScope SanScope(this);
  4103. // Remove any (C++17) exception specifications, to allow calling e.g. a
  4104. // noexcept function through a non-noexcept pointer.
  4105. auto ProtoTy =
  4106. getContext().getFunctionTypeWithExceptionSpec(PointeeType, EST_None);
  4107. llvm::Constant *FTRTTIConst =
  4108. CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
  4109. llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
  4110. llvm::StructType *PrefixStructTy = llvm::StructType::get(
  4111. CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
  4112. llvm::Value *CalleePtr = Callee.getFunctionPointer();
  4113. llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
  4114. CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
  4115. llvm::Value *CalleeSigPtr =
  4116. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
  4117. llvm::Value *CalleeSig =
  4118. Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
  4119. llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
  4120. llvm::BasicBlock *Cont = createBasicBlock("cont");
  4121. llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
  4122. Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
  4123. EmitBlock(TypeCheck);
  4124. llvm::Value *CalleeRTTIPtr =
  4125. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
  4126. llvm::Value *CalleeRTTIEncoded =
  4127. Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
  4128. llvm::Value *CalleeRTTI =
  4129. DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
  4130. llvm::Value *CalleeRTTIMatch =
  4131. Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
  4132. llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
  4133. EmitCheckTypeDescriptor(CalleeType)};
  4134. EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
  4135. SanitizerHandler::FunctionTypeMismatch, StaticData,
  4136. {CalleePtr, CalleeRTTI, FTRTTIConst});
  4137. Builder.CreateBr(Cont);
  4138. EmitBlock(Cont);
  4139. }
  4140. }
  4141. const auto *FnType = cast<FunctionType>(PointeeType);
  4142. // If we are checking indirect calls and this call is indirect, check that the
  4143. // function pointer is a member of the bit set for the function type.
  4144. if (SanOpts.has(SanitizerKind::CFIICall) &&
  4145. (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
  4146. SanitizerScope SanScope(this);
  4147. EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
  4148. llvm::Metadata *MD;
  4149. if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
  4150. MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
  4151. else
  4152. MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
  4153. llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
  4154. llvm::Value *CalleePtr = Callee.getFunctionPointer();
  4155. llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
  4156. llvm::Value *TypeTest = Builder.CreateCall(
  4157. CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
  4158. auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
  4159. llvm::Constant *StaticData[] = {
  4160. llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
  4161. EmitCheckSourceLocation(E->getBeginLoc()),
  4162. EmitCheckTypeDescriptor(QualType(FnType, 0)),
  4163. };
  4164. if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
  4165. EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
  4166. CastedCallee, StaticData);
  4167. } else {
  4168. EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
  4169. SanitizerHandler::CFICheckFail, StaticData,
  4170. {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
  4171. }
  4172. }
  4173. CallArgList Args;
  4174. if (Chain)
  4175. Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
  4176. CGM.getContext().VoidPtrTy);
  4177. // C++17 requires that we evaluate arguments to a call using assignment syntax
  4178. // right-to-left, and that we evaluate arguments to certain other operators
  4179. // left-to-right. Note that we allow this to override the order dictated by
  4180. // the calling convention on the MS ABI, which means that parameter
  4181. // destruction order is not necessarily reverse construction order.
  4182. // FIXME: Revisit this based on C++ committee response to unimplementability.
  4183. EvaluationOrder Order = EvaluationOrder::Default;
  4184. if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
  4185. if (OCE->isAssignmentOp())
  4186. Order = EvaluationOrder::ForceRightToLeft;
  4187. else {
  4188. switch (OCE->getOperator()) {
  4189. case OO_LessLess:
  4190. case OO_GreaterGreater:
  4191. case OO_AmpAmp:
  4192. case OO_PipePipe:
  4193. case OO_Comma:
  4194. case OO_ArrowStar:
  4195. Order = EvaluationOrder::ForceLeftToRight;
  4196. break;
  4197. default:
  4198. break;
  4199. }
  4200. }
  4201. }
  4202. EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
  4203. E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
  4204. const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
  4205. Args, FnType, /*isChainCall=*/Chain);
  4206. // C99 6.5.2.2p6:
  4207. // If the expression that denotes the called function has a type
  4208. // that does not include a prototype, [the default argument
  4209. // promotions are performed]. If the number of arguments does not
  4210. // equal the number of parameters, the behavior is undefined. If
  4211. // the function is defined with a type that includes a prototype,
  4212. // and either the prototype ends with an ellipsis (, ...) or the
  4213. // types of the arguments after promotion are not compatible with
  4214. // the types of the parameters, the behavior is undefined. If the
  4215. // function is defined with a type that does not include a
  4216. // prototype, and the types of the arguments after promotion are
  4217. // not compatible with those of the parameters after promotion,
  4218. // the behavior is undefined [except in some trivial cases].
  4219. // That is, in the general case, we should assume that a call
  4220. // through an unprototyped function type works like a *non-variadic*
  4221. // call. The way we make this work is to cast to the exact type
  4222. // of the promoted arguments.
  4223. //
  4224. // Chain calls use this same code path to add the invisible chain parameter
  4225. // to the function type.
  4226. if (isa<FunctionNoProtoType>(FnType) || Chain) {
  4227. llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
  4228. CalleeTy = CalleeTy->getPointerTo();
  4229. llvm::Value *CalleePtr = Callee.getFunctionPointer();
  4230. CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
  4231. Callee.setFunctionPointer(CalleePtr);
  4232. }
  4233. llvm::CallBase *CallOrInvoke = nullptr;
  4234. RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke,
  4235. E->getExprLoc());
  4236. // Generate function declaration DISuprogram in order to be used
  4237. // in debug info about call sites.
  4238. if (CGDebugInfo *DI = getDebugInfo()) {
  4239. if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  4240. DI->EmitFuncDeclForCallSite(CallOrInvoke, QualType(FnType, 0),
  4241. CalleeDecl);
  4242. }
  4243. return Call;
  4244. }
  4245. LValue CodeGenFunction::
  4246. EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
  4247. Address BaseAddr = Address::invalid();
  4248. if (E->getOpcode() == BO_PtrMemI) {
  4249. BaseAddr = EmitPointerWithAlignment(E->getLHS());
  4250. } else {
  4251. BaseAddr = EmitLValue(E->getLHS()).getAddress();
  4252. }
  4253. llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
  4254. const MemberPointerType *MPT
  4255. = E->getRHS()->getType()->getAs<MemberPointerType>();
  4256. LValueBaseInfo BaseInfo;
  4257. TBAAAccessInfo TBAAInfo;
  4258. Address MemberAddr =
  4259. EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
  4260. &TBAAInfo);
  4261. return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
  4262. }
  4263. /// Given the address of a temporary variable, produce an r-value of
  4264. /// its type.
  4265. RValue CodeGenFunction::convertTempToRValue(Address addr,
  4266. QualType type,
  4267. SourceLocation loc) {
  4268. LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
  4269. switch (getEvaluationKind(type)) {
  4270. case TEK_Complex:
  4271. return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
  4272. case TEK_Aggregate:
  4273. return lvalue.asAggregateRValue();
  4274. case TEK_Scalar:
  4275. return RValue::get(EmitLoadOfScalar(lvalue, loc));
  4276. }
  4277. llvm_unreachable("bad evaluation kind");
  4278. }
  4279. void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
  4280. assert(Val->getType()->isFPOrFPVectorTy());
  4281. if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
  4282. return;
  4283. llvm::MDBuilder MDHelper(getLLVMContext());
  4284. llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
  4285. cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
  4286. }
  4287. namespace {
  4288. struct LValueOrRValue {
  4289. LValue LV;
  4290. RValue RV;
  4291. };
  4292. }
  4293. static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
  4294. const PseudoObjectExpr *E,
  4295. bool forLValue,
  4296. AggValueSlot slot) {
  4297. SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
  4298. // Find the result expression, if any.
  4299. const Expr *resultExpr = E->getResultExpr();
  4300. LValueOrRValue result;
  4301. for (PseudoObjectExpr::const_semantics_iterator
  4302. i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
  4303. const Expr *semantic = *i;
  4304. // If this semantic expression is an opaque value, bind it
  4305. // to the result of its source expression.
  4306. if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
  4307. // Skip unique OVEs.
  4308. if (ov->isUnique()) {
  4309. assert(ov != resultExpr &&
  4310. "A unique OVE cannot be used as the result expression");
  4311. continue;
  4312. }
  4313. // If this is the result expression, we may need to evaluate
  4314. // directly into the slot.
  4315. typedef CodeGenFunction::OpaqueValueMappingData OVMA;
  4316. OVMA opaqueData;
  4317. if (ov == resultExpr && ov->isRValue() && !forLValue &&
  4318. CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
  4319. CGF.EmitAggExpr(ov->getSourceExpr(), slot);
  4320. LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
  4321. AlignmentSource::Decl);
  4322. opaqueData = OVMA::bind(CGF, ov, LV);
  4323. result.RV = slot.asRValue();
  4324. // Otherwise, emit as normal.
  4325. } else {
  4326. opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
  4327. // If this is the result, also evaluate the result now.
  4328. if (ov == resultExpr) {
  4329. if (forLValue)
  4330. result.LV = CGF.EmitLValue(ov);
  4331. else
  4332. result.RV = CGF.EmitAnyExpr(ov, slot);
  4333. }
  4334. }
  4335. opaques.push_back(opaqueData);
  4336. // Otherwise, if the expression is the result, evaluate it
  4337. // and remember the result.
  4338. } else if (semantic == resultExpr) {
  4339. if (forLValue)
  4340. result.LV = CGF.EmitLValue(semantic);
  4341. else
  4342. result.RV = CGF.EmitAnyExpr(semantic, slot);
  4343. // Otherwise, evaluate the expression in an ignored context.
  4344. } else {
  4345. CGF.EmitIgnoredExpr(semantic);
  4346. }
  4347. }
  4348. // Unbind all the opaques now.
  4349. for (unsigned i = 0, e = opaques.size(); i != e; ++i)
  4350. opaques[i].unbind(CGF);
  4351. return result;
  4352. }
  4353. RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
  4354. AggValueSlot slot) {
  4355. return emitPseudoObjectExpr(*this, E, false, slot).RV;
  4356. }
  4357. LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
  4358. return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
  4359. }