CGExprScalar.cpp 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862
  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 "clang/Frontend/CodeGenOptions.h"
  14. #include "CodeGenFunction.h"
  15. #include "CGCXXABI.h"
  16. #include "CGObjCRuntime.h"
  17. #include "CodeGenModule.h"
  18. #include "CGDebugInfo.h"
  19. #include "clang/AST/ASTContext.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/RecordLayout.h"
  22. #include "clang/AST/StmtVisitor.h"
  23. #include "clang/Basic/TargetInfo.h"
  24. #include "llvm/Constants.h"
  25. #include "llvm/Function.h"
  26. #include "llvm/GlobalVariable.h"
  27. #include "llvm/Intrinsics.h"
  28. #include "llvm/Module.h"
  29. #include "llvm/Support/CFG.h"
  30. #include "llvm/Target/TargetData.h"
  31. #include <cstdarg>
  32. using namespace clang;
  33. using namespace CodeGen;
  34. using llvm::Value;
  35. //===----------------------------------------------------------------------===//
  36. // Scalar Expression Emitter
  37. //===----------------------------------------------------------------------===//
  38. namespace {
  39. struct BinOpInfo {
  40. Value *LHS;
  41. Value *RHS;
  42. QualType Ty; // Computation Type.
  43. BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
  44. const Expr *E; // Entire expr, for error unsupported. May not be binop.
  45. };
  46. static bool MustVisitNullValue(const Expr *E) {
  47. // If a null pointer expression's type is the C++0x nullptr_t, then
  48. // it's not necessarily a simple constant and it must be evaluated
  49. // for its potential side effects.
  50. return E->getType()->isNullPtrType();
  51. }
  52. class ScalarExprEmitter
  53. : public StmtVisitor<ScalarExprEmitter, Value*> {
  54. CodeGenFunction &CGF;
  55. CGBuilderTy &Builder;
  56. bool IgnoreResultAssign;
  57. llvm::LLVMContext &VMContext;
  58. public:
  59. ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
  60. : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
  61. VMContext(cgf.getLLVMContext()) {
  62. }
  63. //===--------------------------------------------------------------------===//
  64. // Utilities
  65. //===--------------------------------------------------------------------===//
  66. bool TestAndClearIgnoreResultAssign() {
  67. bool I = IgnoreResultAssign;
  68. IgnoreResultAssign = false;
  69. return I;
  70. }
  71. llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
  72. LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
  73. LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
  74. Value *EmitLoadOfLValue(LValue LV) {
  75. return CGF.EmitLoadOfLValue(LV).getScalarVal();
  76. }
  77. /// EmitLoadOfLValue - Given an expression with complex type that represents a
  78. /// value l-value, this method emits the address of the l-value, then loads
  79. /// and returns the result.
  80. Value *EmitLoadOfLValue(const Expr *E) {
  81. return EmitLoadOfLValue(EmitCheckedLValue(E));
  82. }
  83. /// EmitConversionToBool - Convert the specified expression value to a
  84. /// boolean (i1) truth value. This is equivalent to "Val != 0".
  85. Value *EmitConversionToBool(Value *Src, QualType DstTy);
  86. /// EmitScalarConversion - Emit a conversion from the specified type to the
  87. /// specified destination type, both of which are LLVM scalar types.
  88. Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
  89. /// EmitComplexToScalarConversion - Emit a conversion from the specified
  90. /// complex type to the specified destination type, where the destination type
  91. /// is an LLVM scalar type.
  92. Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
  93. QualType SrcTy, QualType DstTy);
  94. /// EmitNullValue - Emit a value that corresponds to null for the given type.
  95. Value *EmitNullValue(QualType Ty);
  96. /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
  97. Value *EmitFloatToBoolConversion(Value *V) {
  98. // Compare against 0.0 for fp scalars.
  99. llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
  100. return Builder.CreateFCmpUNE(V, Zero, "tobool");
  101. }
  102. /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
  103. Value *EmitPointerToBoolConversion(Value *V) {
  104. Value *Zero = llvm::ConstantPointerNull::get(
  105. cast<llvm::PointerType>(V->getType()));
  106. return Builder.CreateICmpNE(V, Zero, "tobool");
  107. }
  108. Value *EmitIntToBoolConversion(Value *V) {
  109. // Because of the type rules of C, we often end up computing a
  110. // logical value, then zero extending it to int, then wanting it
  111. // as a logical value again. Optimize this common case.
  112. if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
  113. if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
  114. Value *Result = ZI->getOperand(0);
  115. // If there aren't any more uses, zap the instruction to save space.
  116. // Note that there can be more uses, for example if this
  117. // is the result of an assignment.
  118. if (ZI->use_empty())
  119. ZI->eraseFromParent();
  120. return Result;
  121. }
  122. }
  123. return Builder.CreateIsNotNull(V, "tobool");
  124. }
  125. //===--------------------------------------------------------------------===//
  126. // Visitor Methods
  127. //===--------------------------------------------------------------------===//
  128. Value *Visit(Expr *E) {
  129. return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
  130. }
  131. Value *VisitStmt(Stmt *S) {
  132. S->dump(CGF.getContext().getSourceManager());
  133. llvm_unreachable("Stmt can't have complex result type!");
  134. }
  135. Value *VisitExpr(Expr *S);
  136. Value *VisitParenExpr(ParenExpr *PE) {
  137. return Visit(PE->getSubExpr());
  138. }
  139. Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
  140. return Visit(E->getReplacement());
  141. }
  142. Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
  143. return Visit(GE->getResultExpr());
  144. }
  145. // Leaves.
  146. Value *VisitIntegerLiteral(const IntegerLiteral *E) {
  147. return Builder.getInt(E->getValue());
  148. }
  149. Value *VisitFloatingLiteral(const FloatingLiteral *E) {
  150. return llvm::ConstantFP::get(VMContext, E->getValue());
  151. }
  152. Value *VisitCharacterLiteral(const CharacterLiteral *E) {
  153. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  154. }
  155. Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  156. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  157. }
  158. Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  159. return EmitNullValue(E->getType());
  160. }
  161. Value *VisitGNUNullExpr(const GNUNullExpr *E) {
  162. return EmitNullValue(E->getType());
  163. }
  164. Value *VisitOffsetOfExpr(OffsetOfExpr *E);
  165. Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  166. Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
  167. llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
  168. return Builder.CreateBitCast(V, ConvertType(E->getType()));
  169. }
  170. Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
  171. return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
  172. }
  173. Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
  174. return CGF.EmitPseudoObjectRValue(E).getScalarVal();
  175. }
  176. Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
  177. if (E->isGLValue())
  178. return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
  179. // Otherwise, assume the mapping is the scalar directly.
  180. return CGF.getOpaqueRValueMapping(E).getScalarVal();
  181. }
  182. // l-values.
  183. Value *VisitDeclRefExpr(DeclRefExpr *E) {
  184. Expr::EvalResult Result;
  185. if (!E->EvaluateAsRValue(Result, CGF.getContext()))
  186. return EmitLoadOfLValue(E);
  187. assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
  188. llvm::Constant *C;
  189. if (Result.Val.isInt())
  190. C = Builder.getInt(Result.Val.getInt());
  191. else if (Result.Val.isFloat())
  192. C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
  193. else
  194. return EmitLoadOfLValue(E);
  195. // Make sure we emit a debug reference to the global variable.
  196. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
  197. if (!CGF.getContext().DeclMustBeEmitted(VD))
  198. CGF.EmitDeclRefExprDbgValue(E, C);
  199. } else if (isa<EnumConstantDecl>(E->getDecl())) {
  200. CGF.EmitDeclRefExprDbgValue(E, C);
  201. }
  202. return C;
  203. }
  204. Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
  205. return CGF.EmitObjCSelectorExpr(E);
  206. }
  207. Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
  208. return CGF.EmitObjCProtocolExpr(E);
  209. }
  210. Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
  211. return EmitLoadOfLValue(E);
  212. }
  213. Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
  214. if (E->getMethodDecl() &&
  215. E->getMethodDecl()->getResultType()->isReferenceType())
  216. return EmitLoadOfLValue(E);
  217. return CGF.EmitObjCMessageExpr(E).getScalarVal();
  218. }
  219. Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
  220. LValue LV = CGF.EmitObjCIsaExpr(E);
  221. Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
  222. return V;
  223. }
  224. Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
  225. Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
  226. Value *VisitMemberExpr(MemberExpr *E);
  227. Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
  228. Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
  229. return EmitLoadOfLValue(E);
  230. }
  231. Value *VisitInitListExpr(InitListExpr *E);
  232. Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  233. return CGF.CGM.EmitNullConstant(E->getType());
  234. }
  235. Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
  236. if (E->getType()->isVariablyModifiedType())
  237. CGF.EmitVariablyModifiedType(E->getType());
  238. return VisitCastExpr(E);
  239. }
  240. Value *VisitCastExpr(CastExpr *E);
  241. Value *VisitCallExpr(const CallExpr *E) {
  242. if (E->getCallReturnType()->isReferenceType())
  243. return EmitLoadOfLValue(E);
  244. return CGF.EmitCallExpr(E).getScalarVal();
  245. }
  246. Value *VisitStmtExpr(const StmtExpr *E);
  247. Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
  248. // Unary Operators.
  249. Value *VisitUnaryPostDec(const UnaryOperator *E) {
  250. LValue LV = EmitLValue(E->getSubExpr());
  251. return EmitScalarPrePostIncDec(E, LV, false, false);
  252. }
  253. Value *VisitUnaryPostInc(const UnaryOperator *E) {
  254. LValue LV = EmitLValue(E->getSubExpr());
  255. return EmitScalarPrePostIncDec(E, LV, true, false);
  256. }
  257. Value *VisitUnaryPreDec(const UnaryOperator *E) {
  258. LValue LV = EmitLValue(E->getSubExpr());
  259. return EmitScalarPrePostIncDec(E, LV, false, true);
  260. }
  261. Value *VisitUnaryPreInc(const UnaryOperator *E) {
  262. LValue LV = EmitLValue(E->getSubExpr());
  263. return EmitScalarPrePostIncDec(E, LV, true, true);
  264. }
  265. llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
  266. llvm::Value *InVal,
  267. llvm::Value *NextVal,
  268. bool IsInc);
  269. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  270. bool isInc, bool isPre);
  271. Value *VisitUnaryAddrOf(const UnaryOperator *E) {
  272. if (isa<MemberPointerType>(E->getType())) // never sugared
  273. return CGF.CGM.getMemberPointerConstant(E);
  274. return EmitLValue(E->getSubExpr()).getAddress();
  275. }
  276. Value *VisitUnaryDeref(const UnaryOperator *E) {
  277. if (E->getType()->isVoidType())
  278. return Visit(E->getSubExpr()); // the actual value should be unused
  279. return EmitLoadOfLValue(E);
  280. }
  281. Value *VisitUnaryPlus(const UnaryOperator *E) {
  282. // This differs from gcc, though, most likely due to a bug in gcc.
  283. TestAndClearIgnoreResultAssign();
  284. return Visit(E->getSubExpr());
  285. }
  286. Value *VisitUnaryMinus (const UnaryOperator *E);
  287. Value *VisitUnaryNot (const UnaryOperator *E);
  288. Value *VisitUnaryLNot (const UnaryOperator *E);
  289. Value *VisitUnaryReal (const UnaryOperator *E);
  290. Value *VisitUnaryImag (const UnaryOperator *E);
  291. Value *VisitUnaryExtension(const UnaryOperator *E) {
  292. return Visit(E->getSubExpr());
  293. }
  294. // C++
  295. Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
  296. return EmitLoadOfLValue(E);
  297. }
  298. Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
  299. return Visit(DAE->getExpr());
  300. }
  301. Value *VisitCXXThisExpr(CXXThisExpr *TE) {
  302. return CGF.LoadCXXThis();
  303. }
  304. Value *VisitExprWithCleanups(ExprWithCleanups *E) {
  305. CGF.enterFullExpression(E);
  306. CodeGenFunction::RunCleanupsScope Scope(CGF);
  307. return Visit(E->getSubExpr());
  308. }
  309. Value *VisitCXXNewExpr(const CXXNewExpr *E) {
  310. return CGF.EmitCXXNewExpr(E);
  311. }
  312. Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
  313. CGF.EmitCXXDeleteExpr(E);
  314. return 0;
  315. }
  316. Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
  317. return Builder.getInt1(E->getValue());
  318. }
  319. Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
  320. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  321. }
  322. Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  323. return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
  324. }
  325. Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  326. return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
  327. }
  328. Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
  329. // C++ [expr.pseudo]p1:
  330. // The result shall only be used as the operand for the function call
  331. // operator (), and the result of such a call has type void. The only
  332. // effect is the evaluation of the postfix-expression before the dot or
  333. // arrow.
  334. CGF.EmitScalarExpr(E->getBase());
  335. return 0;
  336. }
  337. Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  338. return EmitNullValue(E->getType());
  339. }
  340. Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
  341. CGF.EmitCXXThrowExpr(E);
  342. return 0;
  343. }
  344. Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  345. return Builder.getInt1(E->getValue());
  346. }
  347. // Binary Operators.
  348. Value *EmitMul(const BinOpInfo &Ops) {
  349. if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
  350. switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
  351. case LangOptions::SOB_Undefined:
  352. return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
  353. case LangOptions::SOB_Defined:
  354. return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
  355. case LangOptions::SOB_Trapping:
  356. return EmitOverflowCheckedBinOp(Ops);
  357. }
  358. }
  359. if (Ops.LHS->getType()->isFPOrFPVectorTy())
  360. return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
  361. return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
  362. }
  363. bool isTrapvOverflowBehavior() {
  364. return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
  365. == LangOptions::SOB_Trapping;
  366. }
  367. /// Create a binary op that checks for overflow.
  368. /// Currently only supports +, - and *.
  369. Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
  370. // Emit the overflow BB when -ftrapv option is activated.
  371. void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
  372. Builder.SetInsertPoint(overflowBB);
  373. llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
  374. Builder.CreateCall(Trap);
  375. Builder.CreateUnreachable();
  376. }
  377. // Check for undefined division and modulus behaviors.
  378. void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
  379. llvm::Value *Zero,bool isDiv);
  380. Value *EmitDiv(const BinOpInfo &Ops);
  381. Value *EmitRem(const BinOpInfo &Ops);
  382. Value *EmitAdd(const BinOpInfo &Ops);
  383. Value *EmitSub(const BinOpInfo &Ops);
  384. Value *EmitShl(const BinOpInfo &Ops);
  385. Value *EmitShr(const BinOpInfo &Ops);
  386. Value *EmitAnd(const BinOpInfo &Ops) {
  387. return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
  388. }
  389. Value *EmitXor(const BinOpInfo &Ops) {
  390. return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
  391. }
  392. Value *EmitOr (const BinOpInfo &Ops) {
  393. return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
  394. }
  395. BinOpInfo EmitBinOps(const BinaryOperator *E);
  396. LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
  397. Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
  398. Value *&Result);
  399. Value *EmitCompoundAssign(const CompoundAssignOperator *E,
  400. Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
  401. // Binary operators and binary compound assignment operators.
  402. #define HANDLEBINOP(OP) \
  403. Value *VisitBin ## OP(const BinaryOperator *E) { \
  404. return Emit ## OP(EmitBinOps(E)); \
  405. } \
  406. Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
  407. return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
  408. }
  409. HANDLEBINOP(Mul)
  410. HANDLEBINOP(Div)
  411. HANDLEBINOP(Rem)
  412. HANDLEBINOP(Add)
  413. HANDLEBINOP(Sub)
  414. HANDLEBINOP(Shl)
  415. HANDLEBINOP(Shr)
  416. HANDLEBINOP(And)
  417. HANDLEBINOP(Xor)
  418. HANDLEBINOP(Or)
  419. #undef HANDLEBINOP
  420. // Comparisons.
  421. Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
  422. unsigned SICmpOpc, unsigned FCmpOpc);
  423. #define VISITCOMP(CODE, UI, SI, FP) \
  424. Value *VisitBin##CODE(const BinaryOperator *E) { \
  425. return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
  426. llvm::FCmpInst::FP); }
  427. VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
  428. VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
  429. VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
  430. VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
  431. VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
  432. VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
  433. #undef VISITCOMP
  434. Value *VisitBinAssign (const BinaryOperator *E);
  435. Value *VisitBinLAnd (const BinaryOperator *E);
  436. Value *VisitBinLOr (const BinaryOperator *E);
  437. Value *VisitBinComma (const BinaryOperator *E);
  438. Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
  439. Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
  440. // Other Operators.
  441. Value *VisitBlockExpr(const BlockExpr *BE);
  442. Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
  443. Value *VisitChooseExpr(ChooseExpr *CE);
  444. Value *VisitVAArgExpr(VAArgExpr *VE);
  445. Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
  446. return CGF.EmitObjCStringLiteral(E);
  447. }
  448. Value *VisitAsTypeExpr(AsTypeExpr *CE);
  449. Value *VisitAtomicExpr(AtomicExpr *AE);
  450. };
  451. } // end anonymous namespace.
  452. //===----------------------------------------------------------------------===//
  453. // Utilities
  454. //===----------------------------------------------------------------------===//
  455. /// EmitConversionToBool - Convert the specified expression value to a
  456. /// boolean (i1) truth value. This is equivalent to "Val != 0".
  457. Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
  458. assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
  459. if (SrcType->isRealFloatingType())
  460. return EmitFloatToBoolConversion(Src);
  461. if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
  462. return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
  463. assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
  464. "Unknown scalar type to convert");
  465. if (isa<llvm::IntegerType>(Src->getType()))
  466. return EmitIntToBoolConversion(Src);
  467. assert(isa<llvm::PointerType>(Src->getType()));
  468. return EmitPointerToBoolConversion(Src);
  469. }
  470. /// EmitScalarConversion - Emit a conversion from the specified type to the
  471. /// specified destination type, both of which are LLVM scalar types.
  472. Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
  473. QualType DstType) {
  474. SrcType = CGF.getContext().getCanonicalType(SrcType);
  475. DstType = CGF.getContext().getCanonicalType(DstType);
  476. if (SrcType == DstType) return Src;
  477. if (DstType->isVoidType()) return 0;
  478. llvm::Type *SrcTy = Src->getType();
  479. // Floating casts might be a bit special: if we're doing casts to / from half
  480. // FP, we should go via special intrinsics.
  481. if (SrcType->isHalfType()) {
  482. Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
  483. SrcType = CGF.getContext().FloatTy;
  484. SrcTy = CGF.FloatTy;
  485. }
  486. // Handle conversions to bool first, they are special: comparisons against 0.
  487. if (DstType->isBooleanType())
  488. return EmitConversionToBool(Src, SrcType);
  489. llvm::Type *DstTy = ConvertType(DstType);
  490. // Ignore conversions like int -> uint.
  491. if (SrcTy == DstTy)
  492. return Src;
  493. // Handle pointer conversions next: pointers can only be converted to/from
  494. // other pointers and integers. Check for pointer types in terms of LLVM, as
  495. // some native types (like Obj-C id) may map to a pointer type.
  496. if (isa<llvm::PointerType>(DstTy)) {
  497. // The source value may be an integer, or a pointer.
  498. if (isa<llvm::PointerType>(SrcTy))
  499. return Builder.CreateBitCast(Src, DstTy, "conv");
  500. assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
  501. // First, convert to the correct width so that we control the kind of
  502. // extension.
  503. llvm::Type *MiddleTy = CGF.IntPtrTy;
  504. bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
  505. llvm::Value* IntResult =
  506. Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
  507. // Then, cast to pointer.
  508. return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
  509. }
  510. if (isa<llvm::PointerType>(SrcTy)) {
  511. // Must be an ptr to int cast.
  512. assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
  513. return Builder.CreatePtrToInt(Src, DstTy, "conv");
  514. }
  515. // A scalar can be splatted to an extended vector of the same element type
  516. if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
  517. // Cast the scalar to element type
  518. QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
  519. llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
  520. // Insert the element in element zero of an undef vector
  521. llvm::Value *UnV = llvm::UndefValue::get(DstTy);
  522. llvm::Value *Idx = Builder.getInt32(0);
  523. UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
  524. // Splat the element across to all elements
  525. unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
  526. llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements,
  527. Builder.getInt32(0));
  528. llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
  529. return Yay;
  530. }
  531. // Allow bitcast from vector to integer/fp of the same size.
  532. if (isa<llvm::VectorType>(SrcTy) ||
  533. isa<llvm::VectorType>(DstTy))
  534. return Builder.CreateBitCast(Src, DstTy, "conv");
  535. // Finally, we have the arithmetic types: real int/float.
  536. Value *Res = NULL;
  537. llvm::Type *ResTy = DstTy;
  538. // Cast to half via float
  539. if (DstType->isHalfType())
  540. DstTy = CGF.FloatTy;
  541. if (isa<llvm::IntegerType>(SrcTy)) {
  542. bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
  543. if (isa<llvm::IntegerType>(DstTy))
  544. Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
  545. else if (InputSigned)
  546. Res = Builder.CreateSIToFP(Src, DstTy, "conv");
  547. else
  548. Res = Builder.CreateUIToFP(Src, DstTy, "conv");
  549. } else if (isa<llvm::IntegerType>(DstTy)) {
  550. assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
  551. if (DstType->isSignedIntegerOrEnumerationType())
  552. Res = Builder.CreateFPToSI(Src, DstTy, "conv");
  553. else
  554. Res = Builder.CreateFPToUI(Src, DstTy, "conv");
  555. } else {
  556. assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
  557. "Unknown real conversion");
  558. if (DstTy->getTypeID() < SrcTy->getTypeID())
  559. Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
  560. else
  561. Res = Builder.CreateFPExt(Src, DstTy, "conv");
  562. }
  563. if (DstTy != ResTy) {
  564. assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
  565. Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
  566. }
  567. return Res;
  568. }
  569. /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
  570. /// type to the specified destination type, where the destination type is an
  571. /// LLVM scalar type.
  572. Value *ScalarExprEmitter::
  573. EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
  574. QualType SrcTy, QualType DstTy) {
  575. // Get the source element type.
  576. SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
  577. // Handle conversions to bool first, they are special: comparisons against 0.
  578. if (DstTy->isBooleanType()) {
  579. // Complex != 0 -> (Real != 0) | (Imag != 0)
  580. Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
  581. Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
  582. return Builder.CreateOr(Src.first, Src.second, "tobool");
  583. }
  584. // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
  585. // the imaginary part of the complex value is discarded and the value of the
  586. // real part is converted according to the conversion rules for the
  587. // corresponding real type.
  588. return EmitScalarConversion(Src.first, SrcTy, DstTy);
  589. }
  590. Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
  591. if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
  592. return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
  593. return llvm::Constant::getNullValue(ConvertType(Ty));
  594. }
  595. //===----------------------------------------------------------------------===//
  596. // Visitor Methods
  597. //===----------------------------------------------------------------------===//
  598. Value *ScalarExprEmitter::VisitExpr(Expr *E) {
  599. CGF.ErrorUnsupported(E, "scalar expression");
  600. if (E->getType()->isVoidType())
  601. return 0;
  602. return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
  603. }
  604. Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
  605. // Vector Mask Case
  606. if (E->getNumSubExprs() == 2 ||
  607. (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
  608. Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
  609. Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
  610. Value *Mask;
  611. llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
  612. unsigned LHSElts = LTy->getNumElements();
  613. if (E->getNumSubExprs() == 3) {
  614. Mask = CGF.EmitScalarExpr(E->getExpr(2));
  615. // Shuffle LHS & RHS into one input vector.
  616. SmallVector<llvm::Constant*, 32> concat;
  617. for (unsigned i = 0; i != LHSElts; ++i) {
  618. concat.push_back(Builder.getInt32(2*i));
  619. concat.push_back(Builder.getInt32(2*i+1));
  620. }
  621. Value* CV = llvm::ConstantVector::get(concat);
  622. LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
  623. LHSElts *= 2;
  624. } else {
  625. Mask = RHS;
  626. }
  627. llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
  628. llvm::Constant* EltMask;
  629. // Treat vec3 like vec4.
  630. if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
  631. EltMask = llvm::ConstantInt::get(MTy->getElementType(),
  632. (1 << llvm::Log2_32(LHSElts+2))-1);
  633. else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
  634. EltMask = llvm::ConstantInt::get(MTy->getElementType(),
  635. (1 << llvm::Log2_32(LHSElts+1))-1);
  636. else
  637. EltMask = llvm::ConstantInt::get(MTy->getElementType(),
  638. (1 << llvm::Log2_32(LHSElts))-1);
  639. // Mask off the high bits of each shuffle index.
  640. Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
  641. EltMask);
  642. Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
  643. // newv = undef
  644. // mask = mask & maskbits
  645. // for each elt
  646. // n = extract mask i
  647. // x = extract val n
  648. // newv = insert newv, x, i
  649. llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
  650. MTy->getNumElements());
  651. Value* NewV = llvm::UndefValue::get(RTy);
  652. for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
  653. Value *Indx = Builder.getInt32(i);
  654. Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
  655. Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
  656. // Handle vec3 special since the index will be off by one for the RHS.
  657. if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
  658. Value *cmpIndx, *newIndx;
  659. cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
  660. "cmp_shuf_idx");
  661. newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
  662. Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
  663. }
  664. Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
  665. NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
  666. }
  667. return NewV;
  668. }
  669. Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
  670. Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
  671. // Handle vec3 special since the index will be off by one for the RHS.
  672. llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
  673. SmallVector<llvm::Constant*, 32> indices;
  674. for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
  675. unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
  676. if (VTy->getNumElements() == 3 && Idx > 3)
  677. Idx -= 1;
  678. indices.push_back(Builder.getInt32(Idx));
  679. }
  680. Value *SV = llvm::ConstantVector::get(indices);
  681. return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
  682. }
  683. Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
  684. llvm::APSInt Value;
  685. if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
  686. if (E->isArrow())
  687. CGF.EmitScalarExpr(E->getBase());
  688. else
  689. EmitLValue(E->getBase());
  690. return Builder.getInt(Value);
  691. }
  692. // Emit debug info for aggregate now, if it was delayed to reduce
  693. // debug info size.
  694. CGDebugInfo *DI = CGF.getDebugInfo();
  695. if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
  696. QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
  697. if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
  698. if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
  699. DI->getOrCreateRecordType(PTy->getPointeeType(),
  700. M->getParent()->getLocation());
  701. }
  702. return EmitLoadOfLValue(E);
  703. }
  704. Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
  705. TestAndClearIgnoreResultAssign();
  706. // Emit subscript expressions in rvalue context's. For most cases, this just
  707. // loads the lvalue formed by the subscript expr. However, we have to be
  708. // careful, because the base of a vector subscript is occasionally an rvalue,
  709. // so we can't get it as an lvalue.
  710. if (!E->getBase()->getType()->isVectorType())
  711. return EmitLoadOfLValue(E);
  712. // Handle the vector case. The base must be a vector, the index must be an
  713. // integer value.
  714. Value *Base = Visit(E->getBase());
  715. Value *Idx = Visit(E->getIdx());
  716. bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
  717. Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
  718. return Builder.CreateExtractElement(Base, Idx, "vecext");
  719. }
  720. static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
  721. unsigned Off, llvm::Type *I32Ty) {
  722. int MV = SVI->getMaskValue(Idx);
  723. if (MV == -1)
  724. return llvm::UndefValue::get(I32Ty);
  725. return llvm::ConstantInt::get(I32Ty, Off+MV);
  726. }
  727. Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
  728. bool Ignore = TestAndClearIgnoreResultAssign();
  729. (void)Ignore;
  730. assert (Ignore == false && "init list ignored");
  731. unsigned NumInitElements = E->getNumInits();
  732. if (E->hadArrayRangeDesignator())
  733. CGF.ErrorUnsupported(E, "GNU array range designator extension");
  734. llvm::VectorType *VType =
  735. dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
  736. if (!VType) {
  737. if (NumInitElements == 0) {
  738. // C++11 value-initialization for the scalar.
  739. return EmitNullValue(E->getType());
  740. }
  741. // We have a scalar in braces. Just use the first element.
  742. return Visit(E->getInit(0));
  743. }
  744. unsigned ResElts = VType->getNumElements();
  745. // Loop over initializers collecting the Value for each, and remembering
  746. // whether the source was swizzle (ExtVectorElementExpr). This will allow
  747. // us to fold the shuffle for the swizzle into the shuffle for the vector
  748. // initializer, since LLVM optimizers generally do not want to touch
  749. // shuffles.
  750. unsigned CurIdx = 0;
  751. bool VIsUndefShuffle = false;
  752. llvm::Value *V = llvm::UndefValue::get(VType);
  753. for (unsigned i = 0; i != NumInitElements; ++i) {
  754. Expr *IE = E->getInit(i);
  755. Value *Init = Visit(IE);
  756. SmallVector<llvm::Constant*, 16> Args;
  757. llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
  758. // Handle scalar elements. If the scalar initializer is actually one
  759. // element of a different vector of the same width, use shuffle instead of
  760. // extract+insert.
  761. if (!VVT) {
  762. if (isa<ExtVectorElementExpr>(IE)) {
  763. llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
  764. if (EI->getVectorOperandType()->getNumElements() == ResElts) {
  765. llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
  766. Value *LHS = 0, *RHS = 0;
  767. if (CurIdx == 0) {
  768. // insert into undef -> shuffle (src, undef)
  769. Args.push_back(C);
  770. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  771. LHS = EI->getVectorOperand();
  772. RHS = V;
  773. VIsUndefShuffle = true;
  774. } else if (VIsUndefShuffle) {
  775. // insert into undefshuffle && size match -> shuffle (v, src)
  776. llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
  777. for (unsigned j = 0; j != CurIdx; ++j)
  778. Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
  779. Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
  780. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  781. LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
  782. RHS = EI->getVectorOperand();
  783. VIsUndefShuffle = false;
  784. }
  785. if (!Args.empty()) {
  786. llvm::Constant *Mask = llvm::ConstantVector::get(Args);
  787. V = Builder.CreateShuffleVector(LHS, RHS, Mask);
  788. ++CurIdx;
  789. continue;
  790. }
  791. }
  792. }
  793. V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
  794. "vecinit");
  795. VIsUndefShuffle = false;
  796. ++CurIdx;
  797. continue;
  798. }
  799. unsigned InitElts = VVT->getNumElements();
  800. // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
  801. // input is the same width as the vector being constructed, generate an
  802. // optimized shuffle of the swizzle input into the result.
  803. unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
  804. if (isa<ExtVectorElementExpr>(IE)) {
  805. llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
  806. Value *SVOp = SVI->getOperand(0);
  807. llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
  808. if (OpTy->getNumElements() == ResElts) {
  809. for (unsigned j = 0; j != CurIdx; ++j) {
  810. // If the current vector initializer is a shuffle with undef, merge
  811. // this shuffle directly into it.
  812. if (VIsUndefShuffle) {
  813. Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
  814. CGF.Int32Ty));
  815. } else {
  816. Args.push_back(Builder.getInt32(j));
  817. }
  818. }
  819. for (unsigned j = 0, je = InitElts; j != je; ++j)
  820. Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
  821. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  822. if (VIsUndefShuffle)
  823. V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
  824. Init = SVOp;
  825. }
  826. }
  827. // Extend init to result vector length, and then shuffle its contribution
  828. // to the vector initializer into V.
  829. if (Args.empty()) {
  830. for (unsigned j = 0; j != InitElts; ++j)
  831. Args.push_back(Builder.getInt32(j));
  832. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  833. llvm::Constant *Mask = llvm::ConstantVector::get(Args);
  834. Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
  835. Mask, "vext");
  836. Args.clear();
  837. for (unsigned j = 0; j != CurIdx; ++j)
  838. Args.push_back(Builder.getInt32(j));
  839. for (unsigned j = 0; j != InitElts; ++j)
  840. Args.push_back(Builder.getInt32(j+Offset));
  841. Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
  842. }
  843. // If V is undef, make sure it ends up on the RHS of the shuffle to aid
  844. // merging subsequent shuffles into this one.
  845. if (CurIdx == 0)
  846. std::swap(V, Init);
  847. llvm::Constant *Mask = llvm::ConstantVector::get(Args);
  848. V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
  849. VIsUndefShuffle = isa<llvm::UndefValue>(Init);
  850. CurIdx += InitElts;
  851. }
  852. // FIXME: evaluate codegen vs. shuffling against constant null vector.
  853. // Emit remaining default initializers.
  854. llvm::Type *EltTy = VType->getElementType();
  855. // Emit remaining default initializers
  856. for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
  857. Value *Idx = Builder.getInt32(CurIdx);
  858. llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
  859. V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
  860. }
  861. return V;
  862. }
  863. static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
  864. const Expr *E = CE->getSubExpr();
  865. if (CE->getCastKind() == CK_UncheckedDerivedToBase)
  866. return false;
  867. if (isa<CXXThisExpr>(E)) {
  868. // We always assume that 'this' is never null.
  869. return false;
  870. }
  871. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
  872. // And that glvalue casts are never null.
  873. if (ICE->getValueKind() != VK_RValue)
  874. return false;
  875. }
  876. return true;
  877. }
  878. // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
  879. // have to handle a more broad range of conversions than explicit casts, as they
  880. // handle things like function to ptr-to-function decay etc.
  881. Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
  882. Expr *E = CE->getSubExpr();
  883. QualType DestTy = CE->getType();
  884. CastKind Kind = CE->getCastKind();
  885. if (!DestTy->isVoidType())
  886. TestAndClearIgnoreResultAssign();
  887. // Since almost all cast kinds apply to scalars, this switch doesn't have
  888. // a default case, so the compiler will warn on a missing case. The cases
  889. // are in the same order as in the CastKind enum.
  890. switch (Kind) {
  891. case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
  892. case CK_LValueBitCast:
  893. case CK_ObjCObjectLValueCast: {
  894. Value *V = EmitLValue(E).getAddress();
  895. V = Builder.CreateBitCast(V,
  896. ConvertType(CGF.getContext().getPointerType(DestTy)));
  897. return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
  898. }
  899. case CK_CPointerToObjCPointerCast:
  900. case CK_BlockPointerToObjCPointerCast:
  901. case CK_AnyPointerToBlockPointerCast:
  902. case CK_BitCast: {
  903. Value *Src = Visit(const_cast<Expr*>(E));
  904. return Builder.CreateBitCast(Src, ConvertType(DestTy));
  905. }
  906. case CK_AtomicToNonAtomic:
  907. case CK_NonAtomicToAtomic:
  908. case CK_NoOp:
  909. case CK_UserDefinedConversion:
  910. return Visit(const_cast<Expr*>(E));
  911. case CK_BaseToDerived: {
  912. const CXXRecordDecl *DerivedClassDecl =
  913. DestTy->getCXXRecordDeclForPointerType();
  914. return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
  915. CE->path_begin(), CE->path_end(),
  916. ShouldNullCheckClassCastValue(CE));
  917. }
  918. case CK_UncheckedDerivedToBase:
  919. case CK_DerivedToBase: {
  920. const RecordType *DerivedClassTy =
  921. E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
  922. CXXRecordDecl *DerivedClassDecl =
  923. cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  924. return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
  925. CE->path_begin(), CE->path_end(),
  926. ShouldNullCheckClassCastValue(CE));
  927. }
  928. case CK_Dynamic: {
  929. Value *V = Visit(const_cast<Expr*>(E));
  930. const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
  931. return CGF.EmitDynamicCast(V, DCE);
  932. }
  933. case CK_ArrayToPointerDecay: {
  934. assert(E->getType()->isArrayType() &&
  935. "Array to pointer decay must have array source type!");
  936. Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
  937. // Note that VLA pointers are always decayed, so we don't need to do
  938. // anything here.
  939. if (!E->getType()->isVariableArrayType()) {
  940. assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
  941. assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
  942. ->getElementType()) &&
  943. "Expected pointer to array");
  944. V = Builder.CreateStructGEP(V, 0, "arraydecay");
  945. }
  946. // Make sure the array decay ends up being the right type. This matters if
  947. // the array type was of an incomplete type.
  948. return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
  949. }
  950. case CK_FunctionToPointerDecay:
  951. return EmitLValue(E).getAddress();
  952. case CK_NullToPointer:
  953. if (MustVisitNullValue(E))
  954. (void) Visit(E);
  955. return llvm::ConstantPointerNull::get(
  956. cast<llvm::PointerType>(ConvertType(DestTy)));
  957. case CK_NullToMemberPointer: {
  958. if (MustVisitNullValue(E))
  959. (void) Visit(E);
  960. const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
  961. return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
  962. }
  963. case CK_ReinterpretMemberPointer:
  964. case CK_BaseToDerivedMemberPointer:
  965. case CK_DerivedToBaseMemberPointer: {
  966. Value *Src = Visit(E);
  967. // Note that the AST doesn't distinguish between checked and
  968. // unchecked member pointer conversions, so we always have to
  969. // implement checked conversions here. This is inefficient when
  970. // actual control flow may be required in order to perform the
  971. // check, which it is for data member pointers (but not member
  972. // function pointers on Itanium and ARM).
  973. return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
  974. }
  975. case CK_ARCProduceObject:
  976. return CGF.EmitARCRetainScalarExpr(E);
  977. case CK_ARCConsumeObject:
  978. return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
  979. case CK_ARCReclaimReturnedObject: {
  980. llvm::Value *value = Visit(E);
  981. value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
  982. return CGF.EmitObjCConsumeObject(E->getType(), value);
  983. }
  984. case CK_ARCExtendBlockObject:
  985. return CGF.EmitARCExtendBlockObject(E);
  986. case CK_FloatingRealToComplex:
  987. case CK_FloatingComplexCast:
  988. case CK_IntegralRealToComplex:
  989. case CK_IntegralComplexCast:
  990. case CK_IntegralComplexToFloatingComplex:
  991. case CK_FloatingComplexToIntegralComplex:
  992. case CK_ConstructorConversion:
  993. case CK_ToUnion:
  994. llvm_unreachable("scalar cast to non-scalar value");
  995. case CK_LValueToRValue:
  996. assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
  997. assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
  998. return Visit(const_cast<Expr*>(E));
  999. case CK_IntegralToPointer: {
  1000. Value *Src = Visit(const_cast<Expr*>(E));
  1001. // First, convert to the correct width so that we control the kind of
  1002. // extension.
  1003. llvm::Type *MiddleTy = CGF.IntPtrTy;
  1004. bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
  1005. llvm::Value* IntResult =
  1006. Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
  1007. return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
  1008. }
  1009. case CK_PointerToIntegral:
  1010. assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
  1011. return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
  1012. case CK_ToVoid: {
  1013. CGF.EmitIgnoredExpr(E);
  1014. return 0;
  1015. }
  1016. case CK_VectorSplat: {
  1017. llvm::Type *DstTy = ConvertType(DestTy);
  1018. Value *Elt = Visit(const_cast<Expr*>(E));
  1019. Elt = EmitScalarConversion(Elt, E->getType(),
  1020. DestTy->getAs<VectorType>()->getElementType());
  1021. // Insert the element in element zero of an undef vector
  1022. llvm::Value *UnV = llvm::UndefValue::get(DstTy);
  1023. llvm::Value *Idx = Builder.getInt32(0);
  1024. UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
  1025. // Splat the element across to all elements
  1026. unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
  1027. llvm::Constant *Zero = Builder.getInt32(0);
  1028. llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero);
  1029. llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
  1030. return Yay;
  1031. }
  1032. case CK_IntegralCast:
  1033. case CK_IntegralToFloating:
  1034. case CK_FloatingToIntegral:
  1035. case CK_FloatingCast:
  1036. return EmitScalarConversion(Visit(E), E->getType(), DestTy);
  1037. case CK_IntegralToBoolean:
  1038. return EmitIntToBoolConversion(Visit(E));
  1039. case CK_PointerToBoolean:
  1040. return EmitPointerToBoolConversion(Visit(E));
  1041. case CK_FloatingToBoolean:
  1042. return EmitFloatToBoolConversion(Visit(E));
  1043. case CK_MemberPointerToBoolean: {
  1044. llvm::Value *MemPtr = Visit(E);
  1045. const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
  1046. return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
  1047. }
  1048. case CK_FloatingComplexToReal:
  1049. case CK_IntegralComplexToReal:
  1050. return CGF.EmitComplexExpr(E, false, true).first;
  1051. case CK_FloatingComplexToBoolean:
  1052. case CK_IntegralComplexToBoolean: {
  1053. CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
  1054. // TODO: kill this function off, inline appropriate case here
  1055. return EmitComplexToScalarConversion(V, E->getType(), DestTy);
  1056. }
  1057. }
  1058. llvm_unreachable("unknown scalar cast");
  1059. }
  1060. Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
  1061. CodeGenFunction::StmtExprEvaluation eval(CGF);
  1062. return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
  1063. .getScalarVal();
  1064. }
  1065. Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
  1066. LValue LV = CGF.EmitBlockDeclRefLValue(E);
  1067. return CGF.EmitLoadOfLValue(LV).getScalarVal();
  1068. }
  1069. //===----------------------------------------------------------------------===//
  1070. // Unary Operators
  1071. //===----------------------------------------------------------------------===//
  1072. llvm::Value *ScalarExprEmitter::
  1073. EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
  1074. llvm::Value *InVal,
  1075. llvm::Value *NextVal, bool IsInc) {
  1076. switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
  1077. case LangOptions::SOB_Undefined:
  1078. return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
  1079. case LangOptions::SOB_Defined:
  1080. return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
  1081. case LangOptions::SOB_Trapping:
  1082. BinOpInfo BinOp;
  1083. BinOp.LHS = InVal;
  1084. BinOp.RHS = NextVal;
  1085. BinOp.Ty = E->getType();
  1086. BinOp.Opcode = BO_Add;
  1087. BinOp.E = E;
  1088. return EmitOverflowCheckedBinOp(BinOp);
  1089. }
  1090. llvm_unreachable("Unknown SignedOverflowBehaviorTy");
  1091. }
  1092. llvm::Value *
  1093. ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  1094. bool isInc, bool isPre) {
  1095. QualType type = E->getSubExpr()->getType();
  1096. llvm::Value *value = EmitLoadOfLValue(LV);
  1097. llvm::Value *input = value;
  1098. llvm::PHINode *atomicPHI = 0;
  1099. int amount = (isInc ? 1 : -1);
  1100. if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
  1101. llvm::BasicBlock *startBB = Builder.GetInsertBlock();
  1102. llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
  1103. Builder.CreateBr(opBB);
  1104. Builder.SetInsertPoint(opBB);
  1105. atomicPHI = Builder.CreatePHI(value->getType(), 2);
  1106. atomicPHI->addIncoming(value, startBB);
  1107. type = atomicTy->getValueType();
  1108. value = atomicPHI;
  1109. }
  1110. // Special case of integer increment that we have to check first: bool++.
  1111. // Due to promotion rules, we get:
  1112. // bool++ -> bool = bool + 1
  1113. // -> bool = (int)bool + 1
  1114. // -> bool = ((int)bool + 1 != 0)
  1115. // An interesting aspect of this is that increment is always true.
  1116. // Decrement does not have this property.
  1117. if (isInc && type->isBooleanType()) {
  1118. value = Builder.getTrue();
  1119. // Most common case by far: integer increment.
  1120. } else if (type->isIntegerType()) {
  1121. llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
  1122. // Note that signed integer inc/dec with width less than int can't
  1123. // overflow because of promotion rules; we're just eliding a few steps here.
  1124. if (type->isSignedIntegerOrEnumerationType() &&
  1125. value->getType()->getPrimitiveSizeInBits() >=
  1126. CGF.IntTy->getBitWidth())
  1127. value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
  1128. else
  1129. value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
  1130. // Next most common: pointer increment.
  1131. } else if (const PointerType *ptr = type->getAs<PointerType>()) {
  1132. QualType type = ptr->getPointeeType();
  1133. // VLA types don't have constant size.
  1134. if (const VariableArrayType *vla
  1135. = CGF.getContext().getAsVariableArrayType(type)) {
  1136. llvm::Value *numElts = CGF.getVLASize(vla).first;
  1137. if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
  1138. if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
  1139. value = Builder.CreateGEP(value, numElts, "vla.inc");
  1140. else
  1141. value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
  1142. // Arithmetic on function pointers (!) is just +-1.
  1143. } else if (type->isFunctionType()) {
  1144. llvm::Value *amt = Builder.getInt32(amount);
  1145. value = CGF.EmitCastToVoidPtr(value);
  1146. if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
  1147. value = Builder.CreateGEP(value, amt, "incdec.funcptr");
  1148. else
  1149. value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
  1150. value = Builder.CreateBitCast(value, input->getType());
  1151. // For everything else, we can just do a simple increment.
  1152. } else {
  1153. llvm::Value *amt = Builder.getInt32(amount);
  1154. if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
  1155. value = Builder.CreateGEP(value, amt, "incdec.ptr");
  1156. else
  1157. value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
  1158. }
  1159. // Vector increment/decrement.
  1160. } else if (type->isVectorType()) {
  1161. if (type->hasIntegerRepresentation()) {
  1162. llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
  1163. value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
  1164. } else {
  1165. value = Builder.CreateFAdd(
  1166. value,
  1167. llvm::ConstantFP::get(value->getType(), amount),
  1168. isInc ? "inc" : "dec");
  1169. }
  1170. // Floating point.
  1171. } else if (type->isRealFloatingType()) {
  1172. // Add the inc/dec to the real part.
  1173. llvm::Value *amt;
  1174. if (type->isHalfType()) {
  1175. // Another special case: half FP increment should be done via float
  1176. value =
  1177. Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
  1178. input);
  1179. }
  1180. if (value->getType()->isFloatTy())
  1181. amt = llvm::ConstantFP::get(VMContext,
  1182. llvm::APFloat(static_cast<float>(amount)));
  1183. else if (value->getType()->isDoubleTy())
  1184. amt = llvm::ConstantFP::get(VMContext,
  1185. llvm::APFloat(static_cast<double>(amount)));
  1186. else {
  1187. llvm::APFloat F(static_cast<float>(amount));
  1188. bool ignored;
  1189. F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
  1190. &ignored);
  1191. amt = llvm::ConstantFP::get(VMContext, F);
  1192. }
  1193. value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
  1194. if (type->isHalfType())
  1195. value =
  1196. Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
  1197. value);
  1198. // Objective-C pointer types.
  1199. } else {
  1200. const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
  1201. value = CGF.EmitCastToVoidPtr(value);
  1202. CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
  1203. if (!isInc) size = -size;
  1204. llvm::Value *sizeValue =
  1205. llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
  1206. if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
  1207. value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
  1208. else
  1209. value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
  1210. value = Builder.CreateBitCast(value, input->getType());
  1211. }
  1212. if (atomicPHI) {
  1213. llvm::BasicBlock *opBB = Builder.GetInsertBlock();
  1214. llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
  1215. llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
  1216. value, llvm::SequentiallyConsistent);
  1217. atomicPHI->addIncoming(old, opBB);
  1218. llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
  1219. Builder.CreateCondBr(success, contBB, opBB);
  1220. Builder.SetInsertPoint(contBB);
  1221. return isPre ? value : input;
  1222. }
  1223. // Store the updated result through the lvalue.
  1224. if (LV.isBitField())
  1225. CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
  1226. else
  1227. CGF.EmitStoreThroughLValue(RValue::get(value), LV);
  1228. // If this is a postinc, return the value read from memory, otherwise use the
  1229. // updated value.
  1230. return isPre ? value : input;
  1231. }
  1232. Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
  1233. TestAndClearIgnoreResultAssign();
  1234. // Emit unary minus with EmitSub so we handle overflow cases etc.
  1235. BinOpInfo BinOp;
  1236. BinOp.RHS = Visit(E->getSubExpr());
  1237. if (BinOp.RHS->getType()->isFPOrFPVectorTy())
  1238. BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
  1239. else
  1240. BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
  1241. BinOp.Ty = E->getType();
  1242. BinOp.Opcode = BO_Sub;
  1243. BinOp.E = E;
  1244. return EmitSub(BinOp);
  1245. }
  1246. Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
  1247. TestAndClearIgnoreResultAssign();
  1248. Value *Op = Visit(E->getSubExpr());
  1249. return Builder.CreateNot(Op, "neg");
  1250. }
  1251. Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
  1252. // Perform vector logical not on comparison with zero vector.
  1253. if (E->getType()->isExtVectorType()) {
  1254. Value *Oper = Visit(E->getSubExpr());
  1255. Value *Zero = llvm::Constant::getNullValue(Oper->getType());
  1256. Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
  1257. return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
  1258. }
  1259. // Compare operand to zero.
  1260. Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
  1261. // Invert value.
  1262. // TODO: Could dynamically modify easy computations here. For example, if
  1263. // the operand is an icmp ne, turn into icmp eq.
  1264. BoolVal = Builder.CreateNot(BoolVal, "lnot");
  1265. // ZExt result to the expr type.
  1266. return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
  1267. }
  1268. Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
  1269. // Try folding the offsetof to a constant.
  1270. llvm::APSInt Value;
  1271. if (E->EvaluateAsInt(Value, CGF.getContext()))
  1272. return Builder.getInt(Value);
  1273. // Loop over the components of the offsetof to compute the value.
  1274. unsigned n = E->getNumComponents();
  1275. llvm::Type* ResultType = ConvertType(E->getType());
  1276. llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
  1277. QualType CurrentType = E->getTypeSourceInfo()->getType();
  1278. for (unsigned i = 0; i != n; ++i) {
  1279. OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
  1280. llvm::Value *Offset = 0;
  1281. switch (ON.getKind()) {
  1282. case OffsetOfExpr::OffsetOfNode::Array: {
  1283. // Compute the index
  1284. Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
  1285. llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
  1286. bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
  1287. Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
  1288. // Save the element type
  1289. CurrentType =
  1290. CGF.getContext().getAsArrayType(CurrentType)->getElementType();
  1291. // Compute the element size
  1292. llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
  1293. CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
  1294. // Multiply out to compute the result
  1295. Offset = Builder.CreateMul(Idx, ElemSize);
  1296. break;
  1297. }
  1298. case OffsetOfExpr::OffsetOfNode::Field: {
  1299. FieldDecl *MemberDecl = ON.getField();
  1300. RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
  1301. const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
  1302. // Compute the index of the field in its parent.
  1303. unsigned i = 0;
  1304. // FIXME: It would be nice if we didn't have to loop here!
  1305. for (RecordDecl::field_iterator Field = RD->field_begin(),
  1306. FieldEnd = RD->field_end();
  1307. Field != FieldEnd; (void)++Field, ++i) {
  1308. if (*Field == MemberDecl)
  1309. break;
  1310. }
  1311. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  1312. // Compute the offset to the field
  1313. int64_t OffsetInt = RL.getFieldOffset(i) /
  1314. CGF.getContext().getCharWidth();
  1315. Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
  1316. // Save the element type.
  1317. CurrentType = MemberDecl->getType();
  1318. break;
  1319. }
  1320. case OffsetOfExpr::OffsetOfNode::Identifier:
  1321. llvm_unreachable("dependent __builtin_offsetof");
  1322. case OffsetOfExpr::OffsetOfNode::Base: {
  1323. if (ON.getBase()->isVirtual()) {
  1324. CGF.ErrorUnsupported(E, "virtual base in offsetof");
  1325. continue;
  1326. }
  1327. RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
  1328. const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
  1329. // Save the element type.
  1330. CurrentType = ON.getBase()->getType();
  1331. // Compute the offset to the base.
  1332. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  1333. CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
  1334. int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
  1335. CGF.getContext().getCharWidth();
  1336. Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
  1337. break;
  1338. }
  1339. }
  1340. Result = Builder.CreateAdd(Result, Offset);
  1341. }
  1342. return Result;
  1343. }
  1344. /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
  1345. /// argument of the sizeof expression as an integer.
  1346. Value *
  1347. ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
  1348. const UnaryExprOrTypeTraitExpr *E) {
  1349. QualType TypeToSize = E->getTypeOfArgument();
  1350. if (E->getKind() == UETT_SizeOf) {
  1351. if (const VariableArrayType *VAT =
  1352. CGF.getContext().getAsVariableArrayType(TypeToSize)) {
  1353. if (E->isArgumentType()) {
  1354. // sizeof(type) - make sure to emit the VLA size.
  1355. CGF.EmitVariablyModifiedType(TypeToSize);
  1356. } else {
  1357. // C99 6.5.3.4p2: If the argument is an expression of type
  1358. // VLA, it is evaluated.
  1359. CGF.EmitIgnoredExpr(E->getArgumentExpr());
  1360. }
  1361. QualType eltType;
  1362. llvm::Value *numElts;
  1363. llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
  1364. llvm::Value *size = numElts;
  1365. // Scale the number of non-VLA elements by the non-VLA element size.
  1366. CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
  1367. if (!eltSize.isOne())
  1368. size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
  1369. return size;
  1370. }
  1371. }
  1372. // If this isn't sizeof(vla), the result must be constant; use the constant
  1373. // folding logic so we don't have to duplicate it here.
  1374. return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
  1375. }
  1376. Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
  1377. Expr *Op = E->getSubExpr();
  1378. if (Op->getType()->isAnyComplexType()) {
  1379. // If it's an l-value, load through the appropriate subobject l-value.
  1380. // Note that we have to ask E because Op might be an l-value that
  1381. // this won't work for, e.g. an Obj-C property.
  1382. if (E->isGLValue())
  1383. return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
  1384. // Otherwise, calculate and project.
  1385. return CGF.EmitComplexExpr(Op, false, true).first;
  1386. }
  1387. return Visit(Op);
  1388. }
  1389. Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
  1390. Expr *Op = E->getSubExpr();
  1391. if (Op->getType()->isAnyComplexType()) {
  1392. // If it's an l-value, load through the appropriate subobject l-value.
  1393. // Note that we have to ask E because Op might be an l-value that
  1394. // this won't work for, e.g. an Obj-C property.
  1395. if (Op->isGLValue())
  1396. return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
  1397. // Otherwise, calculate and project.
  1398. return CGF.EmitComplexExpr(Op, true, false).second;
  1399. }
  1400. // __imag on a scalar returns zero. Emit the subexpr to ensure side
  1401. // effects are evaluated, but not the actual value.
  1402. CGF.EmitScalarExpr(Op, true);
  1403. return llvm::Constant::getNullValue(ConvertType(E->getType()));
  1404. }
  1405. //===----------------------------------------------------------------------===//
  1406. // Binary Operators
  1407. //===----------------------------------------------------------------------===//
  1408. BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
  1409. TestAndClearIgnoreResultAssign();
  1410. BinOpInfo Result;
  1411. Result.LHS = Visit(E->getLHS());
  1412. Result.RHS = Visit(E->getRHS());
  1413. Result.Ty = E->getType();
  1414. Result.Opcode = E->getOpcode();
  1415. Result.E = E;
  1416. return Result;
  1417. }
  1418. LValue ScalarExprEmitter::EmitCompoundAssignLValue(
  1419. const CompoundAssignOperator *E,
  1420. Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
  1421. Value *&Result) {
  1422. QualType LHSTy = E->getLHS()->getType();
  1423. BinOpInfo OpInfo;
  1424. if (E->getComputationResultType()->isAnyComplexType()) {
  1425. // This needs to go through the complex expression emitter, but it's a tad
  1426. // complicated to do that... I'm leaving it out for now. (Note that we do
  1427. // actually need the imaginary part of the RHS for multiplication and
  1428. // division.)
  1429. CGF.ErrorUnsupported(E, "complex compound assignment");
  1430. Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
  1431. return LValue();
  1432. }
  1433. // Emit the RHS first. __block variables need to have the rhs evaluated
  1434. // first, plus this should improve codegen a little.
  1435. OpInfo.RHS = Visit(E->getRHS());
  1436. OpInfo.Ty = E->getComputationResultType();
  1437. OpInfo.Opcode = E->getOpcode();
  1438. OpInfo.E = E;
  1439. // Load/convert the LHS.
  1440. LValue LHSLV = EmitCheckedLValue(E->getLHS());
  1441. OpInfo.LHS = EmitLoadOfLValue(LHSLV);
  1442. OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
  1443. E->getComputationLHSType());
  1444. llvm::PHINode *atomicPHI = 0;
  1445. if (const AtomicType *atomicTy = OpInfo.Ty->getAs<AtomicType>()) {
  1446. // FIXME: For floating point types, we should be saving and restoring the
  1447. // floating point environment in the loop.
  1448. llvm::BasicBlock *startBB = Builder.GetInsertBlock();
  1449. llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
  1450. Builder.CreateBr(opBB);
  1451. Builder.SetInsertPoint(opBB);
  1452. atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
  1453. atomicPHI->addIncoming(OpInfo.LHS, startBB);
  1454. OpInfo.Ty = atomicTy->getValueType();
  1455. OpInfo.LHS = atomicPHI;
  1456. }
  1457. // Expand the binary operator.
  1458. Result = (this->*Func)(OpInfo);
  1459. // Convert the result back to the LHS type.
  1460. Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
  1461. if (atomicPHI) {
  1462. llvm::BasicBlock *opBB = Builder.GetInsertBlock();
  1463. llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
  1464. llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
  1465. Result, llvm::SequentiallyConsistent);
  1466. atomicPHI->addIncoming(old, opBB);
  1467. llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
  1468. Builder.CreateCondBr(success, contBB, opBB);
  1469. Builder.SetInsertPoint(contBB);
  1470. return LHSLV;
  1471. }
  1472. // Store the result value into the LHS lvalue. Bit-fields are handled
  1473. // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
  1474. // 'An assignment expression has the value of the left operand after the
  1475. // assignment...'.
  1476. if (LHSLV.isBitField())
  1477. CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
  1478. else
  1479. CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
  1480. return LHSLV;
  1481. }
  1482. Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
  1483. Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
  1484. bool Ignore = TestAndClearIgnoreResultAssign();
  1485. Value *RHS;
  1486. LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
  1487. // If the result is clearly ignored, return now.
  1488. if (Ignore)
  1489. return 0;
  1490. // The result of an assignment in C is the assigned r-value.
  1491. if (!CGF.getContext().getLangOptions().CPlusPlus)
  1492. return RHS;
  1493. // If the lvalue is non-volatile, return the computed value of the assignment.
  1494. if (!LHS.isVolatileQualified())
  1495. return RHS;
  1496. // Otherwise, reload the value.
  1497. return EmitLoadOfLValue(LHS);
  1498. }
  1499. void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
  1500. const BinOpInfo &Ops,
  1501. llvm::Value *Zero, bool isDiv) {
  1502. llvm::Function::iterator insertPt = Builder.GetInsertBlock();
  1503. llvm::BasicBlock *contBB =
  1504. CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn,
  1505. llvm::next(insertPt));
  1506. llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
  1507. llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
  1508. if (Ops.Ty->hasSignedIntegerRepresentation()) {
  1509. llvm::Value *IntMin =
  1510. Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
  1511. llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
  1512. llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
  1513. llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
  1514. llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
  1515. llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
  1516. Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
  1517. overflowBB, contBB);
  1518. } else {
  1519. CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
  1520. overflowBB, contBB);
  1521. }
  1522. EmitOverflowBB(overflowBB);
  1523. Builder.SetInsertPoint(contBB);
  1524. }
  1525. Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
  1526. if (isTrapvOverflowBehavior()) {
  1527. llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
  1528. if (Ops.Ty->isIntegerType())
  1529. EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
  1530. else if (Ops.Ty->isRealFloatingType()) {
  1531. llvm::Function::iterator insertPt = Builder.GetInsertBlock();
  1532. llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn,
  1533. llvm::next(insertPt));
  1534. llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
  1535. CGF.CurFn);
  1536. CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
  1537. overflowBB, DivCont);
  1538. EmitOverflowBB(overflowBB);
  1539. Builder.SetInsertPoint(DivCont);
  1540. }
  1541. }
  1542. if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
  1543. llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
  1544. if (CGF.getContext().getLangOptions().OpenCL) {
  1545. // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
  1546. llvm::Type *ValTy = Val->getType();
  1547. if (ValTy->isFloatTy() ||
  1548. (isa<llvm::VectorType>(ValTy) &&
  1549. cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
  1550. CGF.SetFPAccuracy(Val, 5, 2);
  1551. }
  1552. return Val;
  1553. }
  1554. else if (Ops.Ty->hasUnsignedIntegerRepresentation())
  1555. return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
  1556. else
  1557. return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
  1558. }
  1559. Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
  1560. // Rem in C can't be a floating point type: C99 6.5.5p2.
  1561. if (isTrapvOverflowBehavior()) {
  1562. llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
  1563. if (Ops.Ty->isIntegerType())
  1564. EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
  1565. }
  1566. if (Ops.Ty->hasUnsignedIntegerRepresentation())
  1567. return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
  1568. else
  1569. return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
  1570. }
  1571. Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
  1572. unsigned IID;
  1573. unsigned OpID = 0;
  1574. switch (Ops.Opcode) {
  1575. case BO_Add:
  1576. case BO_AddAssign:
  1577. OpID = 1;
  1578. IID = llvm::Intrinsic::sadd_with_overflow;
  1579. break;
  1580. case BO_Sub:
  1581. case BO_SubAssign:
  1582. OpID = 2;
  1583. IID = llvm::Intrinsic::ssub_with_overflow;
  1584. break;
  1585. case BO_Mul:
  1586. case BO_MulAssign:
  1587. OpID = 3;
  1588. IID = llvm::Intrinsic::smul_with_overflow;
  1589. break;
  1590. default:
  1591. llvm_unreachable("Unsupported operation for overflow detection");
  1592. }
  1593. OpID <<= 1;
  1594. OpID |= 1;
  1595. llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
  1596. llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
  1597. Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
  1598. Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
  1599. Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
  1600. // Branch in case of overflow.
  1601. llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
  1602. llvm::Function::iterator insertPt = initialBB;
  1603. llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
  1604. llvm::next(insertPt));
  1605. llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
  1606. Builder.CreateCondBr(overflow, overflowBB, continueBB);
  1607. // Handle overflow with llvm.trap.
  1608. const std::string *handlerName =
  1609. &CGF.getContext().getLangOptions().OverflowHandler;
  1610. if (handlerName->empty()) {
  1611. EmitOverflowBB(overflowBB);
  1612. Builder.SetInsertPoint(continueBB);
  1613. return result;
  1614. }
  1615. // If an overflow handler is set, then we want to call it and then use its
  1616. // result, if it returns.
  1617. Builder.SetInsertPoint(overflowBB);
  1618. // Get the overflow handler.
  1619. llvm::Type *Int8Ty = CGF.Int8Ty;
  1620. llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
  1621. llvm::FunctionType *handlerTy =
  1622. llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
  1623. llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
  1624. // Sign extend the args to 64-bit, so that we can use the same handler for
  1625. // all types of overflow.
  1626. llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
  1627. llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
  1628. // Call the handler with the two arguments, the operation, and the size of
  1629. // the result.
  1630. llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
  1631. Builder.getInt8(OpID),
  1632. Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
  1633. // Truncate the result back to the desired size.
  1634. handlerResult = Builder.CreateTrunc(handlerResult, opTy);
  1635. Builder.CreateBr(continueBB);
  1636. Builder.SetInsertPoint(continueBB);
  1637. llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
  1638. phi->addIncoming(result, initialBB);
  1639. phi->addIncoming(handlerResult, overflowBB);
  1640. return phi;
  1641. }
  1642. /// Emit pointer + index arithmetic.
  1643. static Value *emitPointerArithmetic(CodeGenFunction &CGF,
  1644. const BinOpInfo &op,
  1645. bool isSubtraction) {
  1646. // Must have binary (not unary) expr here. Unary pointer
  1647. // increment/decrement doesn't use this path.
  1648. const BinaryOperator *expr = cast<BinaryOperator>(op.E);
  1649. Value *pointer = op.LHS;
  1650. Expr *pointerOperand = expr->getLHS();
  1651. Value *index = op.RHS;
  1652. Expr *indexOperand = expr->getRHS();
  1653. // In a subtraction, the LHS is always the pointer.
  1654. if (!isSubtraction && !pointer->getType()->isPointerTy()) {
  1655. std::swap(pointer, index);
  1656. std::swap(pointerOperand, indexOperand);
  1657. }
  1658. unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
  1659. if (width != CGF.PointerWidthInBits) {
  1660. // Zero-extend or sign-extend the pointer value according to
  1661. // whether the index is signed or not.
  1662. bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
  1663. index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
  1664. "idx.ext");
  1665. }
  1666. // If this is subtraction, negate the index.
  1667. if (isSubtraction)
  1668. index = CGF.Builder.CreateNeg(index, "idx.neg");
  1669. const PointerType *pointerType
  1670. = pointerOperand->getType()->getAs<PointerType>();
  1671. if (!pointerType) {
  1672. QualType objectType = pointerOperand->getType()
  1673. ->castAs<ObjCObjectPointerType>()
  1674. ->getPointeeType();
  1675. llvm::Value *objectSize
  1676. = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
  1677. index = CGF.Builder.CreateMul(index, objectSize);
  1678. Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
  1679. result = CGF.Builder.CreateGEP(result, index, "add.ptr");
  1680. return CGF.Builder.CreateBitCast(result, pointer->getType());
  1681. }
  1682. QualType elementType = pointerType->getPointeeType();
  1683. if (const VariableArrayType *vla
  1684. = CGF.getContext().getAsVariableArrayType(elementType)) {
  1685. // The element count here is the total number of non-VLA elements.
  1686. llvm::Value *numElements = CGF.getVLASize(vla).first;
  1687. // Effectively, the multiply by the VLA size is part of the GEP.
  1688. // GEP indexes are signed, and scaling an index isn't permitted to
  1689. // signed-overflow, so we use the same semantics for our explicit
  1690. // multiply. We suppress this if overflow is not undefined behavior.
  1691. if (CGF.getLangOptions().isSignedOverflowDefined()) {
  1692. index = CGF.Builder.CreateMul(index, numElements, "vla.index");
  1693. pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
  1694. } else {
  1695. index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
  1696. pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
  1697. }
  1698. return pointer;
  1699. }
  1700. // Explicitly handle GNU void* and function pointer arithmetic extensions. The
  1701. // GNU void* casts amount to no-ops since our void* type is i8*, but this is
  1702. // future proof.
  1703. if (elementType->isVoidType() || elementType->isFunctionType()) {
  1704. Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
  1705. result = CGF.Builder.CreateGEP(result, index, "add.ptr");
  1706. return CGF.Builder.CreateBitCast(result, pointer->getType());
  1707. }
  1708. if (CGF.getLangOptions().isSignedOverflowDefined())
  1709. return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
  1710. return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
  1711. }
  1712. Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
  1713. if (op.LHS->getType()->isPointerTy() ||
  1714. op.RHS->getType()->isPointerTy())
  1715. return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
  1716. if (op.Ty->isSignedIntegerOrEnumerationType()) {
  1717. switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
  1718. case LangOptions::SOB_Undefined:
  1719. return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
  1720. case LangOptions::SOB_Defined:
  1721. return Builder.CreateAdd(op.LHS, op.RHS, "add");
  1722. case LangOptions::SOB_Trapping:
  1723. return EmitOverflowCheckedBinOp(op);
  1724. }
  1725. }
  1726. if (op.LHS->getType()->isFPOrFPVectorTy())
  1727. return Builder.CreateFAdd(op.LHS, op.RHS, "add");
  1728. return Builder.CreateAdd(op.LHS, op.RHS, "add");
  1729. }
  1730. Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
  1731. // The LHS is always a pointer if either side is.
  1732. if (!op.LHS->getType()->isPointerTy()) {
  1733. if (op.Ty->isSignedIntegerOrEnumerationType()) {
  1734. switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
  1735. case LangOptions::SOB_Undefined:
  1736. return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
  1737. case LangOptions::SOB_Defined:
  1738. return Builder.CreateSub(op.LHS, op.RHS, "sub");
  1739. case LangOptions::SOB_Trapping:
  1740. return EmitOverflowCheckedBinOp(op);
  1741. }
  1742. }
  1743. if (op.LHS->getType()->isFPOrFPVectorTy())
  1744. return Builder.CreateFSub(op.LHS, op.RHS, "sub");
  1745. return Builder.CreateSub(op.LHS, op.RHS, "sub");
  1746. }
  1747. // If the RHS is not a pointer, then we have normal pointer
  1748. // arithmetic.
  1749. if (!op.RHS->getType()->isPointerTy())
  1750. return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
  1751. // Otherwise, this is a pointer subtraction.
  1752. // Do the raw subtraction part.
  1753. llvm::Value *LHS
  1754. = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
  1755. llvm::Value *RHS
  1756. = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
  1757. Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
  1758. // Okay, figure out the element size.
  1759. const BinaryOperator *expr = cast<BinaryOperator>(op.E);
  1760. QualType elementType = expr->getLHS()->getType()->getPointeeType();
  1761. llvm::Value *divisor = 0;
  1762. // For a variable-length array, this is going to be non-constant.
  1763. if (const VariableArrayType *vla
  1764. = CGF.getContext().getAsVariableArrayType(elementType)) {
  1765. llvm::Value *numElements;
  1766. llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
  1767. divisor = numElements;
  1768. // Scale the number of non-VLA elements by the non-VLA element size.
  1769. CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
  1770. if (!eltSize.isOne())
  1771. divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
  1772. // For everything elese, we can just compute it, safe in the
  1773. // assumption that Sema won't let anything through that we can't
  1774. // safely compute the size of.
  1775. } else {
  1776. CharUnits elementSize;
  1777. // Handle GCC extension for pointer arithmetic on void* and
  1778. // function pointer types.
  1779. if (elementType->isVoidType() || elementType->isFunctionType())
  1780. elementSize = CharUnits::One();
  1781. else
  1782. elementSize = CGF.getContext().getTypeSizeInChars(elementType);
  1783. // Don't even emit the divide for element size of 1.
  1784. if (elementSize.isOne())
  1785. return diffInChars;
  1786. divisor = CGF.CGM.getSize(elementSize);
  1787. }
  1788. // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
  1789. // pointer difference in C is only defined in the case where both operands
  1790. // are pointing to elements of an array.
  1791. return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
  1792. }
  1793. Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
  1794. // LLVM requires the LHS and RHS to be the same type: promote or truncate the
  1795. // RHS to the same size as the LHS.
  1796. Value *RHS = Ops.RHS;
  1797. if (Ops.LHS->getType() != RHS->getType())
  1798. RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
  1799. if (CGF.CatchUndefined
  1800. && isa<llvm::IntegerType>(Ops.LHS->getType())) {
  1801. unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
  1802. llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
  1803. CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
  1804. llvm::ConstantInt::get(RHS->getType(), Width)),
  1805. Cont, CGF.getTrapBB());
  1806. CGF.EmitBlock(Cont);
  1807. }
  1808. return Builder.CreateShl(Ops.LHS, RHS, "shl");
  1809. }
  1810. Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
  1811. // LLVM requires the LHS and RHS to be the same type: promote or truncate the
  1812. // RHS to the same size as the LHS.
  1813. Value *RHS = Ops.RHS;
  1814. if (Ops.LHS->getType() != RHS->getType())
  1815. RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
  1816. if (CGF.CatchUndefined
  1817. && isa<llvm::IntegerType>(Ops.LHS->getType())) {
  1818. unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
  1819. llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
  1820. CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
  1821. llvm::ConstantInt::get(RHS->getType(), Width)),
  1822. Cont, CGF.getTrapBB());
  1823. CGF.EmitBlock(Cont);
  1824. }
  1825. if (Ops.Ty->hasUnsignedIntegerRepresentation())
  1826. return Builder.CreateLShr(Ops.LHS, RHS, "shr");
  1827. return Builder.CreateAShr(Ops.LHS, RHS, "shr");
  1828. }
  1829. enum IntrinsicType { VCMPEQ, VCMPGT };
  1830. // return corresponding comparison intrinsic for given vector type
  1831. static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
  1832. BuiltinType::Kind ElemKind) {
  1833. switch (ElemKind) {
  1834. default: llvm_unreachable("unexpected element type");
  1835. case BuiltinType::Char_U:
  1836. case BuiltinType::UChar:
  1837. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
  1838. llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
  1839. case BuiltinType::Char_S:
  1840. case BuiltinType::SChar:
  1841. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
  1842. llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
  1843. case BuiltinType::UShort:
  1844. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
  1845. llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
  1846. case BuiltinType::Short:
  1847. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
  1848. llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
  1849. case BuiltinType::UInt:
  1850. case BuiltinType::ULong:
  1851. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
  1852. llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
  1853. case BuiltinType::Int:
  1854. case BuiltinType::Long:
  1855. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
  1856. llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
  1857. case BuiltinType::Float:
  1858. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
  1859. llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
  1860. }
  1861. }
  1862. Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
  1863. unsigned SICmpOpc, unsigned FCmpOpc) {
  1864. TestAndClearIgnoreResultAssign();
  1865. Value *Result;
  1866. QualType LHSTy = E->getLHS()->getType();
  1867. if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
  1868. assert(E->getOpcode() == BO_EQ ||
  1869. E->getOpcode() == BO_NE);
  1870. Value *LHS = CGF.EmitScalarExpr(E->getLHS());
  1871. Value *RHS = CGF.EmitScalarExpr(E->getRHS());
  1872. Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
  1873. CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
  1874. } else if (!LHSTy->isAnyComplexType()) {
  1875. Value *LHS = Visit(E->getLHS());
  1876. Value *RHS = Visit(E->getRHS());
  1877. // If AltiVec, the comparison results in a numeric type, so we use
  1878. // intrinsics comparing vectors and giving 0 or 1 as a result
  1879. if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
  1880. // constants for mapping CR6 register bits to predicate result
  1881. enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
  1882. llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
  1883. // in several cases vector arguments order will be reversed
  1884. Value *FirstVecArg = LHS,
  1885. *SecondVecArg = RHS;
  1886. QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
  1887. const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
  1888. BuiltinType::Kind ElementKind = BTy->getKind();
  1889. switch(E->getOpcode()) {
  1890. default: llvm_unreachable("is not a comparison operation");
  1891. case BO_EQ:
  1892. CR6 = CR6_LT;
  1893. ID = GetIntrinsic(VCMPEQ, ElementKind);
  1894. break;
  1895. case BO_NE:
  1896. CR6 = CR6_EQ;
  1897. ID = GetIntrinsic(VCMPEQ, ElementKind);
  1898. break;
  1899. case BO_LT:
  1900. CR6 = CR6_LT;
  1901. ID = GetIntrinsic(VCMPGT, ElementKind);
  1902. std::swap(FirstVecArg, SecondVecArg);
  1903. break;
  1904. case BO_GT:
  1905. CR6 = CR6_LT;
  1906. ID = GetIntrinsic(VCMPGT, ElementKind);
  1907. break;
  1908. case BO_LE:
  1909. if (ElementKind == BuiltinType::Float) {
  1910. CR6 = CR6_LT;
  1911. ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
  1912. std::swap(FirstVecArg, SecondVecArg);
  1913. }
  1914. else {
  1915. CR6 = CR6_EQ;
  1916. ID = GetIntrinsic(VCMPGT, ElementKind);
  1917. }
  1918. break;
  1919. case BO_GE:
  1920. if (ElementKind == BuiltinType::Float) {
  1921. CR6 = CR6_LT;
  1922. ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
  1923. }
  1924. else {
  1925. CR6 = CR6_EQ;
  1926. ID = GetIntrinsic(VCMPGT, ElementKind);
  1927. std::swap(FirstVecArg, SecondVecArg);
  1928. }
  1929. break;
  1930. }
  1931. Value *CR6Param = Builder.getInt32(CR6);
  1932. llvm::Function *F = CGF.CGM.getIntrinsic(ID);
  1933. Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
  1934. return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
  1935. }
  1936. if (LHS->getType()->isFPOrFPVectorTy()) {
  1937. Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
  1938. LHS, RHS, "cmp");
  1939. } else if (LHSTy->hasSignedIntegerRepresentation()) {
  1940. Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
  1941. LHS, RHS, "cmp");
  1942. } else {
  1943. // Unsigned integers and pointers.
  1944. Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
  1945. LHS, RHS, "cmp");
  1946. }
  1947. // If this is a vector comparison, sign extend the result to the appropriate
  1948. // vector integer type and return it (don't convert to bool).
  1949. if (LHSTy->isVectorType())
  1950. return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
  1951. } else {
  1952. // Complex Comparison: can only be an equality comparison.
  1953. CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
  1954. CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
  1955. QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
  1956. Value *ResultR, *ResultI;
  1957. if (CETy->isRealFloatingType()) {
  1958. ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
  1959. LHS.first, RHS.first, "cmp.r");
  1960. ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
  1961. LHS.second, RHS.second, "cmp.i");
  1962. } else {
  1963. // Complex comparisons can only be equality comparisons. As such, signed
  1964. // and unsigned opcodes are the same.
  1965. ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
  1966. LHS.first, RHS.first, "cmp.r");
  1967. ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
  1968. LHS.second, RHS.second, "cmp.i");
  1969. }
  1970. if (E->getOpcode() == BO_EQ) {
  1971. Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
  1972. } else {
  1973. assert(E->getOpcode() == BO_NE &&
  1974. "Complex comparison other than == or != ?");
  1975. Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
  1976. }
  1977. }
  1978. return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
  1979. }
  1980. Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
  1981. bool Ignore = TestAndClearIgnoreResultAssign();
  1982. Value *RHS;
  1983. LValue LHS;
  1984. switch (E->getLHS()->getType().getObjCLifetime()) {
  1985. case Qualifiers::OCL_Strong:
  1986. llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
  1987. break;
  1988. case Qualifiers::OCL_Autoreleasing:
  1989. llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
  1990. break;
  1991. case Qualifiers::OCL_Weak:
  1992. RHS = Visit(E->getRHS());
  1993. LHS = EmitCheckedLValue(E->getLHS());
  1994. RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
  1995. break;
  1996. // No reason to do any of these differently.
  1997. case Qualifiers::OCL_None:
  1998. case Qualifiers::OCL_ExplicitNone:
  1999. // __block variables need to have the rhs evaluated first, plus
  2000. // this should improve codegen just a little.
  2001. RHS = Visit(E->getRHS());
  2002. LHS = EmitCheckedLValue(E->getLHS());
  2003. // Store the value into the LHS. Bit-fields are handled specially
  2004. // because the result is altered by the store, i.e., [C99 6.5.16p1]
  2005. // 'An assignment expression has the value of the left operand after
  2006. // the assignment...'.
  2007. if (LHS.isBitField())
  2008. CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
  2009. else
  2010. CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
  2011. }
  2012. // If the result is clearly ignored, return now.
  2013. if (Ignore)
  2014. return 0;
  2015. // The result of an assignment in C is the assigned r-value.
  2016. if (!CGF.getContext().getLangOptions().CPlusPlus)
  2017. return RHS;
  2018. // If the lvalue is non-volatile, return the computed value of the assignment.
  2019. if (!LHS.isVolatileQualified())
  2020. return RHS;
  2021. // Otherwise, reload the value.
  2022. return EmitLoadOfLValue(LHS);
  2023. }
  2024. Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
  2025. // Perform vector logical and on comparisons with zero vectors.
  2026. if (E->getType()->isVectorType()) {
  2027. Value *LHS = Visit(E->getLHS());
  2028. Value *RHS = Visit(E->getRHS());
  2029. Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
  2030. LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
  2031. RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
  2032. Value *And = Builder.CreateAnd(LHS, RHS);
  2033. return Builder.CreateSExt(And, Zero->getType(), "sext");
  2034. }
  2035. llvm::Type *ResTy = ConvertType(E->getType());
  2036. // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
  2037. // If we have 1 && X, just emit X without inserting the control flow.
  2038. bool LHSCondVal;
  2039. if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
  2040. if (LHSCondVal) { // If we have 1 && X, just emit X.
  2041. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  2042. // ZExt result to int or bool.
  2043. return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
  2044. }
  2045. // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
  2046. if (!CGF.ContainsLabel(E->getRHS()))
  2047. return llvm::Constant::getNullValue(ResTy);
  2048. }
  2049. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
  2050. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
  2051. CodeGenFunction::ConditionalEvaluation eval(CGF);
  2052. // Branch on the LHS first. If it is false, go to the failure (cont) block.
  2053. CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
  2054. // Any edges into the ContBlock are now from an (indeterminate number of)
  2055. // edges from this first condition. All of these values will be false. Start
  2056. // setting up the PHI node in the Cont Block for this.
  2057. llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
  2058. "", ContBlock);
  2059. for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
  2060. PI != PE; ++PI)
  2061. PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
  2062. eval.begin(CGF);
  2063. CGF.EmitBlock(RHSBlock);
  2064. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  2065. eval.end(CGF);
  2066. // Reaquire the RHS block, as there may be subblocks inserted.
  2067. RHSBlock = Builder.GetInsertBlock();
  2068. // Emit an unconditional branch from this block to ContBlock. Insert an entry
  2069. // into the phi node for the edge with the value of RHSCond.
  2070. if (CGF.getDebugInfo())
  2071. // There is no need to emit line number for unconditional branch.
  2072. Builder.SetCurrentDebugLocation(llvm::DebugLoc());
  2073. CGF.EmitBlock(ContBlock);
  2074. PN->addIncoming(RHSCond, RHSBlock);
  2075. // ZExt result to int.
  2076. return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
  2077. }
  2078. Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
  2079. // Perform vector logical or on comparisons with zero vectors.
  2080. if (E->getType()->isVectorType()) {
  2081. Value *LHS = Visit(E->getLHS());
  2082. Value *RHS = Visit(E->getRHS());
  2083. Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
  2084. LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
  2085. RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
  2086. Value *Or = Builder.CreateOr(LHS, RHS);
  2087. return Builder.CreateSExt(Or, Zero->getType(), "sext");
  2088. }
  2089. llvm::Type *ResTy = ConvertType(E->getType());
  2090. // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
  2091. // If we have 0 || X, just emit X without inserting the control flow.
  2092. bool LHSCondVal;
  2093. if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
  2094. if (!LHSCondVal) { // If we have 0 || X, just emit X.
  2095. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  2096. // ZExt result to int or bool.
  2097. return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
  2098. }
  2099. // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
  2100. if (!CGF.ContainsLabel(E->getRHS()))
  2101. return llvm::ConstantInt::get(ResTy, 1);
  2102. }
  2103. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
  2104. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
  2105. CodeGenFunction::ConditionalEvaluation eval(CGF);
  2106. // Branch on the LHS first. If it is true, go to the success (cont) block.
  2107. CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
  2108. // Any edges into the ContBlock are now from an (indeterminate number of)
  2109. // edges from this first condition. All of these values will be true. Start
  2110. // setting up the PHI node in the Cont Block for this.
  2111. llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
  2112. "", ContBlock);
  2113. for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
  2114. PI != PE; ++PI)
  2115. PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
  2116. eval.begin(CGF);
  2117. // Emit the RHS condition as a bool value.
  2118. CGF.EmitBlock(RHSBlock);
  2119. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  2120. eval.end(CGF);
  2121. // Reaquire the RHS block, as there may be subblocks inserted.
  2122. RHSBlock = Builder.GetInsertBlock();
  2123. // Emit an unconditional branch from this block to ContBlock. Insert an entry
  2124. // into the phi node for the edge with the value of RHSCond.
  2125. CGF.EmitBlock(ContBlock);
  2126. PN->addIncoming(RHSCond, RHSBlock);
  2127. // ZExt result to int.
  2128. return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
  2129. }
  2130. Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
  2131. CGF.EmitIgnoredExpr(E->getLHS());
  2132. CGF.EnsureInsertPoint();
  2133. return Visit(E->getRHS());
  2134. }
  2135. //===----------------------------------------------------------------------===//
  2136. // Other Operators
  2137. //===----------------------------------------------------------------------===//
  2138. /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
  2139. /// expression is cheap enough and side-effect-free enough to evaluate
  2140. /// unconditionally instead of conditionally. This is used to convert control
  2141. /// flow into selects in some cases.
  2142. static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
  2143. CodeGenFunction &CGF) {
  2144. E = E->IgnoreParens();
  2145. // Anything that is an integer or floating point constant is fine.
  2146. if (E->isConstantInitializer(CGF.getContext(), false))
  2147. return true;
  2148. // Non-volatile automatic variables too, to get "cond ? X : Y" where
  2149. // X and Y are local variables.
  2150. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  2151. if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  2152. if (VD->hasLocalStorage() && !(CGF.getContext()
  2153. .getCanonicalType(VD->getType())
  2154. .isVolatileQualified()))
  2155. return true;
  2156. return false;
  2157. }
  2158. Value *ScalarExprEmitter::
  2159. VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  2160. TestAndClearIgnoreResultAssign();
  2161. // Bind the common expression if necessary.
  2162. CodeGenFunction::OpaqueValueMapping binding(CGF, E);
  2163. Expr *condExpr = E->getCond();
  2164. Expr *lhsExpr = E->getTrueExpr();
  2165. Expr *rhsExpr = E->getFalseExpr();
  2166. // If the condition constant folds and can be elided, try to avoid emitting
  2167. // the condition and the dead arm.
  2168. bool CondExprBool;
  2169. if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
  2170. Expr *live = lhsExpr, *dead = rhsExpr;
  2171. if (!CondExprBool) std::swap(live, dead);
  2172. // If the dead side doesn't have labels we need, just emit the Live part.
  2173. if (!CGF.ContainsLabel(dead)) {
  2174. Value *Result = Visit(live);
  2175. // If the live part is a throw expression, it acts like it has a void
  2176. // type, so evaluating it returns a null Value*. However, a conditional
  2177. // with non-void type must return a non-null Value*.
  2178. if (!Result && !E->getType()->isVoidType())
  2179. Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
  2180. return Result;
  2181. }
  2182. }
  2183. // OpenCL: If the condition is a vector, we can treat this condition like
  2184. // the select function.
  2185. if (CGF.getContext().getLangOptions().OpenCL
  2186. && condExpr->getType()->isVectorType()) {
  2187. llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
  2188. llvm::Value *LHS = Visit(lhsExpr);
  2189. llvm::Value *RHS = Visit(rhsExpr);
  2190. llvm::Type *condType = ConvertType(condExpr->getType());
  2191. llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
  2192. unsigned numElem = vecTy->getNumElements();
  2193. llvm::Type *elemType = vecTy->getElementType();
  2194. llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
  2195. llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
  2196. llvm::Value *tmp = Builder.CreateSExt(TestMSB,
  2197. llvm::VectorType::get(elemType,
  2198. numElem),
  2199. "sext");
  2200. llvm::Value *tmp2 = Builder.CreateNot(tmp);
  2201. // Cast float to int to perform ANDs if necessary.
  2202. llvm::Value *RHSTmp = RHS;
  2203. llvm::Value *LHSTmp = LHS;
  2204. bool wasCast = false;
  2205. llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
  2206. if (rhsVTy->getElementType()->isFloatTy()) {
  2207. RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
  2208. LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
  2209. wasCast = true;
  2210. }
  2211. llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
  2212. llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
  2213. llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
  2214. if (wasCast)
  2215. tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
  2216. return tmp5;
  2217. }
  2218. // If this is a really simple expression (like x ? 4 : 5), emit this as a
  2219. // select instead of as control flow. We can only do this if it is cheap and
  2220. // safe to evaluate the LHS and RHS unconditionally.
  2221. if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
  2222. isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
  2223. llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
  2224. llvm::Value *LHS = Visit(lhsExpr);
  2225. llvm::Value *RHS = Visit(rhsExpr);
  2226. if (!LHS) {
  2227. // If the conditional has void type, make sure we return a null Value*.
  2228. assert(!RHS && "LHS and RHS types must match");
  2229. return 0;
  2230. }
  2231. return Builder.CreateSelect(CondV, LHS, RHS, "cond");
  2232. }
  2233. llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
  2234. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
  2235. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
  2236. CodeGenFunction::ConditionalEvaluation eval(CGF);
  2237. CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
  2238. CGF.EmitBlock(LHSBlock);
  2239. eval.begin(CGF);
  2240. Value *LHS = Visit(lhsExpr);
  2241. eval.end(CGF);
  2242. LHSBlock = Builder.GetInsertBlock();
  2243. Builder.CreateBr(ContBlock);
  2244. CGF.EmitBlock(RHSBlock);
  2245. eval.begin(CGF);
  2246. Value *RHS = Visit(rhsExpr);
  2247. eval.end(CGF);
  2248. RHSBlock = Builder.GetInsertBlock();
  2249. CGF.EmitBlock(ContBlock);
  2250. // If the LHS or RHS is a throw expression, it will be legitimately null.
  2251. if (!LHS)
  2252. return RHS;
  2253. if (!RHS)
  2254. return LHS;
  2255. // Create a PHI node for the real part.
  2256. llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
  2257. PN->addIncoming(LHS, LHSBlock);
  2258. PN->addIncoming(RHS, RHSBlock);
  2259. return PN;
  2260. }
  2261. Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
  2262. return Visit(E->getChosenSubExpr(CGF.getContext()));
  2263. }
  2264. Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
  2265. llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
  2266. llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
  2267. // If EmitVAArg fails, we fall back to the LLVM instruction.
  2268. if (!ArgPtr)
  2269. return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
  2270. // FIXME Volatility.
  2271. return Builder.CreateLoad(ArgPtr);
  2272. }
  2273. Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
  2274. return CGF.EmitBlockLiteral(block);
  2275. }
  2276. Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
  2277. Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
  2278. llvm::Type *DstTy = ConvertType(E->getType());
  2279. // Going from vec4->vec3 or vec3->vec4 is a special case and requires
  2280. // a shuffle vector instead of a bitcast.
  2281. llvm::Type *SrcTy = Src->getType();
  2282. if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
  2283. unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
  2284. unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
  2285. if ((numElementsDst == 3 && numElementsSrc == 4)
  2286. || (numElementsDst == 4 && numElementsSrc == 3)) {
  2287. // In the case of going from int4->float3, a bitcast is needed before
  2288. // doing a shuffle.
  2289. llvm::Type *srcElemTy =
  2290. cast<llvm::VectorType>(SrcTy)->getElementType();
  2291. llvm::Type *dstElemTy =
  2292. cast<llvm::VectorType>(DstTy)->getElementType();
  2293. if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
  2294. || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
  2295. // Create a float type of the same size as the source or destination.
  2296. llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
  2297. numElementsSrc);
  2298. Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
  2299. }
  2300. llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
  2301. SmallVector<llvm::Constant*, 3> Args;
  2302. Args.push_back(Builder.getInt32(0));
  2303. Args.push_back(Builder.getInt32(1));
  2304. Args.push_back(Builder.getInt32(2));
  2305. if (numElementsDst == 4)
  2306. Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
  2307. llvm::Constant *Mask = llvm::ConstantVector::get(Args);
  2308. return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
  2309. }
  2310. }
  2311. return Builder.CreateBitCast(Src, DstTy, "astype");
  2312. }
  2313. Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
  2314. return CGF.EmitAtomicExpr(E).getScalarVal();
  2315. }
  2316. //===----------------------------------------------------------------------===//
  2317. // Entry Point into this File
  2318. //===----------------------------------------------------------------------===//
  2319. /// EmitScalarExpr - Emit the computation of the specified expression of scalar
  2320. /// type, ignoring the result.
  2321. Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
  2322. assert(E && !hasAggregateLLVMType(E->getType()) &&
  2323. "Invalid scalar expression to emit");
  2324. if (isa<CXXDefaultArgExpr>(E))
  2325. disableDebugInfo();
  2326. Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
  2327. .Visit(const_cast<Expr*>(E));
  2328. if (isa<CXXDefaultArgExpr>(E))
  2329. enableDebugInfo();
  2330. return V;
  2331. }
  2332. /// EmitScalarConversion - Emit a conversion from the specified type to the
  2333. /// specified destination type, both of which are LLVM scalar types.
  2334. Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
  2335. QualType DstTy) {
  2336. assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
  2337. "Invalid scalar expression to emit");
  2338. return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
  2339. }
  2340. /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
  2341. /// type to the specified destination type, where the destination type is an
  2342. /// LLVM scalar type.
  2343. Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
  2344. QualType SrcTy,
  2345. QualType DstTy) {
  2346. assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
  2347. "Invalid complex -> scalar conversion");
  2348. return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
  2349. DstTy);
  2350. }
  2351. llvm::Value *CodeGenFunction::
  2352. EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  2353. bool isInc, bool isPre) {
  2354. return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
  2355. }
  2356. LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
  2357. llvm::Value *V;
  2358. // object->isa or (*object).isa
  2359. // Generate code as for: *(Class*)object
  2360. // build Class* type
  2361. llvm::Type *ClassPtrTy = ConvertType(E->getType());
  2362. Expr *BaseExpr = E->getBase();
  2363. if (BaseExpr->isRValue()) {
  2364. V = CreateMemTemp(E->getType(), "resval");
  2365. llvm::Value *Src = EmitScalarExpr(BaseExpr);
  2366. Builder.CreateStore(Src, V);
  2367. V = ScalarExprEmitter(*this).EmitLoadOfLValue(
  2368. MakeNaturalAlignAddrLValue(V, E->getType()));
  2369. } else {
  2370. if (E->isArrow())
  2371. V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
  2372. else
  2373. V = EmitLValue(BaseExpr).getAddress();
  2374. }
  2375. // build Class* type
  2376. ClassPtrTy = ClassPtrTy->getPointerTo();
  2377. V = Builder.CreateBitCast(V, ClassPtrTy);
  2378. return MakeNaturalAlignAddrLValue(V, E->getType());
  2379. }
  2380. LValue CodeGenFunction::EmitCompoundAssignmentLValue(
  2381. const CompoundAssignOperator *E) {
  2382. ScalarExprEmitter Scalar(*this);
  2383. Value *Result = 0;
  2384. switch (E->getOpcode()) {
  2385. #define COMPOUND_OP(Op) \
  2386. case BO_##Op##Assign: \
  2387. return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
  2388. Result)
  2389. COMPOUND_OP(Mul);
  2390. COMPOUND_OP(Div);
  2391. COMPOUND_OP(Rem);
  2392. COMPOUND_OP(Add);
  2393. COMPOUND_OP(Sub);
  2394. COMPOUND_OP(Shl);
  2395. COMPOUND_OP(Shr);
  2396. COMPOUND_OP(And);
  2397. COMPOUND_OP(Xor);
  2398. COMPOUND_OP(Or);
  2399. #undef COMPOUND_OP
  2400. case BO_PtrMemD:
  2401. case BO_PtrMemI:
  2402. case BO_Mul:
  2403. case BO_Div:
  2404. case BO_Rem:
  2405. case BO_Add:
  2406. case BO_Sub:
  2407. case BO_Shl:
  2408. case BO_Shr:
  2409. case BO_LT:
  2410. case BO_GT:
  2411. case BO_LE:
  2412. case BO_GE:
  2413. case BO_EQ:
  2414. case BO_NE:
  2415. case BO_And:
  2416. case BO_Xor:
  2417. case BO_Or:
  2418. case BO_LAnd:
  2419. case BO_LOr:
  2420. case BO_Assign:
  2421. case BO_Comma:
  2422. llvm_unreachable("Not valid compound assignment operators");
  2423. }
  2424. llvm_unreachable("Unhandled compound assignment operator");
  2425. }