CGExprScalar.cpp 185 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766
  1. //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
  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 with scalar LLVM types as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGCXXABI.h"
  13. #include "CGCleanup.h"
  14. #include "CGDebugInfo.h"
  15. #include "CGObjCRuntime.h"
  16. #include "CodeGenFunction.h"
  17. #include "CodeGenModule.h"
  18. #include "ConstantEmitter.h"
  19. #include "TargetInfo.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/RecordLayout.h"
  24. #include "clang/AST/StmtVisitor.h"
  25. #include "clang/Basic/CodeGenOptions.h"
  26. #include "clang/Basic/FixedPoint.h"
  27. #include "clang/Basic/TargetInfo.h"
  28. #include "llvm/ADT/Optional.h"
  29. #include "llvm/IR/CFG.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/Function.h"
  33. #include "llvm/IR/GetElementPtrTypeIterator.h"
  34. #include "llvm/IR/GlobalVariable.h"
  35. #include "llvm/IR/Intrinsics.h"
  36. #include "llvm/IR/Module.h"
  37. #include <cstdarg>
  38. using namespace clang;
  39. using namespace CodeGen;
  40. using llvm::Value;
  41. //===----------------------------------------------------------------------===//
  42. // Scalar Expression Emitter
  43. //===----------------------------------------------------------------------===//
  44. namespace {
  45. /// Determine whether the given binary operation may overflow.
  46. /// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
  47. /// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
  48. /// the returned overflow check is precise. The returned value is 'true' for
  49. /// all other opcodes, to be conservative.
  50. bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
  51. BinaryOperator::Opcode Opcode, bool Signed,
  52. llvm::APInt &Result) {
  53. // Assume overflow is possible, unless we can prove otherwise.
  54. bool Overflow = true;
  55. const auto &LHSAP = LHS->getValue();
  56. const auto &RHSAP = RHS->getValue();
  57. if (Opcode == BO_Add) {
  58. if (Signed)
  59. Result = LHSAP.sadd_ov(RHSAP, Overflow);
  60. else
  61. Result = LHSAP.uadd_ov(RHSAP, Overflow);
  62. } else if (Opcode == BO_Sub) {
  63. if (Signed)
  64. Result = LHSAP.ssub_ov(RHSAP, Overflow);
  65. else
  66. Result = LHSAP.usub_ov(RHSAP, Overflow);
  67. } else if (Opcode == BO_Mul) {
  68. if (Signed)
  69. Result = LHSAP.smul_ov(RHSAP, Overflow);
  70. else
  71. Result = LHSAP.umul_ov(RHSAP, Overflow);
  72. } else if (Opcode == BO_Div || Opcode == BO_Rem) {
  73. if (Signed && !RHS->isZero())
  74. Result = LHSAP.sdiv_ov(RHSAP, Overflow);
  75. else
  76. return false;
  77. }
  78. return Overflow;
  79. }
  80. struct BinOpInfo {
  81. Value *LHS;
  82. Value *RHS;
  83. QualType Ty; // Computation Type.
  84. BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
  85. FPOptions FPFeatures;
  86. const Expr *E; // Entire expr, for error unsupported. May not be binop.
  87. /// Check if the binop can result in integer overflow.
  88. bool mayHaveIntegerOverflow() const {
  89. // Without constant input, we can't rule out overflow.
  90. auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
  91. auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
  92. if (!LHSCI || !RHSCI)
  93. return true;
  94. llvm::APInt Result;
  95. return ::mayHaveIntegerOverflow(
  96. LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
  97. }
  98. /// Check if the binop computes a division or a remainder.
  99. bool isDivremOp() const {
  100. return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
  101. Opcode == BO_RemAssign;
  102. }
  103. /// Check if the binop can result in an integer division by zero.
  104. bool mayHaveIntegerDivisionByZero() const {
  105. if (isDivremOp())
  106. if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
  107. return CI->isZero();
  108. return true;
  109. }
  110. /// Check if the binop can result in a float division by zero.
  111. bool mayHaveFloatDivisionByZero() const {
  112. if (isDivremOp())
  113. if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
  114. return CFP->isZero();
  115. return true;
  116. }
  117. /// Check if either operand is a fixed point type or integer type, with at
  118. /// least one being a fixed point type. In any case, this
  119. /// operation did not follow usual arithmetic conversion and both operands may
  120. /// not be the same.
  121. bool isFixedPointBinOp() const {
  122. // We cannot simply check the result type since comparison operations return
  123. // an int.
  124. if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
  125. QualType LHSType = BinOp->getLHS()->getType();
  126. QualType RHSType = BinOp->getRHS()->getType();
  127. return LHSType->isFixedPointType() || RHSType->isFixedPointType();
  128. }
  129. return false;
  130. }
  131. };
  132. static bool MustVisitNullValue(const Expr *E) {
  133. // If a null pointer expression's type is the C++0x nullptr_t, then
  134. // it's not necessarily a simple constant and it must be evaluated
  135. // for its potential side effects.
  136. return E->getType()->isNullPtrType();
  137. }
  138. /// If \p E is a widened promoted integer, get its base (unpromoted) type.
  139. static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
  140. const Expr *E) {
  141. const Expr *Base = E->IgnoreImpCasts();
  142. if (E == Base)
  143. return llvm::None;
  144. QualType BaseTy = Base->getType();
  145. if (!BaseTy->isPromotableIntegerType() ||
  146. Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
  147. return llvm::None;
  148. return BaseTy;
  149. }
  150. /// Check if \p E is a widened promoted integer.
  151. static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
  152. return getUnwidenedIntegerType(Ctx, E).hasValue();
  153. }
  154. /// Check if we can skip the overflow check for \p Op.
  155. static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
  156. assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
  157. "Expected a unary or binary operator");
  158. // If the binop has constant inputs and we can prove there is no overflow,
  159. // we can elide the overflow check.
  160. if (!Op.mayHaveIntegerOverflow())
  161. return true;
  162. // If a unary op has a widened operand, the op cannot overflow.
  163. if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
  164. return !UO->canOverflow();
  165. // We usually don't need overflow checks for binops with widened operands.
  166. // Multiplication with promoted unsigned operands is a special case.
  167. const auto *BO = cast<BinaryOperator>(Op.E);
  168. auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
  169. if (!OptionalLHSTy)
  170. return false;
  171. auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
  172. if (!OptionalRHSTy)
  173. return false;
  174. QualType LHSTy = *OptionalLHSTy;
  175. QualType RHSTy = *OptionalRHSTy;
  176. // This is the simple case: binops without unsigned multiplication, and with
  177. // widened operands. No overflow check is needed here.
  178. if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
  179. !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
  180. return true;
  181. // For unsigned multiplication the overflow check can be elided if either one
  182. // of the unpromoted types are less than half the size of the promoted type.
  183. unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
  184. return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
  185. (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
  186. }
  187. /// Update the FastMathFlags of LLVM IR from the FPOptions in LangOptions.
  188. static void updateFastMathFlags(llvm::FastMathFlags &FMF,
  189. FPOptions FPFeatures) {
  190. FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
  191. }
  192. /// Propagate fast-math flags from \p Op to the instruction in \p V.
  193. static Value *propagateFMFlags(Value *V, const BinOpInfo &Op) {
  194. if (auto *I = dyn_cast<llvm::Instruction>(V)) {
  195. llvm::FastMathFlags FMF = I->getFastMathFlags();
  196. updateFastMathFlags(FMF, Op.FPFeatures);
  197. I->setFastMathFlags(FMF);
  198. }
  199. return V;
  200. }
  201. class ScalarExprEmitter
  202. : public StmtVisitor<ScalarExprEmitter, Value*> {
  203. CodeGenFunction &CGF;
  204. CGBuilderTy &Builder;
  205. bool IgnoreResultAssign;
  206. llvm::LLVMContext &VMContext;
  207. public:
  208. ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
  209. : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
  210. VMContext(cgf.getLLVMContext()) {
  211. }
  212. //===--------------------------------------------------------------------===//
  213. // Utilities
  214. //===--------------------------------------------------------------------===//
  215. bool TestAndClearIgnoreResultAssign() {
  216. bool I = IgnoreResultAssign;
  217. IgnoreResultAssign = false;
  218. return I;
  219. }
  220. llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
  221. LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
  222. LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
  223. return CGF.EmitCheckedLValue(E, TCK);
  224. }
  225. void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
  226. const BinOpInfo &Info);
  227. Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
  228. return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
  229. }
  230. void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
  231. const AlignValueAttr *AVAttr = nullptr;
  232. if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  233. const ValueDecl *VD = DRE->getDecl();
  234. if (VD->getType()->isReferenceType()) {
  235. if (const auto *TTy =
  236. dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
  237. AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
  238. } else {
  239. // Assumptions for function parameters are emitted at the start of the
  240. // function, so there is no need to repeat that here,
  241. // unless the alignment-assumption sanitizer is enabled,
  242. // then we prefer the assumption over alignment attribute
  243. // on IR function param.
  244. if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment))
  245. return;
  246. AVAttr = VD->getAttr<AlignValueAttr>();
  247. }
  248. }
  249. if (!AVAttr)
  250. if (const auto *TTy =
  251. dyn_cast<TypedefType>(E->getType()))
  252. AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
  253. if (!AVAttr)
  254. return;
  255. Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
  256. llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
  257. CGF.EmitAlignmentAssumption(V, E, AVAttr->getLocation(), AlignmentCI);
  258. }
  259. /// EmitLoadOfLValue - Given an expression with complex type that represents a
  260. /// value l-value, this method emits the address of the l-value, then loads
  261. /// and returns the result.
  262. Value *EmitLoadOfLValue(const Expr *E) {
  263. Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
  264. E->getExprLoc());
  265. EmitLValueAlignmentAssumption(E, V);
  266. return V;
  267. }
  268. /// EmitConversionToBool - Convert the specified expression value to a
  269. /// boolean (i1) truth value. This is equivalent to "Val != 0".
  270. Value *EmitConversionToBool(Value *Src, QualType DstTy);
  271. /// Emit a check that a conversion from a floating-point type does not
  272. /// overflow.
  273. void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
  274. Value *Src, QualType SrcType, QualType DstType,
  275. llvm::Type *DstTy, SourceLocation Loc);
  276. /// Known implicit conversion check kinds.
  277. /// Keep in sync with the enum of the same name in ubsan_handlers.h
  278. enum ImplicitConversionCheckKind : unsigned char {
  279. ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
  280. ICCK_UnsignedIntegerTruncation = 1,
  281. ICCK_SignedIntegerTruncation = 2,
  282. ICCK_IntegerSignChange = 3,
  283. ICCK_SignedIntegerTruncationOrSignChange = 4,
  284. };
  285. /// Emit a check that an [implicit] truncation of an integer does not
  286. /// discard any bits. It is not UB, so we use the value after truncation.
  287. void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
  288. QualType DstType, SourceLocation Loc);
  289. /// Emit a check that an [implicit] conversion of an integer does not change
  290. /// the sign of the value. It is not UB, so we use the value after conversion.
  291. /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
  292. void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
  293. QualType DstType, SourceLocation Loc);
  294. /// Emit a conversion from the specified type to the specified destination
  295. /// type, both of which are LLVM scalar types.
  296. struct ScalarConversionOpts {
  297. bool TreatBooleanAsSigned;
  298. bool EmitImplicitIntegerTruncationChecks;
  299. bool EmitImplicitIntegerSignChangeChecks;
  300. ScalarConversionOpts()
  301. : TreatBooleanAsSigned(false),
  302. EmitImplicitIntegerTruncationChecks(false),
  303. EmitImplicitIntegerSignChangeChecks(false) {}
  304. ScalarConversionOpts(clang::SanitizerSet SanOpts)
  305. : TreatBooleanAsSigned(false),
  306. EmitImplicitIntegerTruncationChecks(
  307. SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
  308. EmitImplicitIntegerSignChangeChecks(
  309. SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
  310. };
  311. Value *
  312. EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
  313. SourceLocation Loc,
  314. ScalarConversionOpts Opts = ScalarConversionOpts());
  315. /// Convert between either a fixed point and other fixed point or fixed point
  316. /// and an integer.
  317. Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
  318. SourceLocation Loc);
  319. Value *EmitFixedPointConversion(Value *Src, FixedPointSemantics &SrcFixedSema,
  320. FixedPointSemantics &DstFixedSema,
  321. SourceLocation Loc,
  322. bool DstIsInteger = false);
  323. /// Emit a conversion from the specified complex type to the specified
  324. /// destination type, where the destination type is an LLVM scalar type.
  325. Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
  326. QualType SrcTy, QualType DstTy,
  327. SourceLocation Loc);
  328. /// EmitNullValue - Emit a value that corresponds to null for the given type.
  329. Value *EmitNullValue(QualType Ty);
  330. /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
  331. Value *EmitFloatToBoolConversion(Value *V) {
  332. // Compare against 0.0 for fp scalars.
  333. llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
  334. return Builder.CreateFCmpUNE(V, Zero, "tobool");
  335. }
  336. /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
  337. Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
  338. Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
  339. return Builder.CreateICmpNE(V, Zero, "tobool");
  340. }
  341. Value *EmitIntToBoolConversion(Value *V) {
  342. // Because of the type rules of C, we often end up computing a
  343. // logical value, then zero extending it to int, then wanting it
  344. // as a logical value again. Optimize this common case.
  345. if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
  346. if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
  347. Value *Result = ZI->getOperand(0);
  348. // If there aren't any more uses, zap the instruction to save space.
  349. // Note that there can be more uses, for example if this
  350. // is the result of an assignment.
  351. if (ZI->use_empty())
  352. ZI->eraseFromParent();
  353. return Result;
  354. }
  355. }
  356. return Builder.CreateIsNotNull(V, "tobool");
  357. }
  358. //===--------------------------------------------------------------------===//
  359. // Visitor Methods
  360. //===--------------------------------------------------------------------===//
  361. Value *Visit(Expr *E) {
  362. ApplyDebugLocation DL(CGF, E);
  363. return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
  364. }
  365. Value *VisitStmt(Stmt *S) {
  366. S->dump(CGF.getContext().getSourceManager());
  367. llvm_unreachable("Stmt can't have complex result type!");
  368. }
  369. Value *VisitExpr(Expr *S);
  370. Value *VisitConstantExpr(ConstantExpr *E) {
  371. return Visit(E->getSubExpr());
  372. }
  373. Value *VisitParenExpr(ParenExpr *PE) {
  374. return Visit(PE->getSubExpr());
  375. }
  376. Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
  377. return Visit(E->getReplacement());
  378. }
  379. Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
  380. return Visit(GE->getResultExpr());
  381. }
  382. Value *VisitCoawaitExpr(CoawaitExpr *S) {
  383. return CGF.EmitCoawaitExpr(*S).getScalarVal();
  384. }
  385. Value *VisitCoyieldExpr(CoyieldExpr *S) {
  386. return CGF.EmitCoyieldExpr(*S).getScalarVal();
  387. }
  388. Value *VisitUnaryCoawait(const UnaryOperator *E) {
  389. return Visit(E->getSubExpr());
  390. }
  391. // Leaves.
  392. Value *VisitIntegerLiteral(const IntegerLiteral *E) {
  393. return Builder.getInt(E->getValue());
  394. }
  395. Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
  396. return Builder.getInt(E->getValue());
  397. }
  398. Value *VisitFloatingLiteral(const FloatingLiteral *E) {
  399. return llvm::ConstantFP::get(VMContext, E->getValue());
  400. }
  401. Value *VisitCharacterLiteral(const CharacterLiteral *E) {
  402. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  403. }
  404. Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  405. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  406. }
  407. Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  408. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  409. }
  410. Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  411. return EmitNullValue(E->getType());
  412. }
  413. Value *VisitGNUNullExpr(const GNUNullExpr *E) {
  414. return EmitNullValue(E->getType());
  415. }
  416. Value *VisitOffsetOfExpr(OffsetOfExpr *E);
  417. Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  418. Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
  419. llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
  420. return Builder.CreateBitCast(V, ConvertType(E->getType()));
  421. }
  422. Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
  423. return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
  424. }
  425. Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
  426. return CGF.EmitPseudoObjectRValue(E).getScalarVal();
  427. }
  428. Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
  429. if (E->isGLValue())
  430. return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
  431. E->getExprLoc());
  432. // Otherwise, assume the mapping is the scalar directly.
  433. return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal();
  434. }
  435. // l-values.
  436. Value *VisitDeclRefExpr(DeclRefExpr *E) {
  437. if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
  438. return CGF.emitScalarConstant(Constant, E);
  439. return EmitLoadOfLValue(E);
  440. }
  441. Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
  442. return CGF.EmitObjCSelectorExpr(E);
  443. }
  444. Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
  445. return CGF.EmitObjCProtocolExpr(E);
  446. }
  447. Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
  448. return EmitLoadOfLValue(E);
  449. }
  450. Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
  451. if (E->getMethodDecl() &&
  452. E->getMethodDecl()->getReturnType()->isReferenceType())
  453. return EmitLoadOfLValue(E);
  454. return CGF.EmitObjCMessageExpr(E).getScalarVal();
  455. }
  456. Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
  457. LValue LV = CGF.EmitObjCIsaExpr(E);
  458. Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
  459. return V;
  460. }
  461. Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
  462. VersionTuple Version = E->getVersion();
  463. // If we're checking for a platform older than our minimum deployment
  464. // target, we can fold the check away.
  465. if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
  466. return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
  467. Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
  468. llvm::Value *Args[] = {
  469. llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()),
  470. llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0),
  471. llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0),
  472. };
  473. return CGF.EmitBuiltinAvailable(Args);
  474. }
  475. Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
  476. Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
  477. Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
  478. Value *VisitMemberExpr(MemberExpr *E);
  479. Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
  480. Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
  481. return EmitLoadOfLValue(E);
  482. }
  483. Value *VisitInitListExpr(InitListExpr *E);
  484. Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
  485. assert(CGF.getArrayInitIndex() &&
  486. "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
  487. return CGF.getArrayInitIndex();
  488. }
  489. Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  490. return EmitNullValue(E->getType());
  491. }
  492. Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
  493. CGF.CGM.EmitExplicitCastExprType(E, &CGF);
  494. return VisitCastExpr(E);
  495. }
  496. Value *VisitCastExpr(CastExpr *E);
  497. Value *VisitCallExpr(const CallExpr *E) {
  498. if (E->getCallReturnType(CGF.getContext())->isReferenceType())
  499. return EmitLoadOfLValue(E);
  500. Value *V = CGF.EmitCallExpr(E).getScalarVal();
  501. EmitLValueAlignmentAssumption(E, V);
  502. return V;
  503. }
  504. Value *VisitStmtExpr(const StmtExpr *E);
  505. // Unary Operators.
  506. Value *VisitUnaryPostDec(const UnaryOperator *E) {
  507. LValue LV = EmitLValue(E->getSubExpr());
  508. return EmitScalarPrePostIncDec(E, LV, false, false);
  509. }
  510. Value *VisitUnaryPostInc(const UnaryOperator *E) {
  511. LValue LV = EmitLValue(E->getSubExpr());
  512. return EmitScalarPrePostIncDec(E, LV, true, false);
  513. }
  514. Value *VisitUnaryPreDec(const UnaryOperator *E) {
  515. LValue LV = EmitLValue(E->getSubExpr());
  516. return EmitScalarPrePostIncDec(E, LV, false, true);
  517. }
  518. Value *VisitUnaryPreInc(const UnaryOperator *E) {
  519. LValue LV = EmitLValue(E->getSubExpr());
  520. return EmitScalarPrePostIncDec(E, LV, true, true);
  521. }
  522. llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
  523. llvm::Value *InVal,
  524. bool IsInc);
  525. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  526. bool isInc, bool isPre);
  527. Value *VisitUnaryAddrOf(const UnaryOperator *E) {
  528. if (isa<MemberPointerType>(E->getType())) // never sugared
  529. return CGF.CGM.getMemberPointerConstant(E);
  530. return EmitLValue(E->getSubExpr()).getPointer();
  531. }
  532. Value *VisitUnaryDeref(const UnaryOperator *E) {
  533. if (E->getType()->isVoidType())
  534. return Visit(E->getSubExpr()); // the actual value should be unused
  535. return EmitLoadOfLValue(E);
  536. }
  537. Value *VisitUnaryPlus(const UnaryOperator *E) {
  538. // This differs from gcc, though, most likely due to a bug in gcc.
  539. TestAndClearIgnoreResultAssign();
  540. return Visit(E->getSubExpr());
  541. }
  542. Value *VisitUnaryMinus (const UnaryOperator *E);
  543. Value *VisitUnaryNot (const UnaryOperator *E);
  544. Value *VisitUnaryLNot (const UnaryOperator *E);
  545. Value *VisitUnaryReal (const UnaryOperator *E);
  546. Value *VisitUnaryImag (const UnaryOperator *E);
  547. Value *VisitUnaryExtension(const UnaryOperator *E) {
  548. return Visit(E->getSubExpr());
  549. }
  550. // C++
  551. Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
  552. return EmitLoadOfLValue(E);
  553. }
  554. Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
  555. auto &Ctx = CGF.getContext();
  556. APValue Evaluated =
  557. SLE->EvaluateInContext(Ctx, CGF.CurSourceLocExprScope.getDefaultExpr());
  558. return ConstantEmitter(CGF.CGM, &CGF)
  559. .emitAbstract(SLE->getLocation(), Evaluated, SLE->getType());
  560. }
  561. Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
  562. CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
  563. return Visit(DAE->getExpr());
  564. }
  565. Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
  566. CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
  567. return Visit(DIE->getExpr());
  568. }
  569. Value *VisitCXXThisExpr(CXXThisExpr *TE) {
  570. return CGF.LoadCXXThis();
  571. }
  572. Value *VisitExprWithCleanups(ExprWithCleanups *E);
  573. Value *VisitCXXNewExpr(const CXXNewExpr *E) {
  574. return CGF.EmitCXXNewExpr(E);
  575. }
  576. Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
  577. CGF.EmitCXXDeleteExpr(E);
  578. return nullptr;
  579. }
  580. Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
  581. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  582. }
  583. Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
  584. return Builder.getInt1(E->isSatisfied());
  585. }
  586. Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  587. return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
  588. }
  589. Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  590. return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
  591. }
  592. Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
  593. // C++ [expr.pseudo]p1:
  594. // The result shall only be used as the operand for the function call
  595. // operator (), and the result of such a call has type void. The only
  596. // effect is the evaluation of the postfix-expression before the dot or
  597. // arrow.
  598. CGF.EmitScalarExpr(E->getBase());
  599. return nullptr;
  600. }
  601. Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  602. return EmitNullValue(E->getType());
  603. }
  604. Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
  605. CGF.EmitCXXThrowExpr(E);
  606. return nullptr;
  607. }
  608. Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  609. return Builder.getInt1(E->getValue());
  610. }
  611. // Binary Operators.
  612. Value *EmitMul(const BinOpInfo &Ops) {
  613. if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
  614. switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
  615. case LangOptions::SOB_Defined:
  616. return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
  617. case LangOptions::SOB_Undefined:
  618. if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
  619. return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
  620. LLVM_FALLTHROUGH;
  621. case LangOptions::SOB_Trapping:
  622. if (CanElideOverflowCheck(CGF.getContext(), Ops))
  623. return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
  624. return EmitOverflowCheckedBinOp(Ops);
  625. }
  626. }
  627. if (Ops.Ty->isUnsignedIntegerType() &&
  628. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
  629. !CanElideOverflowCheck(CGF.getContext(), Ops))
  630. return EmitOverflowCheckedBinOp(Ops);
  631. if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
  632. Value *V = Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
  633. return propagateFMFlags(V, Ops);
  634. }
  635. return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
  636. }
  637. /// Create a binary op that checks for overflow.
  638. /// Currently only supports +, - and *.
  639. Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
  640. // Check for undefined division and modulus behaviors.
  641. void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
  642. llvm::Value *Zero,bool isDiv);
  643. // Common helper for getting how wide LHS of shift is.
  644. static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
  645. Value *EmitDiv(const BinOpInfo &Ops);
  646. Value *EmitRem(const BinOpInfo &Ops);
  647. Value *EmitAdd(const BinOpInfo &Ops);
  648. Value *EmitSub(const BinOpInfo &Ops);
  649. Value *EmitShl(const BinOpInfo &Ops);
  650. Value *EmitShr(const BinOpInfo &Ops);
  651. Value *EmitAnd(const BinOpInfo &Ops) {
  652. return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
  653. }
  654. Value *EmitXor(const BinOpInfo &Ops) {
  655. return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
  656. }
  657. Value *EmitOr (const BinOpInfo &Ops) {
  658. return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
  659. }
  660. // Helper functions for fixed point binary operations.
  661. Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
  662. BinOpInfo EmitBinOps(const BinaryOperator *E);
  663. LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
  664. Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
  665. Value *&Result);
  666. Value *EmitCompoundAssign(const CompoundAssignOperator *E,
  667. Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
  668. // Binary operators and binary compound assignment operators.
  669. #define HANDLEBINOP(OP) \
  670. Value *VisitBin ## OP(const BinaryOperator *E) { \
  671. return Emit ## OP(EmitBinOps(E)); \
  672. } \
  673. Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
  674. return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
  675. }
  676. HANDLEBINOP(Mul)
  677. HANDLEBINOP(Div)
  678. HANDLEBINOP(Rem)
  679. HANDLEBINOP(Add)
  680. HANDLEBINOP(Sub)
  681. HANDLEBINOP(Shl)
  682. HANDLEBINOP(Shr)
  683. HANDLEBINOP(And)
  684. HANDLEBINOP(Xor)
  685. HANDLEBINOP(Or)
  686. #undef HANDLEBINOP
  687. // Comparisons.
  688. Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
  689. llvm::CmpInst::Predicate SICmpOpc,
  690. llvm::CmpInst::Predicate FCmpOpc);
  691. #define VISITCOMP(CODE, UI, SI, FP) \
  692. Value *VisitBin##CODE(const BinaryOperator *E) { \
  693. return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
  694. llvm::FCmpInst::FP); }
  695. VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
  696. VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
  697. VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
  698. VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
  699. VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
  700. VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
  701. #undef VISITCOMP
  702. Value *VisitBinAssign (const BinaryOperator *E);
  703. Value *VisitBinLAnd (const BinaryOperator *E);
  704. Value *VisitBinLOr (const BinaryOperator *E);
  705. Value *VisitBinComma (const BinaryOperator *E);
  706. Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
  707. Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
  708. Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
  709. return Visit(E->getSemanticForm());
  710. }
  711. // Other Operators.
  712. Value *VisitBlockExpr(const BlockExpr *BE);
  713. Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
  714. Value *VisitChooseExpr(ChooseExpr *CE);
  715. Value *VisitVAArgExpr(VAArgExpr *VE);
  716. Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
  717. return CGF.EmitObjCStringLiteral(E);
  718. }
  719. Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
  720. return CGF.EmitObjCBoxedExpr(E);
  721. }
  722. Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
  723. return CGF.EmitObjCArrayLiteral(E);
  724. }
  725. Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
  726. return CGF.EmitObjCDictionaryLiteral(E);
  727. }
  728. Value *VisitAsTypeExpr(AsTypeExpr *CE);
  729. Value *VisitAtomicExpr(AtomicExpr *AE);
  730. };
  731. } // end anonymous namespace.
  732. //===----------------------------------------------------------------------===//
  733. // Utilities
  734. //===----------------------------------------------------------------------===//
  735. /// EmitConversionToBool - Convert the specified expression value to a
  736. /// boolean (i1) truth value. This is equivalent to "Val != 0".
  737. Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
  738. assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
  739. if (SrcType->isRealFloatingType())
  740. return EmitFloatToBoolConversion(Src);
  741. if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
  742. return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
  743. assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
  744. "Unknown scalar type to convert");
  745. if (isa<llvm::IntegerType>(Src->getType()))
  746. return EmitIntToBoolConversion(Src);
  747. assert(isa<llvm::PointerType>(Src->getType()));
  748. return EmitPointerToBoolConversion(Src, SrcType);
  749. }
  750. void ScalarExprEmitter::EmitFloatConversionCheck(
  751. Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
  752. QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
  753. assert(SrcType->isFloatingType() && "not a conversion from floating point");
  754. if (!isa<llvm::IntegerType>(DstTy))
  755. return;
  756. CodeGenFunction::SanitizerScope SanScope(&CGF);
  757. using llvm::APFloat;
  758. using llvm::APSInt;
  759. llvm::Value *Check = nullptr;
  760. const llvm::fltSemantics &SrcSema =
  761. CGF.getContext().getFloatTypeSemantics(OrigSrcType);
  762. // Floating-point to integer. This has undefined behavior if the source is
  763. // +-Inf, NaN, or doesn't fit into the destination type (after truncation
  764. // to an integer).
  765. unsigned Width = CGF.getContext().getIntWidth(DstType);
  766. bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
  767. APSInt Min = APSInt::getMinValue(Width, Unsigned);
  768. APFloat MinSrc(SrcSema, APFloat::uninitialized);
  769. if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
  770. APFloat::opOverflow)
  771. // Don't need an overflow check for lower bound. Just check for
  772. // -Inf/NaN.
  773. MinSrc = APFloat::getInf(SrcSema, true);
  774. else
  775. // Find the largest value which is too small to represent (before
  776. // truncation toward zero).
  777. MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
  778. APSInt Max = APSInt::getMaxValue(Width, Unsigned);
  779. APFloat MaxSrc(SrcSema, APFloat::uninitialized);
  780. if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
  781. APFloat::opOverflow)
  782. // Don't need an overflow check for upper bound. Just check for
  783. // +Inf/NaN.
  784. MaxSrc = APFloat::getInf(SrcSema, false);
  785. else
  786. // Find the smallest value which is too large to represent (before
  787. // truncation toward zero).
  788. MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
  789. // If we're converting from __half, convert the range to float to match
  790. // the type of src.
  791. if (OrigSrcType->isHalfType()) {
  792. const llvm::fltSemantics &Sema =
  793. CGF.getContext().getFloatTypeSemantics(SrcType);
  794. bool IsInexact;
  795. MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
  796. MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
  797. }
  798. llvm::Value *GE =
  799. Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
  800. llvm::Value *LE =
  801. Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
  802. Check = Builder.CreateAnd(GE, LE);
  803. llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
  804. CGF.EmitCheckTypeDescriptor(OrigSrcType),
  805. CGF.EmitCheckTypeDescriptor(DstType)};
  806. CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
  807. SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
  808. }
  809. // Should be called within CodeGenFunction::SanitizerScope RAII scope.
  810. // Returns 'i1 false' when the truncation Src -> Dst was lossy.
  811. static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
  812. std::pair<llvm::Value *, SanitizerMask>>
  813. EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
  814. QualType DstType, CGBuilderTy &Builder) {
  815. llvm::Type *SrcTy = Src->getType();
  816. llvm::Type *DstTy = Dst->getType();
  817. (void)DstTy; // Only used in assert()
  818. // This should be truncation of integral types.
  819. assert(Src != Dst);
  820. assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
  821. assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
  822. "non-integer llvm type");
  823. bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
  824. bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
  825. // If both (src and dst) types are unsigned, then it's an unsigned truncation.
  826. // Else, it is a signed truncation.
  827. ScalarExprEmitter::ImplicitConversionCheckKind Kind;
  828. SanitizerMask Mask;
  829. if (!SrcSigned && !DstSigned) {
  830. Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
  831. Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation;
  832. } else {
  833. Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
  834. Mask = SanitizerKind::ImplicitSignedIntegerTruncation;
  835. }
  836. llvm::Value *Check = nullptr;
  837. // 1. Extend the truncated value back to the same width as the Src.
  838. Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext");
  839. // 2. Equality-compare with the original source value
  840. Check = Builder.CreateICmpEQ(Check, Src, "truncheck");
  841. // If the comparison result is 'i1 false', then the truncation was lossy.
  842. return std::make_pair(Kind, std::make_pair(Check, Mask));
  843. }
  844. void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
  845. Value *Dst, QualType DstType,
  846. SourceLocation Loc) {
  847. if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation))
  848. return;
  849. // We only care about int->int conversions here.
  850. // We ignore conversions to/from pointer and/or bool.
  851. if (!(SrcType->isIntegerType() && DstType->isIntegerType()))
  852. return;
  853. unsigned SrcBits = Src->getType()->getScalarSizeInBits();
  854. unsigned DstBits = Dst->getType()->getScalarSizeInBits();
  855. // This must be truncation. Else we do not care.
  856. if (SrcBits <= DstBits)
  857. return;
  858. assert(!DstType->isBooleanType() && "we should not get here with booleans.");
  859. // If the integer sign change sanitizer is enabled,
  860. // and we are truncating from larger unsigned type to smaller signed type,
  861. // let that next sanitizer deal with it.
  862. bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
  863. bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
  864. if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) &&
  865. (!SrcSigned && DstSigned))
  866. return;
  867. CodeGenFunction::SanitizerScope SanScope(&CGF);
  868. std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
  869. std::pair<llvm::Value *, SanitizerMask>>
  870. Check =
  871. EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
  872. // If the comparison result is 'i1 false', then the truncation was lossy.
  873. // Do we care about this type of truncation?
  874. if (!CGF.SanOpts.has(Check.second.second))
  875. return;
  876. llvm::Constant *StaticArgs[] = {
  877. CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
  878. CGF.EmitCheckTypeDescriptor(DstType),
  879. llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)};
  880. CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
  881. {Src, Dst});
  882. }
  883. // Should be called within CodeGenFunction::SanitizerScope RAII scope.
  884. // Returns 'i1 false' when the conversion Src -> Dst changed the sign.
  885. static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
  886. std::pair<llvm::Value *, SanitizerMask>>
  887. EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
  888. QualType DstType, CGBuilderTy &Builder) {
  889. llvm::Type *SrcTy = Src->getType();
  890. llvm::Type *DstTy = Dst->getType();
  891. assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
  892. "non-integer llvm type");
  893. bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
  894. bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
  895. (void)SrcSigned; // Only used in assert()
  896. (void)DstSigned; // Only used in assert()
  897. unsigned SrcBits = SrcTy->getScalarSizeInBits();
  898. unsigned DstBits = DstTy->getScalarSizeInBits();
  899. (void)SrcBits; // Only used in assert()
  900. (void)DstBits; // Only used in assert()
  901. assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
  902. "either the widths should be different, or the signednesses.");
  903. // NOTE: zero value is considered to be non-negative.
  904. auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType,
  905. const char *Name) -> Value * {
  906. // Is this value a signed type?
  907. bool VSigned = VType->isSignedIntegerOrEnumerationType();
  908. llvm::Type *VTy = V->getType();
  909. if (!VSigned) {
  910. // If the value is unsigned, then it is never negative.
  911. // FIXME: can we encounter non-scalar VTy here?
  912. return llvm::ConstantInt::getFalse(VTy->getContext());
  913. }
  914. // Get the zero of the same type with which we will be comparing.
  915. llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0);
  916. // %V.isnegative = icmp slt %V, 0
  917. // I.e is %V *strictly* less than zero, does it have negative value?
  918. return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero,
  919. llvm::Twine(Name) + "." + V->getName() +
  920. ".negativitycheck");
  921. };
  922. // 1. Was the old Value negative?
  923. llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src");
  924. // 2. Is the new Value negative?
  925. llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst");
  926. // 3. Now, was the 'negativity status' preserved during the conversion?
  927. // NOTE: conversion from negative to zero is considered to change the sign.
  928. // (We want to get 'false' when the conversion changed the sign)
  929. // So we should just equality-compare the negativity statuses.
  930. llvm::Value *Check = nullptr;
  931. Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck");
  932. // If the comparison result is 'false', then the conversion changed the sign.
  933. return std::make_pair(
  934. ScalarExprEmitter::ICCK_IntegerSignChange,
  935. std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange));
  936. }
  937. void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
  938. Value *Dst, QualType DstType,
  939. SourceLocation Loc) {
  940. if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange))
  941. return;
  942. llvm::Type *SrcTy = Src->getType();
  943. llvm::Type *DstTy = Dst->getType();
  944. // We only care about int->int conversions here.
  945. // We ignore conversions to/from pointer and/or bool.
  946. if (!(SrcType->isIntegerType() && DstType->isIntegerType()))
  947. return;
  948. bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
  949. bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
  950. unsigned SrcBits = SrcTy->getScalarSizeInBits();
  951. unsigned DstBits = DstTy->getScalarSizeInBits();
  952. // Now, we do not need to emit the check in *all* of the cases.
  953. // We can avoid emitting it in some obvious cases where it would have been
  954. // dropped by the opt passes (instcombine) always anyways.
  955. // If it's a cast between effectively the same type, no check.
  956. // NOTE: this is *not* equivalent to checking the canonical types.
  957. if (SrcSigned == DstSigned && SrcBits == DstBits)
  958. return;
  959. // At least one of the values needs to have signed type.
  960. // If both are unsigned, then obviously, neither of them can be negative.
  961. if (!SrcSigned && !DstSigned)
  962. return;
  963. // If the conversion is to *larger* *signed* type, then no check is needed.
  964. // Because either sign-extension happens (so the sign will remain),
  965. // or zero-extension will happen (the sign bit will be zero.)
  966. if ((DstBits > SrcBits) && DstSigned)
  967. return;
  968. if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
  969. (SrcBits > DstBits) && SrcSigned) {
  970. // If the signed integer truncation sanitizer is enabled,
  971. // and this is a truncation from signed type, then no check is needed.
  972. // Because here sign change check is interchangeable with truncation check.
  973. return;
  974. }
  975. // That's it. We can't rule out any more cases with the data we have.
  976. CodeGenFunction::SanitizerScope SanScope(&CGF);
  977. std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
  978. std::pair<llvm::Value *, SanitizerMask>>
  979. Check;
  980. // Each of these checks needs to return 'false' when an issue was detected.
  981. ImplicitConversionCheckKind CheckKind;
  982. llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
  983. // So we can 'and' all the checks together, and still get 'false',
  984. // if at least one of the checks detected an issue.
  985. Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
  986. CheckKind = Check.first;
  987. Checks.emplace_back(Check.second);
  988. if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
  989. (SrcBits > DstBits) && !SrcSigned && DstSigned) {
  990. // If the signed integer truncation sanitizer was enabled,
  991. // and we are truncating from larger unsigned type to smaller signed type,
  992. // let's handle the case we skipped in that check.
  993. Check =
  994. EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
  995. CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
  996. Checks.emplace_back(Check.second);
  997. // If the comparison result is 'i1 false', then the truncation was lossy.
  998. }
  999. llvm::Constant *StaticArgs[] = {
  1000. CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
  1001. CGF.EmitCheckTypeDescriptor(DstType),
  1002. llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)};
  1003. // EmitCheck() will 'and' all the checks together.
  1004. CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs,
  1005. {Src, Dst});
  1006. }
  1007. /// Emit a conversion from the specified type to the specified destination type,
  1008. /// both of which are LLVM scalar types.
  1009. Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
  1010. QualType DstType,
  1011. SourceLocation Loc,
  1012. ScalarConversionOpts Opts) {
  1013. // All conversions involving fixed point types should be handled by the
  1014. // EmitFixedPoint family functions. This is done to prevent bloating up this
  1015. // function more, and although fixed point numbers are represented by
  1016. // integers, we do not want to follow any logic that assumes they should be
  1017. // treated as integers.
  1018. // TODO(leonardchan): When necessary, add another if statement checking for
  1019. // conversions to fixed point types from other types.
  1020. if (SrcType->isFixedPointType()) {
  1021. if (DstType->isBooleanType())
  1022. // It is important that we check this before checking if the dest type is
  1023. // an integer because booleans are technically integer types.
  1024. // We do not need to check the padding bit on unsigned types if unsigned
  1025. // padding is enabled because overflow into this bit is undefined
  1026. // behavior.
  1027. return Builder.CreateIsNotNull(Src, "tobool");
  1028. if (DstType->isFixedPointType() || DstType->isIntegerType())
  1029. return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
  1030. llvm_unreachable(
  1031. "Unhandled scalar conversion from a fixed point type to another type.");
  1032. } else if (DstType->isFixedPointType()) {
  1033. if (SrcType->isIntegerType())
  1034. // This also includes converting booleans and enums to fixed point types.
  1035. return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
  1036. llvm_unreachable(
  1037. "Unhandled scalar conversion to a fixed point type from another type.");
  1038. }
  1039. QualType NoncanonicalSrcType = SrcType;
  1040. QualType NoncanonicalDstType = DstType;
  1041. SrcType = CGF.getContext().getCanonicalType(SrcType);
  1042. DstType = CGF.getContext().getCanonicalType(DstType);
  1043. if (SrcType == DstType) return Src;
  1044. if (DstType->isVoidType()) return nullptr;
  1045. llvm::Value *OrigSrc = Src;
  1046. QualType OrigSrcType = SrcType;
  1047. llvm::Type *SrcTy = Src->getType();
  1048. // Handle conversions to bool first, they are special: comparisons against 0.
  1049. if (DstType->isBooleanType())
  1050. return EmitConversionToBool(Src, SrcType);
  1051. llvm::Type *DstTy = ConvertType(DstType);
  1052. // Cast from half through float if half isn't a native type.
  1053. if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
  1054. // Cast to FP using the intrinsic if the half type itself isn't supported.
  1055. if (DstTy->isFloatingPointTy()) {
  1056. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
  1057. return Builder.CreateCall(
  1058. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
  1059. Src);
  1060. } else {
  1061. // Cast to other types through float, using either the intrinsic or FPExt,
  1062. // depending on whether the half type itself is supported
  1063. // (as opposed to operations on half, available with NativeHalfType).
  1064. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
  1065. Src = Builder.CreateCall(
  1066. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
  1067. CGF.CGM.FloatTy),
  1068. Src);
  1069. } else {
  1070. Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
  1071. }
  1072. SrcType = CGF.getContext().FloatTy;
  1073. SrcTy = CGF.FloatTy;
  1074. }
  1075. }
  1076. // Ignore conversions like int -> uint.
  1077. if (SrcTy == DstTy) {
  1078. if (Opts.EmitImplicitIntegerSignChangeChecks)
  1079. EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
  1080. NoncanonicalDstType, Loc);
  1081. return Src;
  1082. }
  1083. // Handle pointer conversions next: pointers can only be converted to/from
  1084. // other pointers and integers. Check for pointer types in terms of LLVM, as
  1085. // some native types (like Obj-C id) may map to a pointer type.
  1086. if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
  1087. // The source value may be an integer, or a pointer.
  1088. if (isa<llvm::PointerType>(SrcTy))
  1089. return Builder.CreateBitCast(Src, DstTy, "conv");
  1090. assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
  1091. // First, convert to the correct width so that we control the kind of
  1092. // extension.
  1093. llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
  1094. bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
  1095. llvm::Value* IntResult =
  1096. Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
  1097. // Then, cast to pointer.
  1098. return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
  1099. }
  1100. if (isa<llvm::PointerType>(SrcTy)) {
  1101. // Must be an ptr to int cast.
  1102. assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
  1103. return Builder.CreatePtrToInt(Src, DstTy, "conv");
  1104. }
  1105. // A scalar can be splatted to an extended vector of the same element type
  1106. if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
  1107. // Sema should add casts to make sure that the source expression's type is
  1108. // the same as the vector's element type (sans qualifiers)
  1109. assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
  1110. SrcType.getTypePtr() &&
  1111. "Splatted expr doesn't match with vector element type?");
  1112. // Splat the element across to all elements
  1113. unsigned NumElements = DstTy->getVectorNumElements();
  1114. return Builder.CreateVectorSplat(NumElements, Src, "splat");
  1115. }
  1116. if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) {
  1117. // Allow bitcast from vector to integer/fp of the same size.
  1118. unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
  1119. unsigned DstSize = DstTy->getPrimitiveSizeInBits();
  1120. if (SrcSize == DstSize)
  1121. return Builder.CreateBitCast(Src, DstTy, "conv");
  1122. // Conversions between vectors of different sizes are not allowed except
  1123. // when vectors of half are involved. Operations on storage-only half
  1124. // vectors require promoting half vector operands to float vectors and
  1125. // truncating the result, which is either an int or float vector, to a
  1126. // short or half vector.
  1127. // Source and destination are both expected to be vectors.
  1128. llvm::Type *SrcElementTy = SrcTy->getVectorElementType();
  1129. llvm::Type *DstElementTy = DstTy->getVectorElementType();
  1130. (void)DstElementTy;
  1131. assert(((SrcElementTy->isIntegerTy() &&
  1132. DstElementTy->isIntegerTy()) ||
  1133. (SrcElementTy->isFloatingPointTy() &&
  1134. DstElementTy->isFloatingPointTy())) &&
  1135. "unexpected conversion between a floating-point vector and an "
  1136. "integer vector");
  1137. // Truncate an i32 vector to an i16 vector.
  1138. if (SrcElementTy->isIntegerTy())
  1139. return Builder.CreateIntCast(Src, DstTy, false, "conv");
  1140. // Truncate a float vector to a half vector.
  1141. if (SrcSize > DstSize)
  1142. return Builder.CreateFPTrunc(Src, DstTy, "conv");
  1143. // Promote a half vector to a float vector.
  1144. return Builder.CreateFPExt(Src, DstTy, "conv");
  1145. }
  1146. // Finally, we have the arithmetic types: real int/float.
  1147. Value *Res = nullptr;
  1148. llvm::Type *ResTy = DstTy;
  1149. // An overflowing conversion has undefined behavior if either the source type
  1150. // or the destination type is a floating-point type. However, we consider the
  1151. // range of representable values for all floating-point types to be
  1152. // [-inf,+inf], so no overflow can ever happen when the destination type is a
  1153. // floating-point type.
  1154. if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
  1155. OrigSrcType->isFloatingType())
  1156. EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
  1157. Loc);
  1158. // Cast to half through float if half isn't a native type.
  1159. if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
  1160. // Make sure we cast in a single step if from another FP type.
  1161. if (SrcTy->isFloatingPointTy()) {
  1162. // Use the intrinsic if the half type itself isn't supported
  1163. // (as opposed to operations on half, available with NativeHalfType).
  1164. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
  1165. return Builder.CreateCall(
  1166. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
  1167. // If the half type is supported, just use an fptrunc.
  1168. return Builder.CreateFPTrunc(Src, DstTy);
  1169. }
  1170. DstTy = CGF.FloatTy;
  1171. }
  1172. if (isa<llvm::IntegerType>(SrcTy)) {
  1173. bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
  1174. if (SrcType->isBooleanType() && Opts.TreatBooleanAsSigned) {
  1175. InputSigned = true;
  1176. }
  1177. if (isa<llvm::IntegerType>(DstTy))
  1178. Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
  1179. else if (InputSigned)
  1180. Res = Builder.CreateSIToFP(Src, DstTy, "conv");
  1181. else
  1182. Res = Builder.CreateUIToFP(Src, DstTy, "conv");
  1183. } else if (isa<llvm::IntegerType>(DstTy)) {
  1184. assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
  1185. if (DstType->isSignedIntegerOrEnumerationType())
  1186. Res = Builder.CreateFPToSI(Src, DstTy, "conv");
  1187. else
  1188. Res = Builder.CreateFPToUI(Src, DstTy, "conv");
  1189. } else {
  1190. assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
  1191. "Unknown real conversion");
  1192. if (DstTy->getTypeID() < SrcTy->getTypeID())
  1193. Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
  1194. else
  1195. Res = Builder.CreateFPExt(Src, DstTy, "conv");
  1196. }
  1197. if (DstTy != ResTy) {
  1198. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
  1199. assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
  1200. Res = Builder.CreateCall(
  1201. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
  1202. Res);
  1203. } else {
  1204. Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
  1205. }
  1206. }
  1207. if (Opts.EmitImplicitIntegerTruncationChecks)
  1208. EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
  1209. NoncanonicalDstType, Loc);
  1210. if (Opts.EmitImplicitIntegerSignChangeChecks)
  1211. EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
  1212. NoncanonicalDstType, Loc);
  1213. return Res;
  1214. }
  1215. Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
  1216. QualType DstTy,
  1217. SourceLocation Loc) {
  1218. FixedPointSemantics SrcFPSema =
  1219. CGF.getContext().getFixedPointSemantics(SrcTy);
  1220. FixedPointSemantics DstFPSema =
  1221. CGF.getContext().getFixedPointSemantics(DstTy);
  1222. return EmitFixedPointConversion(Src, SrcFPSema, DstFPSema, Loc,
  1223. DstTy->isIntegerType());
  1224. }
  1225. Value *ScalarExprEmitter::EmitFixedPointConversion(
  1226. Value *Src, FixedPointSemantics &SrcFPSema, FixedPointSemantics &DstFPSema,
  1227. SourceLocation Loc, bool DstIsInteger) {
  1228. using llvm::APInt;
  1229. using llvm::ConstantInt;
  1230. using llvm::Value;
  1231. unsigned SrcWidth = SrcFPSema.getWidth();
  1232. unsigned DstWidth = DstFPSema.getWidth();
  1233. unsigned SrcScale = SrcFPSema.getScale();
  1234. unsigned DstScale = DstFPSema.getScale();
  1235. bool SrcIsSigned = SrcFPSema.isSigned();
  1236. bool DstIsSigned = DstFPSema.isSigned();
  1237. llvm::Type *DstIntTy = Builder.getIntNTy(DstWidth);
  1238. Value *Result = Src;
  1239. unsigned ResultWidth = SrcWidth;
  1240. // Downscale.
  1241. if (DstScale < SrcScale) {
  1242. // When converting to integers, we round towards zero. For negative numbers,
  1243. // right shifting rounds towards negative infinity. In this case, we can
  1244. // just round up before shifting.
  1245. if (DstIsInteger && SrcIsSigned) {
  1246. Value *Zero = llvm::Constant::getNullValue(Result->getType());
  1247. Value *IsNegative = Builder.CreateICmpSLT(Result, Zero);
  1248. Value *LowBits = ConstantInt::get(
  1249. CGF.getLLVMContext(), APInt::getLowBitsSet(ResultWidth, SrcScale));
  1250. Value *Rounded = Builder.CreateAdd(Result, LowBits);
  1251. Result = Builder.CreateSelect(IsNegative, Rounded, Result);
  1252. }
  1253. Result = SrcIsSigned
  1254. ? Builder.CreateAShr(Result, SrcScale - DstScale, "downscale")
  1255. : Builder.CreateLShr(Result, SrcScale - DstScale, "downscale");
  1256. }
  1257. if (!DstFPSema.isSaturated()) {
  1258. // Resize.
  1259. Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
  1260. // Upscale.
  1261. if (DstScale > SrcScale)
  1262. Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
  1263. } else {
  1264. // Adjust the number of fractional bits.
  1265. if (DstScale > SrcScale) {
  1266. // Compare to DstWidth to prevent resizing twice.
  1267. ResultWidth = std::max(SrcWidth + DstScale - SrcScale, DstWidth);
  1268. llvm::Type *UpscaledTy = Builder.getIntNTy(ResultWidth);
  1269. Result = Builder.CreateIntCast(Result, UpscaledTy, SrcIsSigned, "resize");
  1270. Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
  1271. }
  1272. // Handle saturation.
  1273. bool LessIntBits = DstFPSema.getIntegralBits() < SrcFPSema.getIntegralBits();
  1274. if (LessIntBits) {
  1275. Value *Max = ConstantInt::get(
  1276. CGF.getLLVMContext(),
  1277. APFixedPoint::getMax(DstFPSema).getValue().extOrTrunc(ResultWidth));
  1278. Value *TooHigh = SrcIsSigned ? Builder.CreateICmpSGT(Result, Max)
  1279. : Builder.CreateICmpUGT(Result, Max);
  1280. Result = Builder.CreateSelect(TooHigh, Max, Result, "satmax");
  1281. }
  1282. // Cannot overflow min to dest type if src is unsigned since all fixed
  1283. // point types can cover the unsigned min of 0.
  1284. if (SrcIsSigned && (LessIntBits || !DstIsSigned)) {
  1285. Value *Min = ConstantInt::get(
  1286. CGF.getLLVMContext(),
  1287. APFixedPoint::getMin(DstFPSema).getValue().extOrTrunc(ResultWidth));
  1288. Value *TooLow = Builder.CreateICmpSLT(Result, Min);
  1289. Result = Builder.CreateSelect(TooLow, Min, Result, "satmin");
  1290. }
  1291. // Resize the integer part to get the final destination size.
  1292. if (ResultWidth != DstWidth)
  1293. Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
  1294. }
  1295. return Result;
  1296. }
  1297. /// Emit a conversion from the specified complex type to the specified
  1298. /// destination type, where the destination type is an LLVM scalar type.
  1299. Value *ScalarExprEmitter::EmitComplexToScalarConversion(
  1300. CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
  1301. SourceLocation Loc) {
  1302. // Get the source element type.
  1303. SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
  1304. // Handle conversions to bool first, they are special: comparisons against 0.
  1305. if (DstTy->isBooleanType()) {
  1306. // Complex != 0 -> (Real != 0) | (Imag != 0)
  1307. Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
  1308. Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
  1309. return Builder.CreateOr(Src.first, Src.second, "tobool");
  1310. }
  1311. // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
  1312. // the imaginary part of the complex value is discarded and the value of the
  1313. // real part is converted according to the conversion rules for the
  1314. // corresponding real type.
  1315. return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
  1316. }
  1317. Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
  1318. return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
  1319. }
  1320. /// Emit a sanitization check for the given "binary" operation (which
  1321. /// might actually be a unary increment which has been lowered to a binary
  1322. /// operation). The check passes if all values in \p Checks (which are \c i1),
  1323. /// are \c true.
  1324. void ScalarExprEmitter::EmitBinOpCheck(
  1325. ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
  1326. assert(CGF.IsSanitizerScope);
  1327. SanitizerHandler Check;
  1328. SmallVector<llvm::Constant *, 4> StaticData;
  1329. SmallVector<llvm::Value *, 2> DynamicData;
  1330. BinaryOperatorKind Opcode = Info.Opcode;
  1331. if (BinaryOperator::isCompoundAssignmentOp(Opcode))
  1332. Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
  1333. StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
  1334. const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
  1335. if (UO && UO->getOpcode() == UO_Minus) {
  1336. Check = SanitizerHandler::NegateOverflow;
  1337. StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
  1338. DynamicData.push_back(Info.RHS);
  1339. } else {
  1340. if (BinaryOperator::isShiftOp(Opcode)) {
  1341. // Shift LHS negative or too large, or RHS out of bounds.
  1342. Check = SanitizerHandler::ShiftOutOfBounds;
  1343. const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
  1344. StaticData.push_back(
  1345. CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
  1346. StaticData.push_back(
  1347. CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
  1348. } else if (Opcode == BO_Div || Opcode == BO_Rem) {
  1349. // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
  1350. Check = SanitizerHandler::DivremOverflow;
  1351. StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
  1352. } else {
  1353. // Arithmetic overflow (+, -, *).
  1354. switch (Opcode) {
  1355. case BO_Add: Check = SanitizerHandler::AddOverflow; break;
  1356. case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
  1357. case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
  1358. default: llvm_unreachable("unexpected opcode for bin op check");
  1359. }
  1360. StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
  1361. }
  1362. DynamicData.push_back(Info.LHS);
  1363. DynamicData.push_back(Info.RHS);
  1364. }
  1365. CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
  1366. }
  1367. //===----------------------------------------------------------------------===//
  1368. // Visitor Methods
  1369. //===----------------------------------------------------------------------===//
  1370. Value *ScalarExprEmitter::VisitExpr(Expr *E) {
  1371. CGF.ErrorUnsupported(E, "scalar expression");
  1372. if (E->getType()->isVoidType())
  1373. return nullptr;
  1374. return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
  1375. }
  1376. Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
  1377. // Vector Mask Case
  1378. if (E->getNumSubExprs() == 2) {
  1379. Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
  1380. Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
  1381. Value *Mask;
  1382. llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
  1383. unsigned LHSElts = LTy->getNumElements();
  1384. Mask = RHS;
  1385. llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
  1386. // Mask off the high bits of each shuffle index.
  1387. Value *MaskBits =
  1388. llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
  1389. Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
  1390. // newv = undef
  1391. // mask = mask & maskbits
  1392. // for each elt
  1393. // n = extract mask i
  1394. // x = extract val n
  1395. // newv = insert newv, x, i
  1396. llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
  1397. MTy->getNumElements());
  1398. Value* NewV = llvm::UndefValue::get(RTy);
  1399. for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
  1400. Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
  1401. Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
  1402. Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
  1403. NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
  1404. }
  1405. return NewV;
  1406. }
  1407. Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
  1408. Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
  1409. SmallVector<llvm::Constant*, 32> indices;
  1410. for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
  1411. llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
  1412. // Check for -1 and output it as undef in the IR.
  1413. if (Idx.isSigned() && Idx.isAllOnesValue())
  1414. indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
  1415. else
  1416. indices.push_back(Builder.getInt32(Idx.getZExtValue()));
  1417. }
  1418. Value *SV = llvm::ConstantVector::get(indices);
  1419. return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
  1420. }
  1421. Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
  1422. QualType SrcType = E->getSrcExpr()->getType(),
  1423. DstType = E->getType();
  1424. Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
  1425. SrcType = CGF.getContext().getCanonicalType(SrcType);
  1426. DstType = CGF.getContext().getCanonicalType(DstType);
  1427. if (SrcType == DstType) return Src;
  1428. assert(SrcType->isVectorType() &&
  1429. "ConvertVector source type must be a vector");
  1430. assert(DstType->isVectorType() &&
  1431. "ConvertVector destination type must be a vector");
  1432. llvm::Type *SrcTy = Src->getType();
  1433. llvm::Type *DstTy = ConvertType(DstType);
  1434. // Ignore conversions like int -> uint.
  1435. if (SrcTy == DstTy)
  1436. return Src;
  1437. QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
  1438. DstEltType = DstType->castAs<VectorType>()->getElementType();
  1439. assert(SrcTy->isVectorTy() &&
  1440. "ConvertVector source IR type must be a vector");
  1441. assert(DstTy->isVectorTy() &&
  1442. "ConvertVector destination IR type must be a vector");
  1443. llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
  1444. *DstEltTy = DstTy->getVectorElementType();
  1445. if (DstEltType->isBooleanType()) {
  1446. assert((SrcEltTy->isFloatingPointTy() ||
  1447. isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
  1448. llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
  1449. if (SrcEltTy->isFloatingPointTy()) {
  1450. return Builder.CreateFCmpUNE(Src, Zero, "tobool");
  1451. } else {
  1452. return Builder.CreateICmpNE(Src, Zero, "tobool");
  1453. }
  1454. }
  1455. // We have the arithmetic types: real int/float.
  1456. Value *Res = nullptr;
  1457. if (isa<llvm::IntegerType>(SrcEltTy)) {
  1458. bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
  1459. if (isa<llvm::IntegerType>(DstEltTy))
  1460. Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
  1461. else if (InputSigned)
  1462. Res = Builder.CreateSIToFP(Src, DstTy, "conv");
  1463. else
  1464. Res = Builder.CreateUIToFP(Src, DstTy, "conv");
  1465. } else if (isa<llvm::IntegerType>(DstEltTy)) {
  1466. assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
  1467. if (DstEltType->isSignedIntegerOrEnumerationType())
  1468. Res = Builder.CreateFPToSI(Src, DstTy, "conv");
  1469. else
  1470. Res = Builder.CreateFPToUI(Src, DstTy, "conv");
  1471. } else {
  1472. assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
  1473. "Unknown real conversion");
  1474. if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
  1475. Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
  1476. else
  1477. Res = Builder.CreateFPExt(Src, DstTy, "conv");
  1478. }
  1479. return Res;
  1480. }
  1481. Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
  1482. if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
  1483. CGF.EmitIgnoredExpr(E->getBase());
  1484. return CGF.emitScalarConstant(Constant, E);
  1485. } else {
  1486. Expr::EvalResult Result;
  1487. if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
  1488. llvm::APSInt Value = Result.Val.getInt();
  1489. CGF.EmitIgnoredExpr(E->getBase());
  1490. return Builder.getInt(Value);
  1491. }
  1492. }
  1493. return EmitLoadOfLValue(E);
  1494. }
  1495. Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
  1496. TestAndClearIgnoreResultAssign();
  1497. // Emit subscript expressions in rvalue context's. For most cases, this just
  1498. // loads the lvalue formed by the subscript expr. However, we have to be
  1499. // careful, because the base of a vector subscript is occasionally an rvalue,
  1500. // so we can't get it as an lvalue.
  1501. if (!E->getBase()->getType()->isVectorType())
  1502. return EmitLoadOfLValue(E);
  1503. // Handle the vector case. The base must be a vector, the index must be an
  1504. // integer value.
  1505. Value *Base = Visit(E->getBase());
  1506. Value *Idx = Visit(E->getIdx());
  1507. QualType IdxTy = E->getIdx()->getType();
  1508. if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
  1509. CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
  1510. return Builder.CreateExtractElement(Base, Idx, "vecext");
  1511. }
  1512. static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
  1513. unsigned Off, llvm::Type *I32Ty) {
  1514. int MV = SVI->getMaskValue(Idx);
  1515. if (MV == -1)
  1516. return llvm::UndefValue::get(I32Ty);
  1517. return llvm::ConstantInt::get(I32Ty, Off+MV);
  1518. }
  1519. static llvm::Constant *getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
  1520. if (C->getBitWidth() != 32) {
  1521. assert(llvm::ConstantInt::isValueValidForType(I32Ty,
  1522. C->getZExtValue()) &&
  1523. "Index operand too large for shufflevector mask!");
  1524. return llvm::ConstantInt::get(I32Ty, C->getZExtValue());
  1525. }
  1526. return C;
  1527. }
  1528. Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
  1529. bool Ignore = TestAndClearIgnoreResultAssign();
  1530. (void)Ignore;
  1531. assert (Ignore == false && "init list ignored");
  1532. unsigned NumInitElements = E->getNumInits();
  1533. if (E->hadArrayRangeDesignator())
  1534. CGF.ErrorUnsupported(E, "GNU array range designator extension");
  1535. llvm::VectorType *VType =
  1536. dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
  1537. if (!VType) {
  1538. if (NumInitElements == 0) {
  1539. // C++11 value-initialization for the scalar.
  1540. return EmitNullValue(E->getType());
  1541. }
  1542. // We have a scalar in braces. Just use the first element.
  1543. return Visit(E->getInit(0));
  1544. }
  1545. unsigned ResElts = VType->getNumElements();
  1546. // Loop over initializers collecting the Value for each, and remembering
  1547. // whether the source was swizzle (ExtVectorElementExpr). This will allow
  1548. // us to fold the shuffle for the swizzle into the shuffle for the vector
  1549. // initializer, since LLVM optimizers generally do not want to touch
  1550. // shuffles.
  1551. unsigned CurIdx = 0;
  1552. bool VIsUndefShuffle = false;
  1553. llvm::Value *V = llvm::UndefValue::get(VType);
  1554. for (unsigned i = 0; i != NumInitElements; ++i) {
  1555. Expr *IE = E->getInit(i);
  1556. Value *Init = Visit(IE);
  1557. SmallVector<llvm::Constant*, 16> Args;
  1558. llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
  1559. // Handle scalar elements. If the scalar initializer is actually one
  1560. // element of a different vector of the same width, use shuffle instead of
  1561. // extract+insert.
  1562. if (!VVT) {
  1563. if (isa<ExtVectorElementExpr>(IE)) {
  1564. llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
  1565. if (EI->getVectorOperandType()->getNumElements() == ResElts) {
  1566. llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
  1567. Value *LHS = nullptr, *RHS = nullptr;
  1568. if (CurIdx == 0) {
  1569. // insert into undef -> shuffle (src, undef)
  1570. // shufflemask must use an i32
  1571. Args.push_back(getAsInt32(C, CGF.Int32Ty));
  1572. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  1573. LHS = EI->getVectorOperand();
  1574. RHS = V;
  1575. VIsUndefShuffle = true;
  1576. } else if (VIsUndefShuffle) {
  1577. // insert into undefshuffle && size match -> shuffle (v, src)
  1578. llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
  1579. for (unsigned j = 0; j != CurIdx; ++j)
  1580. Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
  1581. Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
  1582. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  1583. LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
  1584. RHS = EI->getVectorOperand();
  1585. VIsUndefShuffle = false;
  1586. }
  1587. if (!Args.empty()) {
  1588. llvm::Constant *Mask = llvm::ConstantVector::get(Args);
  1589. V = Builder.CreateShuffleVector(LHS, RHS, Mask);
  1590. ++CurIdx;
  1591. continue;
  1592. }
  1593. }
  1594. }
  1595. V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
  1596. "vecinit");
  1597. VIsUndefShuffle = false;
  1598. ++CurIdx;
  1599. continue;
  1600. }
  1601. unsigned InitElts = VVT->getNumElements();
  1602. // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
  1603. // input is the same width as the vector being constructed, generate an
  1604. // optimized shuffle of the swizzle input into the result.
  1605. unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
  1606. if (isa<ExtVectorElementExpr>(IE)) {
  1607. llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
  1608. Value *SVOp = SVI->getOperand(0);
  1609. llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
  1610. if (OpTy->getNumElements() == ResElts) {
  1611. for (unsigned j = 0; j != CurIdx; ++j) {
  1612. // If the current vector initializer is a shuffle with undef, merge
  1613. // this shuffle directly into it.
  1614. if (VIsUndefShuffle) {
  1615. Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
  1616. CGF.Int32Ty));
  1617. } else {
  1618. Args.push_back(Builder.getInt32(j));
  1619. }
  1620. }
  1621. for (unsigned j = 0, je = InitElts; j != je; ++j)
  1622. Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
  1623. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  1624. if (VIsUndefShuffle)
  1625. V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
  1626. Init = SVOp;
  1627. }
  1628. }
  1629. // Extend init to result vector length, and then shuffle its contribution
  1630. // to the vector initializer into V.
  1631. if (Args.empty()) {
  1632. for (unsigned j = 0; j != InitElts; ++j)
  1633. Args.push_back(Builder.getInt32(j));
  1634. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  1635. llvm::Constant *Mask = llvm::ConstantVector::get(Args);
  1636. Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
  1637. Mask, "vext");
  1638. Args.clear();
  1639. for (unsigned j = 0; j != CurIdx; ++j)
  1640. Args.push_back(Builder.getInt32(j));
  1641. for (unsigned j = 0; j != InitElts; ++j)
  1642. Args.push_back(Builder.getInt32(j+Offset));
  1643. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  1644. }
  1645. // If V is undef, make sure it ends up on the RHS of the shuffle to aid
  1646. // merging subsequent shuffles into this one.
  1647. if (CurIdx == 0)
  1648. std::swap(V, Init);
  1649. llvm::Constant *Mask = llvm::ConstantVector::get(Args);
  1650. V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
  1651. VIsUndefShuffle = isa<llvm::UndefValue>(Init);
  1652. CurIdx += InitElts;
  1653. }
  1654. // FIXME: evaluate codegen vs. shuffling against constant null vector.
  1655. // Emit remaining default initializers.
  1656. llvm::Type *EltTy = VType->getElementType();
  1657. // Emit remaining default initializers
  1658. for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
  1659. Value *Idx = Builder.getInt32(CurIdx);
  1660. llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
  1661. V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
  1662. }
  1663. return V;
  1664. }
  1665. bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
  1666. const Expr *E = CE->getSubExpr();
  1667. if (CE->getCastKind() == CK_UncheckedDerivedToBase)
  1668. return false;
  1669. if (isa<CXXThisExpr>(E->IgnoreParens())) {
  1670. // We always assume that 'this' is never null.
  1671. return false;
  1672. }
  1673. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
  1674. // And that glvalue casts are never null.
  1675. if (ICE->getValueKind() != VK_RValue)
  1676. return false;
  1677. }
  1678. return true;
  1679. }
  1680. // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
  1681. // have to handle a more broad range of conversions than explicit casts, as they
  1682. // handle things like function to ptr-to-function decay etc.
  1683. Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
  1684. Expr *E = CE->getSubExpr();
  1685. QualType DestTy = CE->getType();
  1686. CastKind Kind = CE->getCastKind();
  1687. // These cases are generally not written to ignore the result of
  1688. // evaluating their sub-expressions, so we clear this now.
  1689. bool Ignored = TestAndClearIgnoreResultAssign();
  1690. // Since almost all cast kinds apply to scalars, this switch doesn't have
  1691. // a default case, so the compiler will warn on a missing case. The cases
  1692. // are in the same order as in the CastKind enum.
  1693. switch (Kind) {
  1694. case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
  1695. case CK_BuiltinFnToFnPtr:
  1696. llvm_unreachable("builtin functions are handled elsewhere");
  1697. case CK_LValueBitCast:
  1698. case CK_ObjCObjectLValueCast: {
  1699. Address Addr = EmitLValue(E).getAddress();
  1700. Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
  1701. LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
  1702. return EmitLoadOfLValue(LV, CE->getExprLoc());
  1703. }
  1704. case CK_LValueToRValueBitCast: {
  1705. LValue SourceLVal = CGF.EmitLValue(E);
  1706. Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(),
  1707. CGF.ConvertTypeForMem(DestTy));
  1708. LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
  1709. DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
  1710. return EmitLoadOfLValue(DestLV, CE->getExprLoc());
  1711. }
  1712. case CK_CPointerToObjCPointerCast:
  1713. case CK_BlockPointerToObjCPointerCast:
  1714. case CK_AnyPointerToBlockPointerCast:
  1715. case CK_BitCast: {
  1716. Value *Src = Visit(const_cast<Expr*>(E));
  1717. llvm::Type *SrcTy = Src->getType();
  1718. llvm::Type *DstTy = ConvertType(DestTy);
  1719. if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
  1720. SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
  1721. llvm_unreachable("wrong cast for pointers in different address spaces"
  1722. "(must be an address space cast)!");
  1723. }
  1724. if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
  1725. if (auto PT = DestTy->getAs<PointerType>())
  1726. CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
  1727. /*MayBeNull=*/true,
  1728. CodeGenFunction::CFITCK_UnrelatedCast,
  1729. CE->getBeginLoc());
  1730. }
  1731. if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
  1732. const QualType SrcType = E->getType();
  1733. if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
  1734. // Casting to pointer that could carry dynamic information (provided by
  1735. // invariant.group) requires launder.
  1736. Src = Builder.CreateLaunderInvariantGroup(Src);
  1737. } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
  1738. // Casting to pointer that does not carry dynamic information (provided
  1739. // by invariant.group) requires stripping it. Note that we don't do it
  1740. // if the source could not be dynamic type and destination could be
  1741. // dynamic because dynamic information is already laundered. It is
  1742. // because launder(strip(src)) == launder(src), so there is no need to
  1743. // add extra strip before launder.
  1744. Src = Builder.CreateStripInvariantGroup(Src);
  1745. }
  1746. }
  1747. // Update heapallocsite metadata when there is an explicit cast.
  1748. if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(Src))
  1749. if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE))
  1750. CGF.getDebugInfo()->
  1751. addHeapAllocSiteMetadata(CI, CE->getType(), CE->getExprLoc());
  1752. return Builder.CreateBitCast(Src, DstTy);
  1753. }
  1754. case CK_AddressSpaceConversion: {
  1755. Expr::EvalResult Result;
  1756. if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
  1757. Result.Val.isNullPointer()) {
  1758. // If E has side effect, it is emitted even if its final result is a
  1759. // null pointer. In that case, a DCE pass should be able to
  1760. // eliminate the useless instructions emitted during translating E.
  1761. if (Result.HasSideEffects)
  1762. Visit(E);
  1763. return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
  1764. ConvertType(DestTy)), DestTy);
  1765. }
  1766. // Since target may map different address spaces in AST to the same address
  1767. // space, an address space conversion may end up as a bitcast.
  1768. return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
  1769. CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
  1770. DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
  1771. }
  1772. case CK_AtomicToNonAtomic:
  1773. case CK_NonAtomicToAtomic:
  1774. case CK_NoOp:
  1775. case CK_UserDefinedConversion:
  1776. return Visit(const_cast<Expr*>(E));
  1777. case CK_BaseToDerived: {
  1778. const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
  1779. assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
  1780. Address Base = CGF.EmitPointerWithAlignment(E);
  1781. Address Derived =
  1782. CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
  1783. CE->path_begin(), CE->path_end(),
  1784. CGF.ShouldNullCheckClassCastValue(CE));
  1785. // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
  1786. // performed and the object is not of the derived type.
  1787. if (CGF.sanitizePerformTypeCheck())
  1788. CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
  1789. Derived.getPointer(), DestTy->getPointeeType());
  1790. if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
  1791. CGF.EmitVTablePtrCheckForCast(
  1792. DestTy->getPointeeType(), Derived.getPointer(),
  1793. /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast,
  1794. CE->getBeginLoc());
  1795. return Derived.getPointer();
  1796. }
  1797. case CK_UncheckedDerivedToBase:
  1798. case CK_DerivedToBase: {
  1799. // The EmitPointerWithAlignment path does this fine; just discard
  1800. // the alignment.
  1801. return CGF.EmitPointerWithAlignment(CE).getPointer();
  1802. }
  1803. case CK_Dynamic: {
  1804. Address V = CGF.EmitPointerWithAlignment(E);
  1805. const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
  1806. return CGF.EmitDynamicCast(V, DCE);
  1807. }
  1808. case CK_ArrayToPointerDecay:
  1809. return CGF.EmitArrayToPointerDecay(E).getPointer();
  1810. case CK_FunctionToPointerDecay:
  1811. return EmitLValue(E).getPointer();
  1812. case CK_NullToPointer:
  1813. if (MustVisitNullValue(E))
  1814. CGF.EmitIgnoredExpr(E);
  1815. return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
  1816. DestTy);
  1817. case CK_NullToMemberPointer: {
  1818. if (MustVisitNullValue(E))
  1819. CGF.EmitIgnoredExpr(E);
  1820. const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
  1821. return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
  1822. }
  1823. case CK_ReinterpretMemberPointer:
  1824. case CK_BaseToDerivedMemberPointer:
  1825. case CK_DerivedToBaseMemberPointer: {
  1826. Value *Src = Visit(E);
  1827. // Note that the AST doesn't distinguish between checked and
  1828. // unchecked member pointer conversions, so we always have to
  1829. // implement checked conversions here. This is inefficient when
  1830. // actual control flow may be required in order to perform the
  1831. // check, which it is for data member pointers (but not member
  1832. // function pointers on Itanium and ARM).
  1833. return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
  1834. }
  1835. case CK_ARCProduceObject:
  1836. return CGF.EmitARCRetainScalarExpr(E);
  1837. case CK_ARCConsumeObject:
  1838. return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
  1839. case CK_ARCReclaimReturnedObject:
  1840. return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
  1841. case CK_ARCExtendBlockObject:
  1842. return CGF.EmitARCExtendBlockObject(E);
  1843. case CK_CopyAndAutoreleaseBlockObject:
  1844. return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
  1845. case CK_FloatingRealToComplex:
  1846. case CK_FloatingComplexCast:
  1847. case CK_IntegralRealToComplex:
  1848. case CK_IntegralComplexCast:
  1849. case CK_IntegralComplexToFloatingComplex:
  1850. case CK_FloatingComplexToIntegralComplex:
  1851. case CK_ConstructorConversion:
  1852. case CK_ToUnion:
  1853. llvm_unreachable("scalar cast to non-scalar value");
  1854. case CK_LValueToRValue:
  1855. assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
  1856. assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
  1857. return Visit(const_cast<Expr*>(E));
  1858. case CK_IntegralToPointer: {
  1859. Value *Src = Visit(const_cast<Expr*>(E));
  1860. // First, convert to the correct width so that we control the kind of
  1861. // extension.
  1862. auto DestLLVMTy = ConvertType(DestTy);
  1863. llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
  1864. bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
  1865. llvm::Value* IntResult =
  1866. Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
  1867. auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
  1868. if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
  1869. // Going from integer to pointer that could be dynamic requires reloading
  1870. // dynamic information from invariant.group.
  1871. if (DestTy.mayBeDynamicClass())
  1872. IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
  1873. }
  1874. return IntToPtr;
  1875. }
  1876. case CK_PointerToIntegral: {
  1877. assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
  1878. auto *PtrExpr = Visit(E);
  1879. if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
  1880. const QualType SrcType = E->getType();
  1881. // Casting to integer requires stripping dynamic information as it does
  1882. // not carries it.
  1883. if (SrcType.mayBeDynamicClass())
  1884. PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
  1885. }
  1886. return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
  1887. }
  1888. case CK_ToVoid: {
  1889. CGF.EmitIgnoredExpr(E);
  1890. return nullptr;
  1891. }
  1892. case CK_VectorSplat: {
  1893. llvm::Type *DstTy = ConvertType(DestTy);
  1894. Value *Elt = Visit(const_cast<Expr*>(E));
  1895. // Splat the element across to all elements
  1896. unsigned NumElements = DstTy->getVectorNumElements();
  1897. return Builder.CreateVectorSplat(NumElements, Elt, "splat");
  1898. }
  1899. case CK_FixedPointCast:
  1900. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1901. CE->getExprLoc());
  1902. case CK_FixedPointToBoolean:
  1903. assert(E->getType()->isFixedPointType() &&
  1904. "Expected src type to be fixed point type");
  1905. assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
  1906. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1907. CE->getExprLoc());
  1908. case CK_FixedPointToIntegral:
  1909. assert(E->getType()->isFixedPointType() &&
  1910. "Expected src type to be fixed point type");
  1911. assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
  1912. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1913. CE->getExprLoc());
  1914. case CK_IntegralToFixedPoint:
  1915. assert(E->getType()->isIntegerType() &&
  1916. "Expected src type to be an integer");
  1917. assert(DestTy->isFixedPointType() &&
  1918. "Expected dest type to be fixed point type");
  1919. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1920. CE->getExprLoc());
  1921. case CK_IntegralCast: {
  1922. ScalarConversionOpts Opts;
  1923. if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
  1924. if (!ICE->isPartOfExplicitCast())
  1925. Opts = ScalarConversionOpts(CGF.SanOpts);
  1926. }
  1927. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1928. CE->getExprLoc(), Opts);
  1929. }
  1930. case CK_IntegralToFloating:
  1931. case CK_FloatingToIntegral:
  1932. case CK_FloatingCast:
  1933. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1934. CE->getExprLoc());
  1935. case CK_BooleanToSignedIntegral: {
  1936. ScalarConversionOpts Opts;
  1937. Opts.TreatBooleanAsSigned = true;
  1938. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  1939. CE->getExprLoc(), Opts);
  1940. }
  1941. case CK_IntegralToBoolean:
  1942. return EmitIntToBoolConversion(Visit(E));
  1943. case CK_PointerToBoolean:
  1944. return EmitPointerToBoolConversion(Visit(E), E->getType());
  1945. case CK_FloatingToBoolean:
  1946. return EmitFloatToBoolConversion(Visit(E));
  1947. case CK_MemberPointerToBoolean: {
  1948. llvm::Value *MemPtr = Visit(E);
  1949. const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
  1950. return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
  1951. }
  1952. case CK_FloatingComplexToReal:
  1953. case CK_IntegralComplexToReal:
  1954. return CGF.EmitComplexExpr(E, false, true).first;
  1955. case CK_FloatingComplexToBoolean:
  1956. case CK_IntegralComplexToBoolean: {
  1957. CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
  1958. // TODO: kill this function off, inline appropriate case here
  1959. return EmitComplexToScalarConversion(V, E->getType(), DestTy,
  1960. CE->getExprLoc());
  1961. }
  1962. case CK_ZeroToOCLOpaqueType: {
  1963. assert((DestTy->isEventT() || DestTy->isQueueT() ||
  1964. DestTy->isOCLIntelSubgroupAVCType()) &&
  1965. "CK_ZeroToOCLEvent cast on non-event type");
  1966. return llvm::Constant::getNullValue(ConvertType(DestTy));
  1967. }
  1968. case CK_IntToOCLSampler:
  1969. return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
  1970. } // end of switch
  1971. llvm_unreachable("unknown scalar cast");
  1972. }
  1973. Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
  1974. CodeGenFunction::StmtExprEvaluation eval(CGF);
  1975. Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
  1976. !E->getType()->isVoidType());
  1977. if (!RetAlloca.isValid())
  1978. return nullptr;
  1979. return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
  1980. E->getExprLoc());
  1981. }
  1982. Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
  1983. CGF.enterFullExpression(E);
  1984. CodeGenFunction::RunCleanupsScope Scope(CGF);
  1985. Value *V = Visit(E->getSubExpr());
  1986. // Defend against dominance problems caused by jumps out of expression
  1987. // evaluation through the shared cleanup block.
  1988. Scope.ForceCleanup({&V});
  1989. return V;
  1990. }
  1991. //===----------------------------------------------------------------------===//
  1992. // Unary Operators
  1993. //===----------------------------------------------------------------------===//
  1994. static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
  1995. llvm::Value *InVal, bool IsInc) {
  1996. BinOpInfo BinOp;
  1997. BinOp.LHS = InVal;
  1998. BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
  1999. BinOp.Ty = E->getType();
  2000. BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
  2001. // FIXME: once UnaryOperator carries FPFeatures, copy it here.
  2002. BinOp.E = E;
  2003. return BinOp;
  2004. }
  2005. llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
  2006. const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
  2007. llvm::Value *Amount =
  2008. llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
  2009. StringRef Name = IsInc ? "inc" : "dec";
  2010. switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
  2011. case LangOptions::SOB_Defined:
  2012. return Builder.CreateAdd(InVal, Amount, Name);
  2013. case LangOptions::SOB_Undefined:
  2014. if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
  2015. return Builder.CreateNSWAdd(InVal, Amount, Name);
  2016. LLVM_FALLTHROUGH;
  2017. case LangOptions::SOB_Trapping:
  2018. if (!E->canOverflow())
  2019. return Builder.CreateNSWAdd(InVal, Amount, Name);
  2020. return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc));
  2021. }
  2022. llvm_unreachable("Unknown SignedOverflowBehaviorTy");
  2023. }
  2024. llvm::Value *
  2025. ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  2026. bool isInc, bool isPre) {
  2027. QualType type = E->getSubExpr()->getType();
  2028. llvm::PHINode *atomicPHI = nullptr;
  2029. llvm::Value *value;
  2030. llvm::Value *input;
  2031. int amount = (isInc ? 1 : -1);
  2032. bool isSubtraction = !isInc;
  2033. if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
  2034. type = atomicTy->getValueType();
  2035. if (isInc && type->isBooleanType()) {
  2036. llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
  2037. if (isPre) {
  2038. Builder.CreateStore(True, LV.getAddress(), LV.isVolatileQualified())
  2039. ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
  2040. return Builder.getTrue();
  2041. }
  2042. // For atomic bool increment, we just store true and return it for
  2043. // preincrement, do an atomic swap with true for postincrement
  2044. return Builder.CreateAtomicRMW(
  2045. llvm::AtomicRMWInst::Xchg, LV.getPointer(), True,
  2046. llvm::AtomicOrdering::SequentiallyConsistent);
  2047. }
  2048. // Special case for atomic increment / decrement on integers, emit
  2049. // atomicrmw instructions. We skip this if we want to be doing overflow
  2050. // checking, and fall into the slow path with the atomic cmpxchg loop.
  2051. if (!type->isBooleanType() && type->isIntegerType() &&
  2052. !(type->isUnsignedIntegerType() &&
  2053. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
  2054. CGF.getLangOpts().getSignedOverflowBehavior() !=
  2055. LangOptions::SOB_Trapping) {
  2056. llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
  2057. llvm::AtomicRMWInst::Sub;
  2058. llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
  2059. llvm::Instruction::Sub;
  2060. llvm::Value *amt = CGF.EmitToMemory(
  2061. llvm::ConstantInt::get(ConvertType(type), 1, true), type);
  2062. llvm::Value *old = Builder.CreateAtomicRMW(aop,
  2063. LV.getPointer(), amt, llvm::AtomicOrdering::SequentiallyConsistent);
  2064. return isPre ? Builder.CreateBinOp(op, old, amt) : old;
  2065. }
  2066. value = EmitLoadOfLValue(LV, E->getExprLoc());
  2067. input = value;
  2068. // For every other atomic operation, we need to emit a load-op-cmpxchg loop
  2069. llvm::BasicBlock *startBB = Builder.GetInsertBlock();
  2070. llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
  2071. value = CGF.EmitToMemory(value, type);
  2072. Builder.CreateBr(opBB);
  2073. Builder.SetInsertPoint(opBB);
  2074. atomicPHI = Builder.CreatePHI(value->getType(), 2);
  2075. atomicPHI->addIncoming(value, startBB);
  2076. value = atomicPHI;
  2077. } else {
  2078. value = EmitLoadOfLValue(LV, E->getExprLoc());
  2079. input = value;
  2080. }
  2081. // Special case of integer increment that we have to check first: bool++.
  2082. // Due to promotion rules, we get:
  2083. // bool++ -> bool = bool + 1
  2084. // -> bool = (int)bool + 1
  2085. // -> bool = ((int)bool + 1 != 0)
  2086. // An interesting aspect of this is that increment is always true.
  2087. // Decrement does not have this property.
  2088. if (isInc && type->isBooleanType()) {
  2089. value = Builder.getTrue();
  2090. // Most common case by far: integer increment.
  2091. } else if (type->isIntegerType()) {
  2092. // Note that signed integer inc/dec with width less than int can't
  2093. // overflow because of promotion rules; we're just eliding a few steps here.
  2094. if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
  2095. value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
  2096. } else if (E->canOverflow() && type->isUnsignedIntegerType() &&
  2097. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
  2098. value =
  2099. EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc));
  2100. } else {
  2101. llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
  2102. value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
  2103. }
  2104. // Next most common: pointer increment.
  2105. } else if (const PointerType *ptr = type->getAs<PointerType>()) {
  2106. QualType type = ptr->getPointeeType();
  2107. // VLA types don't have constant size.
  2108. if (const VariableArrayType *vla
  2109. = CGF.getContext().getAsVariableArrayType(type)) {
  2110. llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
  2111. if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
  2112. if (CGF.getLangOpts().isSignedOverflowDefined())
  2113. value = Builder.CreateGEP(value, numElts, "vla.inc");
  2114. else
  2115. value = CGF.EmitCheckedInBoundsGEP(
  2116. value, numElts, /*SignedIndices=*/false, isSubtraction,
  2117. E->getExprLoc(), "vla.inc");
  2118. // Arithmetic on function pointers (!) is just +-1.
  2119. } else if (type->isFunctionType()) {
  2120. llvm::Value *amt = Builder.getInt32(amount);
  2121. value = CGF.EmitCastToVoidPtr(value);
  2122. if (CGF.getLangOpts().isSignedOverflowDefined())
  2123. value = Builder.CreateGEP(value, amt, "incdec.funcptr");
  2124. else
  2125. value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
  2126. isSubtraction, E->getExprLoc(),
  2127. "incdec.funcptr");
  2128. value = Builder.CreateBitCast(value, input->getType());
  2129. // For everything else, we can just do a simple increment.
  2130. } else {
  2131. llvm::Value *amt = Builder.getInt32(amount);
  2132. if (CGF.getLangOpts().isSignedOverflowDefined())
  2133. value = Builder.CreateGEP(value, amt, "incdec.ptr");
  2134. else
  2135. value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
  2136. isSubtraction, E->getExprLoc(),
  2137. "incdec.ptr");
  2138. }
  2139. // Vector increment/decrement.
  2140. } else if (type->isVectorType()) {
  2141. if (type->hasIntegerRepresentation()) {
  2142. llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
  2143. value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
  2144. } else {
  2145. value = Builder.CreateFAdd(
  2146. value,
  2147. llvm::ConstantFP::get(value->getType(), amount),
  2148. isInc ? "inc" : "dec");
  2149. }
  2150. // Floating point.
  2151. } else if (type->isRealFloatingType()) {
  2152. // Add the inc/dec to the real part.
  2153. llvm::Value *amt;
  2154. if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
  2155. // Another special case: half FP increment should be done via float
  2156. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
  2157. value = Builder.CreateCall(
  2158. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
  2159. CGF.CGM.FloatTy),
  2160. input, "incdec.conv");
  2161. } else {
  2162. value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
  2163. }
  2164. }
  2165. if (value->getType()->isFloatTy())
  2166. amt = llvm::ConstantFP::get(VMContext,
  2167. llvm::APFloat(static_cast<float>(amount)));
  2168. else if (value->getType()->isDoubleTy())
  2169. amt = llvm::ConstantFP::get(VMContext,
  2170. llvm::APFloat(static_cast<double>(amount)));
  2171. else {
  2172. // Remaining types are Half, LongDouble or __float128. Convert from float.
  2173. llvm::APFloat F(static_cast<float>(amount));
  2174. bool ignored;
  2175. const llvm::fltSemantics *FS;
  2176. // Don't use getFloatTypeSemantics because Half isn't
  2177. // necessarily represented using the "half" LLVM type.
  2178. if (value->getType()->isFP128Ty())
  2179. FS = &CGF.getTarget().getFloat128Format();
  2180. else if (value->getType()->isHalfTy())
  2181. FS = &CGF.getTarget().getHalfFormat();
  2182. else
  2183. FS = &CGF.getTarget().getLongDoubleFormat();
  2184. F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
  2185. amt = llvm::ConstantFP::get(VMContext, F);
  2186. }
  2187. value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
  2188. if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
  2189. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
  2190. value = Builder.CreateCall(
  2191. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
  2192. CGF.CGM.FloatTy),
  2193. value, "incdec.conv");
  2194. } else {
  2195. value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
  2196. }
  2197. }
  2198. // Objective-C pointer types.
  2199. } else {
  2200. const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
  2201. value = CGF.EmitCastToVoidPtr(value);
  2202. CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
  2203. if (!isInc) size = -size;
  2204. llvm::Value *sizeValue =
  2205. llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
  2206. if (CGF.getLangOpts().isSignedOverflowDefined())
  2207. value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
  2208. else
  2209. value = CGF.EmitCheckedInBoundsGEP(value, sizeValue,
  2210. /*SignedIndices=*/false, isSubtraction,
  2211. E->getExprLoc(), "incdec.objptr");
  2212. value = Builder.CreateBitCast(value, input->getType());
  2213. }
  2214. if (atomicPHI) {
  2215. llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
  2216. llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
  2217. auto Pair = CGF.EmitAtomicCompareExchange(
  2218. LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
  2219. llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
  2220. llvm::Value *success = Pair.second;
  2221. atomicPHI->addIncoming(old, curBlock);
  2222. Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
  2223. Builder.SetInsertPoint(contBB);
  2224. return isPre ? value : input;
  2225. }
  2226. // Store the updated result through the lvalue.
  2227. if (LV.isBitField())
  2228. CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
  2229. else
  2230. CGF.EmitStoreThroughLValue(RValue::get(value), LV);
  2231. // If this is a postinc, return the value read from memory, otherwise use the
  2232. // updated value.
  2233. return isPre ? value : input;
  2234. }
  2235. Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
  2236. TestAndClearIgnoreResultAssign();
  2237. Value *Op = Visit(E->getSubExpr());
  2238. // Generate a unary FNeg for FP ops.
  2239. if (Op->getType()->isFPOrFPVectorTy())
  2240. return Builder.CreateFNeg(Op, "fneg");
  2241. // Emit unary minus with EmitSub so we handle overflow cases etc.
  2242. BinOpInfo BinOp;
  2243. BinOp.RHS = Op;
  2244. BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
  2245. BinOp.Ty = E->getType();
  2246. BinOp.Opcode = BO_Sub;
  2247. // FIXME: once UnaryOperator carries FPFeatures, copy it here.
  2248. BinOp.E = E;
  2249. return EmitSub(BinOp);
  2250. }
  2251. Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
  2252. TestAndClearIgnoreResultAssign();
  2253. Value *Op = Visit(E->getSubExpr());
  2254. return Builder.CreateNot(Op, "neg");
  2255. }
  2256. Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
  2257. // Perform vector logical not on comparison with zero vector.
  2258. if (E->getType()->isExtVectorType()) {
  2259. Value *Oper = Visit(E->getSubExpr());
  2260. Value *Zero = llvm::Constant::getNullValue(Oper->getType());
  2261. Value *Result;
  2262. if (Oper->getType()->isFPOrFPVectorTy())
  2263. Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
  2264. else
  2265. Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
  2266. return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
  2267. }
  2268. // Compare operand to zero.
  2269. Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
  2270. // Invert value.
  2271. // TODO: Could dynamically modify easy computations here. For example, if
  2272. // the operand is an icmp ne, turn into icmp eq.
  2273. BoolVal = Builder.CreateNot(BoolVal, "lnot");
  2274. // ZExt result to the expr type.
  2275. return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
  2276. }
  2277. Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
  2278. // Try folding the offsetof to a constant.
  2279. Expr::EvalResult EVResult;
  2280. if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
  2281. llvm::APSInt Value = EVResult.Val.getInt();
  2282. return Builder.getInt(Value);
  2283. }
  2284. // Loop over the components of the offsetof to compute the value.
  2285. unsigned n = E->getNumComponents();
  2286. llvm::Type* ResultType = ConvertType(E->getType());
  2287. llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
  2288. QualType CurrentType = E->getTypeSourceInfo()->getType();
  2289. for (unsigned i = 0; i != n; ++i) {
  2290. OffsetOfNode ON = E->getComponent(i);
  2291. llvm::Value *Offset = nullptr;
  2292. switch (ON.getKind()) {
  2293. case OffsetOfNode::Array: {
  2294. // Compute the index
  2295. Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
  2296. llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
  2297. bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
  2298. Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
  2299. // Save the element type
  2300. CurrentType =
  2301. CGF.getContext().getAsArrayType(CurrentType)->getElementType();
  2302. // Compute the element size
  2303. llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
  2304. CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
  2305. // Multiply out to compute the result
  2306. Offset = Builder.CreateMul(Idx, ElemSize);
  2307. break;
  2308. }
  2309. case OffsetOfNode::Field: {
  2310. FieldDecl *MemberDecl = ON.getField();
  2311. RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
  2312. const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
  2313. // Compute the index of the field in its parent.
  2314. unsigned i = 0;
  2315. // FIXME: It would be nice if we didn't have to loop here!
  2316. for (RecordDecl::field_iterator Field = RD->field_begin(),
  2317. FieldEnd = RD->field_end();
  2318. Field != FieldEnd; ++Field, ++i) {
  2319. if (*Field == MemberDecl)
  2320. break;
  2321. }
  2322. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  2323. // Compute the offset to the field
  2324. int64_t OffsetInt = RL.getFieldOffset(i) /
  2325. CGF.getContext().getCharWidth();
  2326. Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
  2327. // Save the element type.
  2328. CurrentType = MemberDecl->getType();
  2329. break;
  2330. }
  2331. case OffsetOfNode::Identifier:
  2332. llvm_unreachable("dependent __builtin_offsetof");
  2333. case OffsetOfNode::Base: {
  2334. if (ON.getBase()->isVirtual()) {
  2335. CGF.ErrorUnsupported(E, "virtual base in offsetof");
  2336. continue;
  2337. }
  2338. RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
  2339. const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
  2340. // Save the element type.
  2341. CurrentType = ON.getBase()->getType();
  2342. // Compute the offset to the base.
  2343. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  2344. CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
  2345. CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
  2346. Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
  2347. break;
  2348. }
  2349. }
  2350. Result = Builder.CreateAdd(Result, Offset);
  2351. }
  2352. return Result;
  2353. }
  2354. /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
  2355. /// argument of the sizeof expression as an integer.
  2356. Value *
  2357. ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
  2358. const UnaryExprOrTypeTraitExpr *E) {
  2359. QualType TypeToSize = E->getTypeOfArgument();
  2360. if (E->getKind() == UETT_SizeOf) {
  2361. if (const VariableArrayType *VAT =
  2362. CGF.getContext().getAsVariableArrayType(TypeToSize)) {
  2363. if (E->isArgumentType()) {
  2364. // sizeof(type) - make sure to emit the VLA size.
  2365. CGF.EmitVariablyModifiedType(TypeToSize);
  2366. } else {
  2367. // C99 6.5.3.4p2: If the argument is an expression of type
  2368. // VLA, it is evaluated.
  2369. CGF.EmitIgnoredExpr(E->getArgumentExpr());
  2370. }
  2371. auto VlaSize = CGF.getVLASize(VAT);
  2372. llvm::Value *size = VlaSize.NumElts;
  2373. // Scale the number of non-VLA elements by the non-VLA element size.
  2374. CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
  2375. if (!eltSize.isOne())
  2376. size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
  2377. return size;
  2378. }
  2379. } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
  2380. auto Alignment =
  2381. CGF.getContext()
  2382. .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
  2383. E->getTypeOfArgument()->getPointeeType()))
  2384. .getQuantity();
  2385. return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
  2386. }
  2387. // If this isn't sizeof(vla), the result must be constant; use the constant
  2388. // folding logic so we don't have to duplicate it here.
  2389. return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
  2390. }
  2391. Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
  2392. Expr *Op = E->getSubExpr();
  2393. if (Op->getType()->isAnyComplexType()) {
  2394. // If it's an l-value, load through the appropriate subobject l-value.
  2395. // Note that we have to ask E because Op might be an l-value that
  2396. // this won't work for, e.g. an Obj-C property.
  2397. if (E->isGLValue())
  2398. return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
  2399. E->getExprLoc()).getScalarVal();
  2400. // Otherwise, calculate and project.
  2401. return CGF.EmitComplexExpr(Op, false, true).first;
  2402. }
  2403. return Visit(Op);
  2404. }
  2405. Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
  2406. Expr *Op = E->getSubExpr();
  2407. if (Op->getType()->isAnyComplexType()) {
  2408. // If it's an l-value, load through the appropriate subobject l-value.
  2409. // Note that we have to ask E because Op might be an l-value that
  2410. // this won't work for, e.g. an Obj-C property.
  2411. if (Op->isGLValue())
  2412. return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
  2413. E->getExprLoc()).getScalarVal();
  2414. // Otherwise, calculate and project.
  2415. return CGF.EmitComplexExpr(Op, true, false).second;
  2416. }
  2417. // __imag on a scalar returns zero. Emit the subexpr to ensure side
  2418. // effects are evaluated, but not the actual value.
  2419. if (Op->isGLValue())
  2420. CGF.EmitLValue(Op);
  2421. else
  2422. CGF.EmitScalarExpr(Op, true);
  2423. return llvm::Constant::getNullValue(ConvertType(E->getType()));
  2424. }
  2425. //===----------------------------------------------------------------------===//
  2426. // Binary Operators
  2427. //===----------------------------------------------------------------------===//
  2428. BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
  2429. TestAndClearIgnoreResultAssign();
  2430. BinOpInfo Result;
  2431. Result.LHS = Visit(E->getLHS());
  2432. Result.RHS = Visit(E->getRHS());
  2433. Result.Ty = E->getType();
  2434. Result.Opcode = E->getOpcode();
  2435. Result.FPFeatures = E->getFPFeatures();
  2436. Result.E = E;
  2437. return Result;
  2438. }
  2439. LValue ScalarExprEmitter::EmitCompoundAssignLValue(
  2440. const CompoundAssignOperator *E,
  2441. Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
  2442. Value *&Result) {
  2443. QualType LHSTy = E->getLHS()->getType();
  2444. BinOpInfo OpInfo;
  2445. if (E->getComputationResultType()->isAnyComplexType())
  2446. return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
  2447. // Emit the RHS first. __block variables need to have the rhs evaluated
  2448. // first, plus this should improve codegen a little.
  2449. OpInfo.RHS = Visit(E->getRHS());
  2450. OpInfo.Ty = E->getComputationResultType();
  2451. OpInfo.Opcode = E->getOpcode();
  2452. OpInfo.FPFeatures = E->getFPFeatures();
  2453. OpInfo.E = E;
  2454. // Load/convert the LHS.
  2455. LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
  2456. llvm::PHINode *atomicPHI = nullptr;
  2457. if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
  2458. QualType type = atomicTy->getValueType();
  2459. if (!type->isBooleanType() && type->isIntegerType() &&
  2460. !(type->isUnsignedIntegerType() &&
  2461. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
  2462. CGF.getLangOpts().getSignedOverflowBehavior() !=
  2463. LangOptions::SOB_Trapping) {
  2464. llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
  2465. switch (OpInfo.Opcode) {
  2466. // We don't have atomicrmw operands for *, %, /, <<, >>
  2467. case BO_MulAssign: case BO_DivAssign:
  2468. case BO_RemAssign:
  2469. case BO_ShlAssign:
  2470. case BO_ShrAssign:
  2471. break;
  2472. case BO_AddAssign:
  2473. aop = llvm::AtomicRMWInst::Add;
  2474. break;
  2475. case BO_SubAssign:
  2476. aop = llvm::AtomicRMWInst::Sub;
  2477. break;
  2478. case BO_AndAssign:
  2479. aop = llvm::AtomicRMWInst::And;
  2480. break;
  2481. case BO_XorAssign:
  2482. aop = llvm::AtomicRMWInst::Xor;
  2483. break;
  2484. case BO_OrAssign:
  2485. aop = llvm::AtomicRMWInst::Or;
  2486. break;
  2487. default:
  2488. llvm_unreachable("Invalid compound assignment type");
  2489. }
  2490. if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
  2491. llvm::Value *amt = CGF.EmitToMemory(
  2492. EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
  2493. E->getExprLoc()),
  2494. LHSTy);
  2495. Builder.CreateAtomicRMW(aop, LHSLV.getPointer(), amt,
  2496. llvm::AtomicOrdering::SequentiallyConsistent);
  2497. return LHSLV;
  2498. }
  2499. }
  2500. // FIXME: For floating point types, we should be saving and restoring the
  2501. // floating point environment in the loop.
  2502. llvm::BasicBlock *startBB = Builder.GetInsertBlock();
  2503. llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
  2504. OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
  2505. OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
  2506. Builder.CreateBr(opBB);
  2507. Builder.SetInsertPoint(opBB);
  2508. atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
  2509. atomicPHI->addIncoming(OpInfo.LHS, startBB);
  2510. OpInfo.LHS = atomicPHI;
  2511. }
  2512. else
  2513. OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
  2514. SourceLocation Loc = E->getExprLoc();
  2515. OpInfo.LHS =
  2516. EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
  2517. // Expand the binary operator.
  2518. Result = (this->*Func)(OpInfo);
  2519. // Convert the result back to the LHS type,
  2520. // potentially with Implicit Conversion sanitizer check.
  2521. Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
  2522. Loc, ScalarConversionOpts(CGF.SanOpts));
  2523. if (atomicPHI) {
  2524. llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
  2525. llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
  2526. auto Pair = CGF.EmitAtomicCompareExchange(
  2527. LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
  2528. llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
  2529. llvm::Value *success = Pair.second;
  2530. atomicPHI->addIncoming(old, curBlock);
  2531. Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
  2532. Builder.SetInsertPoint(contBB);
  2533. return LHSLV;
  2534. }
  2535. // Store the result value into the LHS lvalue. Bit-fields are handled
  2536. // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
  2537. // 'An assignment expression has the value of the left operand after the
  2538. // assignment...'.
  2539. if (LHSLV.isBitField())
  2540. CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
  2541. else
  2542. CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
  2543. return LHSLV;
  2544. }
  2545. Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
  2546. Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
  2547. bool Ignore = TestAndClearIgnoreResultAssign();
  2548. Value *RHS = nullptr;
  2549. LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
  2550. // If the result is clearly ignored, return now.
  2551. if (Ignore)
  2552. return nullptr;
  2553. // The result of an assignment in C is the assigned r-value.
  2554. if (!CGF.getLangOpts().CPlusPlus)
  2555. return RHS;
  2556. // If the lvalue is non-volatile, return the computed value of the assignment.
  2557. if (!LHS.isVolatileQualified())
  2558. return RHS;
  2559. // Otherwise, reload the value.
  2560. return EmitLoadOfLValue(LHS, E->getExprLoc());
  2561. }
  2562. void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
  2563. const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
  2564. SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
  2565. if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
  2566. Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
  2567. SanitizerKind::IntegerDivideByZero));
  2568. }
  2569. const auto *BO = cast<BinaryOperator>(Ops.E);
  2570. if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
  2571. Ops.Ty->hasSignedIntegerRepresentation() &&
  2572. !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
  2573. Ops.mayHaveIntegerOverflow()) {
  2574. llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
  2575. llvm::Value *IntMin =
  2576. Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
  2577. llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
  2578. llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
  2579. llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
  2580. llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
  2581. Checks.push_back(
  2582. std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
  2583. }
  2584. if (Checks.size() > 0)
  2585. EmitBinOpCheck(Checks, Ops);
  2586. }
  2587. Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
  2588. {
  2589. CodeGenFunction::SanitizerScope SanScope(&CGF);
  2590. if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
  2591. CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
  2592. Ops.Ty->isIntegerType() &&
  2593. (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
  2594. llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
  2595. EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
  2596. } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
  2597. Ops.Ty->isRealFloatingType() &&
  2598. Ops.mayHaveFloatDivisionByZero()) {
  2599. llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
  2600. llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
  2601. EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
  2602. Ops);
  2603. }
  2604. }
  2605. if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
  2606. llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
  2607. if (CGF.getLangOpts().OpenCL &&
  2608. !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
  2609. // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
  2610. // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
  2611. // build option allows an application to specify that single precision
  2612. // floating-point divide (x/y and 1/x) and sqrt used in the program
  2613. // source are correctly rounded.
  2614. llvm::Type *ValTy = Val->getType();
  2615. if (ValTy->isFloatTy() ||
  2616. (isa<llvm::VectorType>(ValTy) &&
  2617. cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
  2618. CGF.SetFPAccuracy(Val, 2.5);
  2619. }
  2620. return Val;
  2621. }
  2622. else if (Ops.Ty->hasUnsignedIntegerRepresentation())
  2623. return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
  2624. else
  2625. return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
  2626. }
  2627. Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
  2628. // Rem in C can't be a floating point type: C99 6.5.5p2.
  2629. if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
  2630. CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
  2631. Ops.Ty->isIntegerType() &&
  2632. (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
  2633. CodeGenFunction::SanitizerScope SanScope(&CGF);
  2634. llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
  2635. EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
  2636. }
  2637. if (Ops.Ty->hasUnsignedIntegerRepresentation())
  2638. return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
  2639. else
  2640. return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
  2641. }
  2642. Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
  2643. unsigned IID;
  2644. unsigned OpID = 0;
  2645. bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
  2646. switch (Ops.Opcode) {
  2647. case BO_Add:
  2648. case BO_AddAssign:
  2649. OpID = 1;
  2650. IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
  2651. llvm::Intrinsic::uadd_with_overflow;
  2652. break;
  2653. case BO_Sub:
  2654. case BO_SubAssign:
  2655. OpID = 2;
  2656. IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
  2657. llvm::Intrinsic::usub_with_overflow;
  2658. break;
  2659. case BO_Mul:
  2660. case BO_MulAssign:
  2661. OpID = 3;
  2662. IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
  2663. llvm::Intrinsic::umul_with_overflow;
  2664. break;
  2665. default:
  2666. llvm_unreachable("Unsupported operation for overflow detection");
  2667. }
  2668. OpID <<= 1;
  2669. if (isSigned)
  2670. OpID |= 1;
  2671. CodeGenFunction::SanitizerScope SanScope(&CGF);
  2672. llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
  2673. llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
  2674. Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
  2675. Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
  2676. Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
  2677. // Handle overflow with llvm.trap if no custom handler has been specified.
  2678. const std::string *handlerName =
  2679. &CGF.getLangOpts().OverflowHandler;
  2680. if (handlerName->empty()) {
  2681. // If the signed-integer-overflow sanitizer is enabled, emit a call to its
  2682. // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
  2683. if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
  2684. llvm::Value *NotOverflow = Builder.CreateNot(overflow);
  2685. SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
  2686. : SanitizerKind::UnsignedIntegerOverflow;
  2687. EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
  2688. } else
  2689. CGF.EmitTrapCheck(Builder.CreateNot(overflow));
  2690. return result;
  2691. }
  2692. // Branch in case of overflow.
  2693. llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
  2694. llvm::BasicBlock *continueBB =
  2695. CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
  2696. llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
  2697. Builder.CreateCondBr(overflow, overflowBB, continueBB);
  2698. // If an overflow handler is set, then we want to call it and then use its
  2699. // result, if it returns.
  2700. Builder.SetInsertPoint(overflowBB);
  2701. // Get the overflow handler.
  2702. llvm::Type *Int8Ty = CGF.Int8Ty;
  2703. llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
  2704. llvm::FunctionType *handlerTy =
  2705. llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
  2706. llvm::FunctionCallee handler =
  2707. CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
  2708. // Sign extend the args to 64-bit, so that we can use the same handler for
  2709. // all types of overflow.
  2710. llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
  2711. llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
  2712. // Call the handler with the two arguments, the operation, and the size of
  2713. // the result.
  2714. llvm::Value *handlerArgs[] = {
  2715. lhs,
  2716. rhs,
  2717. Builder.getInt8(OpID),
  2718. Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
  2719. };
  2720. llvm::Value *handlerResult =
  2721. CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
  2722. // Truncate the result back to the desired size.
  2723. handlerResult = Builder.CreateTrunc(handlerResult, opTy);
  2724. Builder.CreateBr(continueBB);
  2725. Builder.SetInsertPoint(continueBB);
  2726. llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
  2727. phi->addIncoming(result, initialBB);
  2728. phi->addIncoming(handlerResult, overflowBB);
  2729. return phi;
  2730. }
  2731. /// Emit pointer + index arithmetic.
  2732. static Value *emitPointerArithmetic(CodeGenFunction &CGF,
  2733. const BinOpInfo &op,
  2734. bool isSubtraction) {
  2735. // Must have binary (not unary) expr here. Unary pointer
  2736. // increment/decrement doesn't use this path.
  2737. const BinaryOperator *expr = cast<BinaryOperator>(op.E);
  2738. Value *pointer = op.LHS;
  2739. Expr *pointerOperand = expr->getLHS();
  2740. Value *index = op.RHS;
  2741. Expr *indexOperand = expr->getRHS();
  2742. // In a subtraction, the LHS is always the pointer.
  2743. if (!isSubtraction && !pointer->getType()->isPointerTy()) {
  2744. std::swap(pointer, index);
  2745. std::swap(pointerOperand, indexOperand);
  2746. }
  2747. bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
  2748. unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
  2749. auto &DL = CGF.CGM.getDataLayout();
  2750. auto PtrTy = cast<llvm::PointerType>(pointer->getType());
  2751. // Some versions of glibc and gcc use idioms (particularly in their malloc
  2752. // routines) that add a pointer-sized integer (known to be a pointer value)
  2753. // to a null pointer in order to cast the value back to an integer or as
  2754. // part of a pointer alignment algorithm. This is undefined behavior, but
  2755. // we'd like to be able to compile programs that use it.
  2756. //
  2757. // Normally, we'd generate a GEP with a null-pointer base here in response
  2758. // to that code, but it's also UB to dereference a pointer created that
  2759. // way. Instead (as an acknowledged hack to tolerate the idiom) we will
  2760. // generate a direct cast of the integer value to a pointer.
  2761. //
  2762. // The idiom (p = nullptr + N) is not met if any of the following are true:
  2763. //
  2764. // The operation is subtraction.
  2765. // The index is not pointer-sized.
  2766. // The pointer type is not byte-sized.
  2767. //
  2768. if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
  2769. op.Opcode,
  2770. expr->getLHS(),
  2771. expr->getRHS()))
  2772. return CGF.Builder.CreateIntToPtr(index, pointer->getType());
  2773. if (width != DL.getTypeSizeInBits(PtrTy)) {
  2774. // Zero-extend or sign-extend the pointer value according to
  2775. // whether the index is signed or not.
  2776. index = CGF.Builder.CreateIntCast(index, DL.getIntPtrType(PtrTy), isSigned,
  2777. "idx.ext");
  2778. }
  2779. // If this is subtraction, negate the index.
  2780. if (isSubtraction)
  2781. index = CGF.Builder.CreateNeg(index, "idx.neg");
  2782. if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
  2783. CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
  2784. /*Accessed*/ false);
  2785. const PointerType *pointerType
  2786. = pointerOperand->getType()->getAs<PointerType>();
  2787. if (!pointerType) {
  2788. QualType objectType = pointerOperand->getType()
  2789. ->castAs<ObjCObjectPointerType>()
  2790. ->getPointeeType();
  2791. llvm::Value *objectSize
  2792. = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
  2793. index = CGF.Builder.CreateMul(index, objectSize);
  2794. Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
  2795. result = CGF.Builder.CreateGEP(result, index, "add.ptr");
  2796. return CGF.Builder.CreateBitCast(result, pointer->getType());
  2797. }
  2798. QualType elementType = pointerType->getPointeeType();
  2799. if (const VariableArrayType *vla
  2800. = CGF.getContext().getAsVariableArrayType(elementType)) {
  2801. // The element count here is the total number of non-VLA elements.
  2802. llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
  2803. // Effectively, the multiply by the VLA size is part of the GEP.
  2804. // GEP indexes are signed, and scaling an index isn't permitted to
  2805. // signed-overflow, so we use the same semantics for our explicit
  2806. // multiply. We suppress this if overflow is not undefined behavior.
  2807. if (CGF.getLangOpts().isSignedOverflowDefined()) {
  2808. index = CGF.Builder.CreateMul(index, numElements, "vla.index");
  2809. pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
  2810. } else {
  2811. index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
  2812. pointer =
  2813. CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
  2814. op.E->getExprLoc(), "add.ptr");
  2815. }
  2816. return pointer;
  2817. }
  2818. // Explicitly handle GNU void* and function pointer arithmetic extensions. The
  2819. // GNU void* casts amount to no-ops since our void* type is i8*, but this is
  2820. // future proof.
  2821. if (elementType->isVoidType() || elementType->isFunctionType()) {
  2822. Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
  2823. result = CGF.Builder.CreateGEP(result, index, "add.ptr");
  2824. return CGF.Builder.CreateBitCast(result, pointer->getType());
  2825. }
  2826. if (CGF.getLangOpts().isSignedOverflowDefined())
  2827. return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
  2828. return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
  2829. op.E->getExprLoc(), "add.ptr");
  2830. }
  2831. // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
  2832. // Addend. Use negMul and negAdd to negate the first operand of the Mul or
  2833. // the add operand respectively. This allows fmuladd to represent a*b-c, or
  2834. // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
  2835. // efficient operations.
  2836. static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
  2837. const CodeGenFunction &CGF, CGBuilderTy &Builder,
  2838. bool negMul, bool negAdd) {
  2839. assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
  2840. Value *MulOp0 = MulOp->getOperand(0);
  2841. Value *MulOp1 = MulOp->getOperand(1);
  2842. if (negMul) {
  2843. MulOp0 =
  2844. Builder.CreateFSub(
  2845. llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
  2846. "neg");
  2847. } else if (negAdd) {
  2848. Addend =
  2849. Builder.CreateFSub(
  2850. llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
  2851. "neg");
  2852. }
  2853. Value *FMulAdd = Builder.CreateCall(
  2854. CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
  2855. {MulOp0, MulOp1, Addend});
  2856. MulOp->eraseFromParent();
  2857. return FMulAdd;
  2858. }
  2859. // Check whether it would be legal to emit an fmuladd intrinsic call to
  2860. // represent op and if so, build the fmuladd.
  2861. //
  2862. // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
  2863. // Does NOT check the type of the operation - it's assumed that this function
  2864. // will be called from contexts where it's known that the type is contractable.
  2865. static Value* tryEmitFMulAdd(const BinOpInfo &op,
  2866. const CodeGenFunction &CGF, CGBuilderTy &Builder,
  2867. bool isSub=false) {
  2868. assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
  2869. op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
  2870. "Only fadd/fsub can be the root of an fmuladd.");
  2871. // Check whether this op is marked as fusable.
  2872. if (!op.FPFeatures.allowFPContractWithinStatement())
  2873. return nullptr;
  2874. // We have a potentially fusable op. Look for a mul on one of the operands.
  2875. // Also, make sure that the mul result isn't used directly. In that case,
  2876. // there's no point creating a muladd operation.
  2877. if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
  2878. if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
  2879. LHSBinOp->use_empty())
  2880. return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
  2881. }
  2882. if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
  2883. if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
  2884. RHSBinOp->use_empty())
  2885. return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
  2886. }
  2887. return nullptr;
  2888. }
  2889. Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
  2890. if (op.LHS->getType()->isPointerTy() ||
  2891. op.RHS->getType()->isPointerTy())
  2892. return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
  2893. if (op.Ty->isSignedIntegerOrEnumerationType()) {
  2894. switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
  2895. case LangOptions::SOB_Defined:
  2896. return Builder.CreateAdd(op.LHS, op.RHS, "add");
  2897. case LangOptions::SOB_Undefined:
  2898. if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
  2899. return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
  2900. LLVM_FALLTHROUGH;
  2901. case LangOptions::SOB_Trapping:
  2902. if (CanElideOverflowCheck(CGF.getContext(), op))
  2903. return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
  2904. return EmitOverflowCheckedBinOp(op);
  2905. }
  2906. }
  2907. if (op.Ty->isUnsignedIntegerType() &&
  2908. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
  2909. !CanElideOverflowCheck(CGF.getContext(), op))
  2910. return EmitOverflowCheckedBinOp(op);
  2911. if (op.LHS->getType()->isFPOrFPVectorTy()) {
  2912. // Try to form an fmuladd.
  2913. if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
  2914. return FMulAdd;
  2915. Value *V = Builder.CreateFAdd(op.LHS, op.RHS, "add");
  2916. return propagateFMFlags(V, op);
  2917. }
  2918. if (op.isFixedPointBinOp())
  2919. return EmitFixedPointBinOp(op);
  2920. return Builder.CreateAdd(op.LHS, op.RHS, "add");
  2921. }
  2922. /// The resulting value must be calculated with exact precision, so the operands
  2923. /// may not be the same type.
  2924. Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
  2925. using llvm::APSInt;
  2926. using llvm::ConstantInt;
  2927. const auto *BinOp = cast<BinaryOperator>(op.E);
  2928. // The result is a fixed point type and at least one of the operands is fixed
  2929. // point while the other is either fixed point or an int. This resulting type
  2930. // should be determined by Sema::handleFixedPointConversions().
  2931. QualType ResultTy = op.Ty;
  2932. QualType LHSTy = BinOp->getLHS()->getType();
  2933. QualType RHSTy = BinOp->getRHS()->getType();
  2934. ASTContext &Ctx = CGF.getContext();
  2935. Value *LHS = op.LHS;
  2936. Value *RHS = op.RHS;
  2937. auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
  2938. auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
  2939. auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
  2940. auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
  2941. // Convert the operands to the full precision type.
  2942. Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema,
  2943. BinOp->getExprLoc());
  2944. Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema,
  2945. BinOp->getExprLoc());
  2946. // Perform the actual addition.
  2947. Value *Result;
  2948. switch (BinOp->getOpcode()) {
  2949. case BO_Add: {
  2950. if (ResultFixedSema.isSaturated()) {
  2951. llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
  2952. ? llvm::Intrinsic::sadd_sat
  2953. : llvm::Intrinsic::uadd_sat;
  2954. Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
  2955. } else {
  2956. Result = Builder.CreateAdd(FullLHS, FullRHS);
  2957. }
  2958. break;
  2959. }
  2960. case BO_Sub: {
  2961. if (ResultFixedSema.isSaturated()) {
  2962. llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
  2963. ? llvm::Intrinsic::ssub_sat
  2964. : llvm::Intrinsic::usub_sat;
  2965. Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
  2966. } else {
  2967. Result = Builder.CreateSub(FullLHS, FullRHS);
  2968. }
  2969. break;
  2970. }
  2971. case BO_LT:
  2972. return CommonFixedSema.isSigned() ? Builder.CreateICmpSLT(FullLHS, FullRHS)
  2973. : Builder.CreateICmpULT(FullLHS, FullRHS);
  2974. case BO_GT:
  2975. return CommonFixedSema.isSigned() ? Builder.CreateICmpSGT(FullLHS, FullRHS)
  2976. : Builder.CreateICmpUGT(FullLHS, FullRHS);
  2977. case BO_LE:
  2978. return CommonFixedSema.isSigned() ? Builder.CreateICmpSLE(FullLHS, FullRHS)
  2979. : Builder.CreateICmpULE(FullLHS, FullRHS);
  2980. case BO_GE:
  2981. return CommonFixedSema.isSigned() ? Builder.CreateICmpSGE(FullLHS, FullRHS)
  2982. : Builder.CreateICmpUGE(FullLHS, FullRHS);
  2983. case BO_EQ:
  2984. // For equality operations, we assume any padding bits on unsigned types are
  2985. // zero'd out. They could be overwritten through non-saturating operations
  2986. // that cause overflow, but this leads to undefined behavior.
  2987. return Builder.CreateICmpEQ(FullLHS, FullRHS);
  2988. case BO_NE:
  2989. return Builder.CreateICmpNE(FullLHS, FullRHS);
  2990. case BO_Mul:
  2991. case BO_Div:
  2992. case BO_Shl:
  2993. case BO_Shr:
  2994. case BO_Cmp:
  2995. case BO_LAnd:
  2996. case BO_LOr:
  2997. case BO_MulAssign:
  2998. case BO_DivAssign:
  2999. case BO_AddAssign:
  3000. case BO_SubAssign:
  3001. case BO_ShlAssign:
  3002. case BO_ShrAssign:
  3003. llvm_unreachable("Found unimplemented fixed point binary operation");
  3004. case BO_PtrMemD:
  3005. case BO_PtrMemI:
  3006. case BO_Rem:
  3007. case BO_Xor:
  3008. case BO_And:
  3009. case BO_Or:
  3010. case BO_Assign:
  3011. case BO_RemAssign:
  3012. case BO_AndAssign:
  3013. case BO_XorAssign:
  3014. case BO_OrAssign:
  3015. case BO_Comma:
  3016. llvm_unreachable("Found unsupported binary operation for fixed point types.");
  3017. }
  3018. // Convert to the result type.
  3019. return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema,
  3020. BinOp->getExprLoc());
  3021. }
  3022. Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
  3023. // The LHS is always a pointer if either side is.
  3024. if (!op.LHS->getType()->isPointerTy()) {
  3025. if (op.Ty->isSignedIntegerOrEnumerationType()) {
  3026. switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
  3027. case LangOptions::SOB_Defined:
  3028. return Builder.CreateSub(op.LHS, op.RHS, "sub");
  3029. case LangOptions::SOB_Undefined:
  3030. if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
  3031. return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
  3032. LLVM_FALLTHROUGH;
  3033. case LangOptions::SOB_Trapping:
  3034. if (CanElideOverflowCheck(CGF.getContext(), op))
  3035. return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
  3036. return EmitOverflowCheckedBinOp(op);
  3037. }
  3038. }
  3039. if (op.Ty->isUnsignedIntegerType() &&
  3040. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
  3041. !CanElideOverflowCheck(CGF.getContext(), op))
  3042. return EmitOverflowCheckedBinOp(op);
  3043. if (op.LHS->getType()->isFPOrFPVectorTy()) {
  3044. // Try to form an fmuladd.
  3045. if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
  3046. return FMulAdd;
  3047. Value *V = Builder.CreateFSub(op.LHS, op.RHS, "sub");
  3048. return propagateFMFlags(V, op);
  3049. }
  3050. if (op.isFixedPointBinOp())
  3051. return EmitFixedPointBinOp(op);
  3052. return Builder.CreateSub(op.LHS, op.RHS, "sub");
  3053. }
  3054. // If the RHS is not a pointer, then we have normal pointer
  3055. // arithmetic.
  3056. if (!op.RHS->getType()->isPointerTy())
  3057. return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
  3058. // Otherwise, this is a pointer subtraction.
  3059. // Do the raw subtraction part.
  3060. llvm::Value *LHS
  3061. = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
  3062. llvm::Value *RHS
  3063. = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
  3064. Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
  3065. // Okay, figure out the element size.
  3066. const BinaryOperator *expr = cast<BinaryOperator>(op.E);
  3067. QualType elementType = expr->getLHS()->getType()->getPointeeType();
  3068. llvm::Value *divisor = nullptr;
  3069. // For a variable-length array, this is going to be non-constant.
  3070. if (const VariableArrayType *vla
  3071. = CGF.getContext().getAsVariableArrayType(elementType)) {
  3072. auto VlaSize = CGF.getVLASize(vla);
  3073. elementType = VlaSize.Type;
  3074. divisor = VlaSize.NumElts;
  3075. // Scale the number of non-VLA elements by the non-VLA element size.
  3076. CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
  3077. if (!eltSize.isOne())
  3078. divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
  3079. // For everything elese, we can just compute it, safe in the
  3080. // assumption that Sema won't let anything through that we can't
  3081. // safely compute the size of.
  3082. } else {
  3083. CharUnits elementSize;
  3084. // Handle GCC extension for pointer arithmetic on void* and
  3085. // function pointer types.
  3086. if (elementType->isVoidType() || elementType->isFunctionType())
  3087. elementSize = CharUnits::One();
  3088. else
  3089. elementSize = CGF.getContext().getTypeSizeInChars(elementType);
  3090. // Don't even emit the divide for element size of 1.
  3091. if (elementSize.isOne())
  3092. return diffInChars;
  3093. divisor = CGF.CGM.getSize(elementSize);
  3094. }
  3095. // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
  3096. // pointer difference in C is only defined in the case where both operands
  3097. // are pointing to elements of an array.
  3098. return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
  3099. }
  3100. Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
  3101. llvm::IntegerType *Ty;
  3102. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
  3103. Ty = cast<llvm::IntegerType>(VT->getElementType());
  3104. else
  3105. Ty = cast<llvm::IntegerType>(LHS->getType());
  3106. return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
  3107. }
  3108. Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
  3109. // LLVM requires the LHS and RHS to be the same type: promote or truncate the
  3110. // RHS to the same size as the LHS.
  3111. Value *RHS = Ops.RHS;
  3112. if (Ops.LHS->getType() != RHS->getType())
  3113. RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
  3114. bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
  3115. Ops.Ty->hasSignedIntegerRepresentation() &&
  3116. !CGF.getLangOpts().isSignedOverflowDefined() &&
  3117. !CGF.getLangOpts().CPlusPlus2a;
  3118. bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
  3119. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  3120. if (CGF.getLangOpts().OpenCL)
  3121. RHS =
  3122. Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
  3123. else if ((SanitizeBase || SanitizeExponent) &&
  3124. isa<llvm::IntegerType>(Ops.LHS->getType())) {
  3125. CodeGenFunction::SanitizerScope SanScope(&CGF);
  3126. SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
  3127. llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
  3128. llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
  3129. if (SanitizeExponent) {
  3130. Checks.push_back(
  3131. std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
  3132. }
  3133. if (SanitizeBase) {
  3134. // Check whether we are shifting any non-zero bits off the top of the
  3135. // integer. We only emit this check if exponent is valid - otherwise
  3136. // instructions below will have undefined behavior themselves.
  3137. llvm::BasicBlock *Orig = Builder.GetInsertBlock();
  3138. llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
  3139. llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
  3140. Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
  3141. llvm::Value *PromotedWidthMinusOne =
  3142. (RHS == Ops.RHS) ? WidthMinusOne
  3143. : GetWidthMinusOneValue(Ops.LHS, RHS);
  3144. CGF.EmitBlock(CheckShiftBase);
  3145. llvm::Value *BitsShiftedOff = Builder.CreateLShr(
  3146. Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
  3147. /*NUW*/ true, /*NSW*/ true),
  3148. "shl.check");
  3149. if (CGF.getLangOpts().CPlusPlus) {
  3150. // In C99, we are not permitted to shift a 1 bit into the sign bit.
  3151. // Under C++11's rules, shifting a 1 bit into the sign bit is
  3152. // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
  3153. // define signed left shifts, so we use the C99 and C++11 rules there).
  3154. llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
  3155. BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
  3156. }
  3157. llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
  3158. llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
  3159. CGF.EmitBlock(Cont);
  3160. llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
  3161. BaseCheck->addIncoming(Builder.getTrue(), Orig);
  3162. BaseCheck->addIncoming(ValidBase, CheckShiftBase);
  3163. Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
  3164. }
  3165. assert(!Checks.empty());
  3166. EmitBinOpCheck(Checks, Ops);
  3167. }
  3168. return Builder.CreateShl(Ops.LHS, RHS, "shl");
  3169. }
  3170. Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
  3171. // LLVM requires the LHS and RHS to be the same type: promote or truncate the
  3172. // RHS to the same size as the LHS.
  3173. Value *RHS = Ops.RHS;
  3174. if (Ops.LHS->getType() != RHS->getType())
  3175. RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
  3176. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  3177. if (CGF.getLangOpts().OpenCL)
  3178. RHS =
  3179. Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
  3180. else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
  3181. isa<llvm::IntegerType>(Ops.LHS->getType())) {
  3182. CodeGenFunction::SanitizerScope SanScope(&CGF);
  3183. llvm::Value *Valid =
  3184. Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
  3185. EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
  3186. }
  3187. if (Ops.Ty->hasUnsignedIntegerRepresentation())
  3188. return Builder.CreateLShr(Ops.LHS, RHS, "shr");
  3189. return Builder.CreateAShr(Ops.LHS, RHS, "shr");
  3190. }
  3191. enum IntrinsicType { VCMPEQ, VCMPGT };
  3192. // return corresponding comparison intrinsic for given vector type
  3193. static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
  3194. BuiltinType::Kind ElemKind) {
  3195. switch (ElemKind) {
  3196. default: llvm_unreachable("unexpected element type");
  3197. case BuiltinType::Char_U:
  3198. case BuiltinType::UChar:
  3199. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
  3200. llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
  3201. case BuiltinType::Char_S:
  3202. case BuiltinType::SChar:
  3203. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
  3204. llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
  3205. case BuiltinType::UShort:
  3206. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
  3207. llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
  3208. case BuiltinType::Short:
  3209. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
  3210. llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
  3211. case BuiltinType::UInt:
  3212. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
  3213. llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
  3214. case BuiltinType::Int:
  3215. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
  3216. llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
  3217. case BuiltinType::ULong:
  3218. case BuiltinType::ULongLong:
  3219. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
  3220. llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
  3221. case BuiltinType::Long:
  3222. case BuiltinType::LongLong:
  3223. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
  3224. llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
  3225. case BuiltinType::Float:
  3226. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
  3227. llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
  3228. case BuiltinType::Double:
  3229. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
  3230. llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
  3231. }
  3232. }
  3233. Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
  3234. llvm::CmpInst::Predicate UICmpOpc,
  3235. llvm::CmpInst::Predicate SICmpOpc,
  3236. llvm::CmpInst::Predicate FCmpOpc) {
  3237. TestAndClearIgnoreResultAssign();
  3238. Value *Result;
  3239. QualType LHSTy = E->getLHS()->getType();
  3240. QualType RHSTy = E->getRHS()->getType();
  3241. if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
  3242. assert(E->getOpcode() == BO_EQ ||
  3243. E->getOpcode() == BO_NE);
  3244. Value *LHS = CGF.EmitScalarExpr(E->getLHS());
  3245. Value *RHS = CGF.EmitScalarExpr(E->getRHS());
  3246. Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
  3247. CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
  3248. } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
  3249. BinOpInfo BOInfo = EmitBinOps(E);
  3250. Value *LHS = BOInfo.LHS;
  3251. Value *RHS = BOInfo.RHS;
  3252. // If AltiVec, the comparison results in a numeric type, so we use
  3253. // intrinsics comparing vectors and giving 0 or 1 as a result
  3254. if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
  3255. // constants for mapping CR6 register bits to predicate result
  3256. enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
  3257. llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
  3258. // in several cases vector arguments order will be reversed
  3259. Value *FirstVecArg = LHS,
  3260. *SecondVecArg = RHS;
  3261. QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
  3262. const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
  3263. BuiltinType::Kind ElementKind = BTy->getKind();
  3264. switch(E->getOpcode()) {
  3265. default: llvm_unreachable("is not a comparison operation");
  3266. case BO_EQ:
  3267. CR6 = CR6_LT;
  3268. ID = GetIntrinsic(VCMPEQ, ElementKind);
  3269. break;
  3270. case BO_NE:
  3271. CR6 = CR6_EQ;
  3272. ID = GetIntrinsic(VCMPEQ, ElementKind);
  3273. break;
  3274. case BO_LT:
  3275. CR6 = CR6_LT;
  3276. ID = GetIntrinsic(VCMPGT, ElementKind);
  3277. std::swap(FirstVecArg, SecondVecArg);
  3278. break;
  3279. case BO_GT:
  3280. CR6 = CR6_LT;
  3281. ID = GetIntrinsic(VCMPGT, ElementKind);
  3282. break;
  3283. case BO_LE:
  3284. if (ElementKind == BuiltinType::Float) {
  3285. CR6 = CR6_LT;
  3286. ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
  3287. std::swap(FirstVecArg, SecondVecArg);
  3288. }
  3289. else {
  3290. CR6 = CR6_EQ;
  3291. ID = GetIntrinsic(VCMPGT, ElementKind);
  3292. }
  3293. break;
  3294. case BO_GE:
  3295. if (ElementKind == BuiltinType::Float) {
  3296. CR6 = CR6_LT;
  3297. ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
  3298. }
  3299. else {
  3300. CR6 = CR6_EQ;
  3301. ID = GetIntrinsic(VCMPGT, ElementKind);
  3302. std::swap(FirstVecArg, SecondVecArg);
  3303. }
  3304. break;
  3305. }
  3306. Value *CR6Param = Builder.getInt32(CR6);
  3307. llvm::Function *F = CGF.CGM.getIntrinsic(ID);
  3308. Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
  3309. // The result type of intrinsic may not be same as E->getType().
  3310. // If E->getType() is not BoolTy, EmitScalarConversion will do the
  3311. // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
  3312. // do nothing, if ResultTy is not i1 at the same time, it will cause
  3313. // crash later.
  3314. llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
  3315. if (ResultTy->getBitWidth() > 1 &&
  3316. E->getType() == CGF.getContext().BoolTy)
  3317. Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
  3318. return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
  3319. E->getExprLoc());
  3320. }
  3321. if (BOInfo.isFixedPointBinOp()) {
  3322. Result = EmitFixedPointBinOp(BOInfo);
  3323. } else if (LHS->getType()->isFPOrFPVectorTy()) {
  3324. Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
  3325. } else if (LHSTy->hasSignedIntegerRepresentation()) {
  3326. Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
  3327. } else {
  3328. // Unsigned integers and pointers.
  3329. if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
  3330. !isa<llvm::ConstantPointerNull>(LHS) &&
  3331. !isa<llvm::ConstantPointerNull>(RHS)) {
  3332. // Dynamic information is required to be stripped for comparisons,
  3333. // because it could leak the dynamic information. Based on comparisons
  3334. // of pointers to dynamic objects, the optimizer can replace one pointer
  3335. // with another, which might be incorrect in presence of invariant
  3336. // groups. Comparison with null is safe because null does not carry any
  3337. // dynamic information.
  3338. if (LHSTy.mayBeDynamicClass())
  3339. LHS = Builder.CreateStripInvariantGroup(LHS);
  3340. if (RHSTy.mayBeDynamicClass())
  3341. RHS = Builder.CreateStripInvariantGroup(RHS);
  3342. }
  3343. Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
  3344. }
  3345. // If this is a vector comparison, sign extend the result to the appropriate
  3346. // vector integer type and return it (don't convert to bool).
  3347. if (LHSTy->isVectorType())
  3348. return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
  3349. } else {
  3350. // Complex Comparison: can only be an equality comparison.
  3351. CodeGenFunction::ComplexPairTy LHS, RHS;
  3352. QualType CETy;
  3353. if (auto *CTy = LHSTy->getAs<ComplexType>()) {
  3354. LHS = CGF.EmitComplexExpr(E->getLHS());
  3355. CETy = CTy->getElementType();
  3356. } else {
  3357. LHS.first = Visit(E->getLHS());
  3358. LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
  3359. CETy = LHSTy;
  3360. }
  3361. if (auto *CTy = RHSTy->getAs<ComplexType>()) {
  3362. RHS = CGF.EmitComplexExpr(E->getRHS());
  3363. assert(CGF.getContext().hasSameUnqualifiedType(CETy,
  3364. CTy->getElementType()) &&
  3365. "The element types must always match.");
  3366. (void)CTy;
  3367. } else {
  3368. RHS.first = Visit(E->getRHS());
  3369. RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
  3370. assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
  3371. "The element types must always match.");
  3372. }
  3373. Value *ResultR, *ResultI;
  3374. if (CETy->isRealFloatingType()) {
  3375. ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
  3376. ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
  3377. } else {
  3378. // Complex comparisons can only be equality comparisons. As such, signed
  3379. // and unsigned opcodes are the same.
  3380. ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
  3381. ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
  3382. }
  3383. if (E->getOpcode() == BO_EQ) {
  3384. Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
  3385. } else {
  3386. assert(E->getOpcode() == BO_NE &&
  3387. "Complex comparison other than == or != ?");
  3388. Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
  3389. }
  3390. }
  3391. return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
  3392. E->getExprLoc());
  3393. }
  3394. Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
  3395. bool Ignore = TestAndClearIgnoreResultAssign();
  3396. Value *RHS;
  3397. LValue LHS;
  3398. switch (E->getLHS()->getType().getObjCLifetime()) {
  3399. case Qualifiers::OCL_Strong:
  3400. std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
  3401. break;
  3402. case Qualifiers::OCL_Autoreleasing:
  3403. std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
  3404. break;
  3405. case Qualifiers::OCL_ExplicitNone:
  3406. std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
  3407. break;
  3408. case Qualifiers::OCL_Weak:
  3409. RHS = Visit(E->getRHS());
  3410. LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
  3411. RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
  3412. break;
  3413. case Qualifiers::OCL_None:
  3414. // __block variables need to have the rhs evaluated first, plus
  3415. // this should improve codegen just a little.
  3416. RHS = Visit(E->getRHS());
  3417. LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
  3418. // Store the value into the LHS. Bit-fields are handled specially
  3419. // because the result is altered by the store, i.e., [C99 6.5.16p1]
  3420. // 'An assignment expression has the value of the left operand after
  3421. // the assignment...'.
  3422. if (LHS.isBitField()) {
  3423. CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
  3424. } else {
  3425. CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
  3426. CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
  3427. }
  3428. }
  3429. // If the result is clearly ignored, return now.
  3430. if (Ignore)
  3431. return nullptr;
  3432. // The result of an assignment in C is the assigned r-value.
  3433. if (!CGF.getLangOpts().CPlusPlus)
  3434. return RHS;
  3435. // If the lvalue is non-volatile, return the computed value of the assignment.
  3436. if (!LHS.isVolatileQualified())
  3437. return RHS;
  3438. // Otherwise, reload the value.
  3439. return EmitLoadOfLValue(LHS, E->getExprLoc());
  3440. }
  3441. Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
  3442. // Perform vector logical and on comparisons with zero vectors.
  3443. if (E->getType()->isVectorType()) {
  3444. CGF.incrementProfileCounter(E);
  3445. Value *LHS = Visit(E->getLHS());
  3446. Value *RHS = Visit(E->getRHS());
  3447. Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
  3448. if (LHS->getType()->isFPOrFPVectorTy()) {
  3449. LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
  3450. RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
  3451. } else {
  3452. LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
  3453. RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
  3454. }
  3455. Value *And = Builder.CreateAnd(LHS, RHS);
  3456. return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
  3457. }
  3458. llvm::Type *ResTy = ConvertType(E->getType());
  3459. // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
  3460. // If we have 1 && X, just emit X without inserting the control flow.
  3461. bool LHSCondVal;
  3462. if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
  3463. if (LHSCondVal) { // If we have 1 && X, just emit X.
  3464. CGF.incrementProfileCounter(E);
  3465. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  3466. // ZExt result to int or bool.
  3467. return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
  3468. }
  3469. // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
  3470. if (!CGF.ContainsLabel(E->getRHS()))
  3471. return llvm::Constant::getNullValue(ResTy);
  3472. }
  3473. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
  3474. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
  3475. CodeGenFunction::ConditionalEvaluation eval(CGF);
  3476. // Branch on the LHS first. If it is false, go to the failure (cont) block.
  3477. CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
  3478. CGF.getProfileCount(E->getRHS()));
  3479. // Any edges into the ContBlock are now from an (indeterminate number of)
  3480. // edges from this first condition. All of these values will be false. Start
  3481. // setting up the PHI node in the Cont Block for this.
  3482. llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
  3483. "", ContBlock);
  3484. for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
  3485. PI != PE; ++PI)
  3486. PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
  3487. eval.begin(CGF);
  3488. CGF.EmitBlock(RHSBlock);
  3489. CGF.incrementProfileCounter(E);
  3490. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  3491. eval.end(CGF);
  3492. // Reaquire the RHS block, as there may be subblocks inserted.
  3493. RHSBlock = Builder.GetInsertBlock();
  3494. // Emit an unconditional branch from this block to ContBlock.
  3495. {
  3496. // There is no need to emit line number for unconditional branch.
  3497. auto NL = ApplyDebugLocation::CreateEmpty(CGF);
  3498. CGF.EmitBlock(ContBlock);
  3499. }
  3500. // Insert an entry into the phi node for the edge with the value of RHSCond.
  3501. PN->addIncoming(RHSCond, RHSBlock);
  3502. // Artificial location to preserve the scope information
  3503. {
  3504. auto NL = ApplyDebugLocation::CreateArtificial(CGF);
  3505. PN->setDebugLoc(Builder.getCurrentDebugLocation());
  3506. }
  3507. // ZExt result to int.
  3508. return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
  3509. }
  3510. Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
  3511. // Perform vector logical or on comparisons with zero vectors.
  3512. if (E->getType()->isVectorType()) {
  3513. CGF.incrementProfileCounter(E);
  3514. Value *LHS = Visit(E->getLHS());
  3515. Value *RHS = Visit(E->getRHS());
  3516. Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
  3517. if (LHS->getType()->isFPOrFPVectorTy()) {
  3518. LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
  3519. RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
  3520. } else {
  3521. LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
  3522. RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
  3523. }
  3524. Value *Or = Builder.CreateOr(LHS, RHS);
  3525. return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
  3526. }
  3527. llvm::Type *ResTy = ConvertType(E->getType());
  3528. // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
  3529. // If we have 0 || X, just emit X without inserting the control flow.
  3530. bool LHSCondVal;
  3531. if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
  3532. if (!LHSCondVal) { // If we have 0 || X, just emit X.
  3533. CGF.incrementProfileCounter(E);
  3534. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  3535. // ZExt result to int or bool.
  3536. return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
  3537. }
  3538. // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
  3539. if (!CGF.ContainsLabel(E->getRHS()))
  3540. return llvm::ConstantInt::get(ResTy, 1);
  3541. }
  3542. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
  3543. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
  3544. CodeGenFunction::ConditionalEvaluation eval(CGF);
  3545. // Branch on the LHS first. If it is true, go to the success (cont) block.
  3546. CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
  3547. CGF.getCurrentProfileCount() -
  3548. CGF.getProfileCount(E->getRHS()));
  3549. // Any edges into the ContBlock are now from an (indeterminate number of)
  3550. // edges from this first condition. All of these values will be true. Start
  3551. // setting up the PHI node in the Cont Block for this.
  3552. llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
  3553. "", ContBlock);
  3554. for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
  3555. PI != PE; ++PI)
  3556. PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
  3557. eval.begin(CGF);
  3558. // Emit the RHS condition as a bool value.
  3559. CGF.EmitBlock(RHSBlock);
  3560. CGF.incrementProfileCounter(E);
  3561. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  3562. eval.end(CGF);
  3563. // Reaquire the RHS block, as there may be subblocks inserted.
  3564. RHSBlock = Builder.GetInsertBlock();
  3565. // Emit an unconditional branch from this block to ContBlock. Insert an entry
  3566. // into the phi node for the edge with the value of RHSCond.
  3567. CGF.EmitBlock(ContBlock);
  3568. PN->addIncoming(RHSCond, RHSBlock);
  3569. // ZExt result to int.
  3570. return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
  3571. }
  3572. Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
  3573. CGF.EmitIgnoredExpr(E->getLHS());
  3574. CGF.EnsureInsertPoint();
  3575. return Visit(E->getRHS());
  3576. }
  3577. //===----------------------------------------------------------------------===//
  3578. // Other Operators
  3579. //===----------------------------------------------------------------------===//
  3580. /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
  3581. /// expression is cheap enough and side-effect-free enough to evaluate
  3582. /// unconditionally instead of conditionally. This is used to convert control
  3583. /// flow into selects in some cases.
  3584. static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
  3585. CodeGenFunction &CGF) {
  3586. // Anything that is an integer or floating point constant is fine.
  3587. return E->IgnoreParens()->isEvaluatable(CGF.getContext());
  3588. // Even non-volatile automatic variables can't be evaluated unconditionally.
  3589. // Referencing a thread_local may cause non-trivial initialization work to
  3590. // occur. If we're inside a lambda and one of the variables is from the scope
  3591. // outside the lambda, that function may have returned already. Reading its
  3592. // locals is a bad idea. Also, these reads may introduce races there didn't
  3593. // exist in the source-level program.
  3594. }
  3595. Value *ScalarExprEmitter::
  3596. VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  3597. TestAndClearIgnoreResultAssign();
  3598. // Bind the common expression if necessary.
  3599. CodeGenFunction::OpaqueValueMapping binding(CGF, E);
  3600. Expr *condExpr = E->getCond();
  3601. Expr *lhsExpr = E->getTrueExpr();
  3602. Expr *rhsExpr = E->getFalseExpr();
  3603. // If the condition constant folds and can be elided, try to avoid emitting
  3604. // the condition and the dead arm.
  3605. bool CondExprBool;
  3606. if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
  3607. Expr *live = lhsExpr, *dead = rhsExpr;
  3608. if (!CondExprBool) std::swap(live, dead);
  3609. // If the dead side doesn't have labels we need, just emit the Live part.
  3610. if (!CGF.ContainsLabel(dead)) {
  3611. if (CondExprBool)
  3612. CGF.incrementProfileCounter(E);
  3613. Value *Result = Visit(live);
  3614. // If the live part is a throw expression, it acts like it has a void
  3615. // type, so evaluating it returns a null Value*. However, a conditional
  3616. // with non-void type must return a non-null Value*.
  3617. if (!Result && !E->getType()->isVoidType())
  3618. Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
  3619. return Result;
  3620. }
  3621. }
  3622. // OpenCL: If the condition is a vector, we can treat this condition like
  3623. // the select function.
  3624. if (CGF.getLangOpts().OpenCL
  3625. && condExpr->getType()->isVectorType()) {
  3626. CGF.incrementProfileCounter(E);
  3627. llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
  3628. llvm::Value *LHS = Visit(lhsExpr);
  3629. llvm::Value *RHS = Visit(rhsExpr);
  3630. llvm::Type *condType = ConvertType(condExpr->getType());
  3631. llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
  3632. unsigned numElem = vecTy->getNumElements();
  3633. llvm::Type *elemType = vecTy->getElementType();
  3634. llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
  3635. llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
  3636. llvm::Value *tmp = Builder.CreateSExt(TestMSB,
  3637. llvm::VectorType::get(elemType,
  3638. numElem),
  3639. "sext");
  3640. llvm::Value *tmp2 = Builder.CreateNot(tmp);
  3641. // Cast float to int to perform ANDs if necessary.
  3642. llvm::Value *RHSTmp = RHS;
  3643. llvm::Value *LHSTmp = LHS;
  3644. bool wasCast = false;
  3645. llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
  3646. if (rhsVTy->getElementType()->isFloatingPointTy()) {
  3647. RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
  3648. LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
  3649. wasCast = true;
  3650. }
  3651. llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
  3652. llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
  3653. llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
  3654. if (wasCast)
  3655. tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
  3656. return tmp5;
  3657. }
  3658. // If this is a really simple expression (like x ? 4 : 5), emit this as a
  3659. // select instead of as control flow. We can only do this if it is cheap and
  3660. // safe to evaluate the LHS and RHS unconditionally.
  3661. if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
  3662. isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
  3663. llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
  3664. llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
  3665. CGF.incrementProfileCounter(E, StepV);
  3666. llvm::Value *LHS = Visit(lhsExpr);
  3667. llvm::Value *RHS = Visit(rhsExpr);
  3668. if (!LHS) {
  3669. // If the conditional has void type, make sure we return a null Value*.
  3670. assert(!RHS && "LHS and RHS types must match");
  3671. return nullptr;
  3672. }
  3673. return Builder.CreateSelect(CondV, LHS, RHS, "cond");
  3674. }
  3675. llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
  3676. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
  3677. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
  3678. CodeGenFunction::ConditionalEvaluation eval(CGF);
  3679. CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
  3680. CGF.getProfileCount(lhsExpr));
  3681. CGF.EmitBlock(LHSBlock);
  3682. CGF.incrementProfileCounter(E);
  3683. eval.begin(CGF);
  3684. Value *LHS = Visit(lhsExpr);
  3685. eval.end(CGF);
  3686. LHSBlock = Builder.GetInsertBlock();
  3687. Builder.CreateBr(ContBlock);
  3688. CGF.EmitBlock(RHSBlock);
  3689. eval.begin(CGF);
  3690. Value *RHS = Visit(rhsExpr);
  3691. eval.end(CGF);
  3692. RHSBlock = Builder.GetInsertBlock();
  3693. CGF.EmitBlock(ContBlock);
  3694. // If the LHS or RHS is a throw expression, it will be legitimately null.
  3695. if (!LHS)
  3696. return RHS;
  3697. if (!RHS)
  3698. return LHS;
  3699. // Create a PHI node for the real part.
  3700. llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
  3701. PN->addIncoming(LHS, LHSBlock);
  3702. PN->addIncoming(RHS, RHSBlock);
  3703. return PN;
  3704. }
  3705. Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
  3706. return Visit(E->getChosenSubExpr());
  3707. }
  3708. Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
  3709. QualType Ty = VE->getType();
  3710. if (Ty->isVariablyModifiedType())
  3711. CGF.EmitVariablyModifiedType(Ty);
  3712. Address ArgValue = Address::invalid();
  3713. Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
  3714. llvm::Type *ArgTy = ConvertType(VE->getType());
  3715. // If EmitVAArg fails, emit an error.
  3716. if (!ArgPtr.isValid()) {
  3717. CGF.ErrorUnsupported(VE, "va_arg expression");
  3718. return llvm::UndefValue::get(ArgTy);
  3719. }
  3720. // FIXME Volatility.
  3721. llvm::Value *Val = Builder.CreateLoad(ArgPtr);
  3722. // If EmitVAArg promoted the type, we must truncate it.
  3723. if (ArgTy != Val->getType()) {
  3724. if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
  3725. Val = Builder.CreateIntToPtr(Val, ArgTy);
  3726. else
  3727. Val = Builder.CreateTrunc(Val, ArgTy);
  3728. }
  3729. return Val;
  3730. }
  3731. Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
  3732. return CGF.EmitBlockLiteral(block);
  3733. }
  3734. // Convert a vec3 to vec4, or vice versa.
  3735. static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
  3736. Value *Src, unsigned NumElementsDst) {
  3737. llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
  3738. SmallVector<llvm::Constant*, 4> Args;
  3739. Args.push_back(Builder.getInt32(0));
  3740. Args.push_back(Builder.getInt32(1));
  3741. Args.push_back(Builder.getInt32(2));
  3742. if (NumElementsDst == 4)
  3743. Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
  3744. llvm::Constant *Mask = llvm::ConstantVector::get(Args);
  3745. return Builder.CreateShuffleVector(Src, UnV, Mask);
  3746. }
  3747. // Create cast instructions for converting LLVM value \p Src to LLVM type \p
  3748. // DstTy. \p Src has the same size as \p DstTy. Both are single value types
  3749. // but could be scalar or vectors of different lengths, and either can be
  3750. // pointer.
  3751. // There are 4 cases:
  3752. // 1. non-pointer -> non-pointer : needs 1 bitcast
  3753. // 2. pointer -> pointer : needs 1 bitcast or addrspacecast
  3754. // 3. pointer -> non-pointer
  3755. // a) pointer -> intptr_t : needs 1 ptrtoint
  3756. // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
  3757. // 4. non-pointer -> pointer
  3758. // a) intptr_t -> pointer : needs 1 inttoptr
  3759. // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
  3760. // Note: for cases 3b and 4b two casts are required since LLVM casts do not
  3761. // allow casting directly between pointer types and non-integer non-pointer
  3762. // types.
  3763. static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
  3764. const llvm::DataLayout &DL,
  3765. Value *Src, llvm::Type *DstTy,
  3766. StringRef Name = "") {
  3767. auto SrcTy = Src->getType();
  3768. // Case 1.
  3769. if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
  3770. return Builder.CreateBitCast(Src, DstTy, Name);
  3771. // Case 2.
  3772. if (SrcTy->isPointerTy() && DstTy->isPointerTy())
  3773. return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
  3774. // Case 3.
  3775. if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
  3776. // Case 3b.
  3777. if (!DstTy->isIntegerTy())
  3778. Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
  3779. // Cases 3a and 3b.
  3780. return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
  3781. }
  3782. // Case 4b.
  3783. if (!SrcTy->isIntegerTy())
  3784. Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
  3785. // Cases 4a and 4b.
  3786. return Builder.CreateIntToPtr(Src, DstTy, Name);
  3787. }
  3788. Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
  3789. Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
  3790. llvm::Type *DstTy = ConvertType(E->getType());
  3791. llvm::Type *SrcTy = Src->getType();
  3792. unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ?
  3793. cast<llvm::VectorType>(SrcTy)->getNumElements() : 0;
  3794. unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ?
  3795. cast<llvm::VectorType>(DstTy)->getNumElements() : 0;
  3796. // Going from vec3 to non-vec3 is a special case and requires a shuffle
  3797. // vector to get a vec4, then a bitcast if the target type is different.
  3798. if (NumElementsSrc == 3 && NumElementsDst != 3) {
  3799. Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
  3800. if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
  3801. Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
  3802. DstTy);
  3803. }
  3804. Src->setName("astype");
  3805. return Src;
  3806. }
  3807. // Going from non-vec3 to vec3 is a special case and requires a bitcast
  3808. // to vec4 if the original type is not vec4, then a shuffle vector to
  3809. // get a vec3.
  3810. if (NumElementsSrc != 3 && NumElementsDst == 3) {
  3811. if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
  3812. auto Vec4Ty = llvm::VectorType::get(DstTy->getVectorElementType(), 4);
  3813. Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
  3814. Vec4Ty);
  3815. }
  3816. Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
  3817. Src->setName("astype");
  3818. return Src;
  3819. }
  3820. return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
  3821. Src, DstTy, "astype");
  3822. }
  3823. Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
  3824. return CGF.EmitAtomicExpr(E).getScalarVal();
  3825. }
  3826. //===----------------------------------------------------------------------===//
  3827. // Entry Point into this File
  3828. //===----------------------------------------------------------------------===//
  3829. /// Emit the computation of the specified expression of scalar type, ignoring
  3830. /// the result.
  3831. Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
  3832. assert(E && hasScalarEvaluationKind(E->getType()) &&
  3833. "Invalid scalar expression to emit");
  3834. return ScalarExprEmitter(*this, IgnoreResultAssign)
  3835. .Visit(const_cast<Expr *>(E));
  3836. }
  3837. /// Emit a conversion from the specified type to the specified destination type,
  3838. /// both of which are LLVM scalar types.
  3839. Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
  3840. QualType DstTy,
  3841. SourceLocation Loc) {
  3842. assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
  3843. "Invalid scalar expression to emit");
  3844. return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
  3845. }
  3846. /// Emit a conversion from the specified complex type to the specified
  3847. /// destination type, where the destination type is an LLVM scalar type.
  3848. Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
  3849. QualType SrcTy,
  3850. QualType DstTy,
  3851. SourceLocation Loc) {
  3852. assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
  3853. "Invalid complex -> scalar conversion");
  3854. return ScalarExprEmitter(*this)
  3855. .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
  3856. }
  3857. llvm::Value *CodeGenFunction::
  3858. EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  3859. bool isInc, bool isPre) {
  3860. return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
  3861. }
  3862. LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
  3863. // object->isa or (*object).isa
  3864. // Generate code as for: *(Class*)object
  3865. Expr *BaseExpr = E->getBase();
  3866. Address Addr = Address::invalid();
  3867. if (BaseExpr->isRValue()) {
  3868. Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
  3869. } else {
  3870. Addr = EmitLValue(BaseExpr).getAddress();
  3871. }
  3872. // Cast the address to Class*.
  3873. Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
  3874. return MakeAddrLValue(Addr, E->getType());
  3875. }
  3876. LValue CodeGenFunction::EmitCompoundAssignmentLValue(
  3877. const CompoundAssignOperator *E) {
  3878. ScalarExprEmitter Scalar(*this);
  3879. Value *Result = nullptr;
  3880. switch (E->getOpcode()) {
  3881. #define COMPOUND_OP(Op) \
  3882. case BO_##Op##Assign: \
  3883. return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
  3884. Result)
  3885. COMPOUND_OP(Mul);
  3886. COMPOUND_OP(Div);
  3887. COMPOUND_OP(Rem);
  3888. COMPOUND_OP(Add);
  3889. COMPOUND_OP(Sub);
  3890. COMPOUND_OP(Shl);
  3891. COMPOUND_OP(Shr);
  3892. COMPOUND_OP(And);
  3893. COMPOUND_OP(Xor);
  3894. COMPOUND_OP(Or);
  3895. #undef COMPOUND_OP
  3896. case BO_PtrMemD:
  3897. case BO_PtrMemI:
  3898. case BO_Mul:
  3899. case BO_Div:
  3900. case BO_Rem:
  3901. case BO_Add:
  3902. case BO_Sub:
  3903. case BO_Shl:
  3904. case BO_Shr:
  3905. case BO_LT:
  3906. case BO_GT:
  3907. case BO_LE:
  3908. case BO_GE:
  3909. case BO_EQ:
  3910. case BO_NE:
  3911. case BO_Cmp:
  3912. case BO_And:
  3913. case BO_Xor:
  3914. case BO_Or:
  3915. case BO_LAnd:
  3916. case BO_LOr:
  3917. case BO_Assign:
  3918. case BO_Comma:
  3919. llvm_unreachable("Not valid compound assignment operators");
  3920. }
  3921. llvm_unreachable("Unhandled compound assignment operator");
  3922. }
  3923. struct GEPOffsetAndOverflow {
  3924. // The total (signed) byte offset for the GEP.
  3925. llvm::Value *TotalOffset;
  3926. // The offset overflow flag - true if the total offset overflows.
  3927. llvm::Value *OffsetOverflows;
  3928. };
  3929. /// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
  3930. /// and compute the total offset it applies from it's base pointer BasePtr.
  3931. /// Returns offset in bytes and a boolean flag whether an overflow happened
  3932. /// during evaluation.
  3933. static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
  3934. llvm::LLVMContext &VMContext,
  3935. CodeGenModule &CGM,
  3936. CGBuilderTy Builder) {
  3937. const auto &DL = CGM.getDataLayout();
  3938. // The total (signed) byte offset for the GEP.
  3939. llvm::Value *TotalOffset = nullptr;
  3940. // Was the GEP already reduced to a constant?
  3941. if (isa<llvm::Constant>(GEPVal)) {
  3942. // Compute the offset by casting both pointers to integers and subtracting:
  3943. // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
  3944. Value *BasePtr_int =
  3945. Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
  3946. Value *GEPVal_int =
  3947. Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
  3948. TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
  3949. return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
  3950. }
  3951. auto *GEP = cast<llvm::GEPOperator>(GEPVal);
  3952. assert(GEP->getPointerOperand() == BasePtr &&
  3953. "BasePtr must be the the base of the GEP.");
  3954. assert(GEP->isInBounds() && "Expected inbounds GEP");
  3955. auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
  3956. // Grab references to the signed add/mul overflow intrinsics for intptr_t.
  3957. auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
  3958. auto *SAddIntrinsic =
  3959. CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
  3960. auto *SMulIntrinsic =
  3961. CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
  3962. // The offset overflow flag - true if the total offset overflows.
  3963. llvm::Value *OffsetOverflows = Builder.getFalse();
  3964. /// Return the result of the given binary operation.
  3965. auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
  3966. llvm::Value *RHS) -> llvm::Value * {
  3967. assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
  3968. // If the operands are constants, return a constant result.
  3969. if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
  3970. if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
  3971. llvm::APInt N;
  3972. bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
  3973. /*Signed=*/true, N);
  3974. if (HasOverflow)
  3975. OffsetOverflows = Builder.getTrue();
  3976. return llvm::ConstantInt::get(VMContext, N);
  3977. }
  3978. }
  3979. // Otherwise, compute the result with checked arithmetic.
  3980. auto *ResultAndOverflow = Builder.CreateCall(
  3981. (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
  3982. OffsetOverflows = Builder.CreateOr(
  3983. Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
  3984. return Builder.CreateExtractValue(ResultAndOverflow, 0);
  3985. };
  3986. // Determine the total byte offset by looking at each GEP operand.
  3987. for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
  3988. GTI != GTE; ++GTI) {
  3989. llvm::Value *LocalOffset;
  3990. auto *Index = GTI.getOperand();
  3991. // Compute the local offset contributed by this indexing step:
  3992. if (auto *STy = GTI.getStructTypeOrNull()) {
  3993. // For struct indexing, the local offset is the byte position of the
  3994. // specified field.
  3995. unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
  3996. LocalOffset = llvm::ConstantInt::get(
  3997. IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
  3998. } else {
  3999. // Otherwise this is array-like indexing. The local offset is the index
  4000. // multiplied by the element size.
  4001. auto *ElementSize = llvm::ConstantInt::get(
  4002. IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
  4003. auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
  4004. LocalOffset = eval(BO_Mul, ElementSize, IndexS);
  4005. }
  4006. // If this is the first offset, set it as the total offset. Otherwise, add
  4007. // the local offset into the running total.
  4008. if (!TotalOffset || TotalOffset == Zero)
  4009. TotalOffset = LocalOffset;
  4010. else
  4011. TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
  4012. }
  4013. return {TotalOffset, OffsetOverflows};
  4014. }
  4015. Value *
  4016. CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
  4017. bool SignedIndices, bool IsSubtraction,
  4018. SourceLocation Loc, const Twine &Name) {
  4019. Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
  4020. // If the pointer overflow sanitizer isn't enabled, do nothing.
  4021. if (!SanOpts.has(SanitizerKind::PointerOverflow))
  4022. return GEPVal;
  4023. llvm::Type *PtrTy = Ptr->getType();
  4024. // Perform nullptr-and-offset check unless the nullptr is defined.
  4025. bool PerformNullCheck = !NullPointerIsDefined(
  4026. Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
  4027. // Check for overflows unless the GEP got constant-folded,
  4028. // and only in the default address space
  4029. bool PerformOverflowCheck =
  4030. !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0;
  4031. if (!(PerformNullCheck || PerformOverflowCheck))
  4032. return GEPVal;
  4033. const auto &DL = CGM.getDataLayout();
  4034. SanitizerScope SanScope(this);
  4035. llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
  4036. GEPOffsetAndOverflow EvaluatedGEP =
  4037. EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
  4038. assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
  4039. EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
  4040. "If the offset got constant-folded, we don't expect that there was an "
  4041. "overflow.");
  4042. auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
  4043. // Common case: if the total offset is zero, and we are using C++ semantics,
  4044. // where nullptr+0 is defined, don't emit a check.
  4045. if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus)
  4046. return GEPVal;
  4047. // Now that we've computed the total offset, add it to the base pointer (with
  4048. // wrapping semantics).
  4049. auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy);
  4050. auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
  4051. llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
  4052. if (PerformNullCheck) {
  4053. // In C++, if the base pointer evaluates to a null pointer value,
  4054. // the only valid pointer this inbounds GEP can produce is also
  4055. // a null pointer, so the offset must also evaluate to zero.
  4056. // Likewise, if we have non-zero base pointer, we can not get null pointer
  4057. // as a result, so the offset can not be -intptr_t(BasePtr).
  4058. // In other words, both pointers are either null, or both are non-null,
  4059. // or the behaviour is undefined.
  4060. //
  4061. // C, however, is more strict in this regard, and gives more
  4062. // optimization opportunities: in C, additionally, nullptr+0 is undefined.
  4063. // So both the input to the 'gep inbounds' AND the output must not be null.
  4064. auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
  4065. auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
  4066. auto *Valid =
  4067. CGM.getLangOpts().CPlusPlus
  4068. ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr)
  4069. : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr);
  4070. Checks.emplace_back(Valid, SanitizerKind::PointerOverflow);
  4071. }
  4072. if (PerformOverflowCheck) {
  4073. // The GEP is valid if:
  4074. // 1) The total offset doesn't overflow, and
  4075. // 2) The sign of the difference between the computed address and the base
  4076. // pointer matches the sign of the total offset.
  4077. llvm::Value *ValidGEP;
  4078. auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
  4079. if (SignedIndices) {
  4080. // GEP is computed as `unsigned base + signed offset`, therefore:
  4081. // * If offset was positive, then the computed pointer can not be
  4082. // [unsigned] less than the base pointer, unless it overflowed.
  4083. // * If offset was negative, then the computed pointer can not be
  4084. // [unsigned] greater than the bas pointere, unless it overflowed.
  4085. auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
  4086. auto *PosOrZeroOffset =
  4087. Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
  4088. llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
  4089. ValidGEP =
  4090. Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
  4091. } else if (!IsSubtraction) {
  4092. // GEP is computed as `unsigned base + unsigned offset`, therefore the
  4093. // computed pointer can not be [unsigned] less than base pointer,
  4094. // unless there was an overflow.
  4095. // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
  4096. ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
  4097. } else {
  4098. // GEP is computed as `unsigned base - unsigned offset`, therefore the
  4099. // computed pointer can not be [unsigned] greater than base pointer,
  4100. // unless there was an overflow.
  4101. // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
  4102. ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
  4103. }
  4104. ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
  4105. Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
  4106. }
  4107. assert(!Checks.empty() && "Should have produced some checks.");
  4108. llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
  4109. // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
  4110. llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
  4111. EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
  4112. return GEPVal;
  4113. }