CGExprScalar.cpp 185 KB

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