CGExprScalar.cpp 166 KB

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