CGExprScalar.cpp 155 KB

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