CGExprScalar.cpp 212 KB

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