blob: 91b10b29d12e274dbdc94f06fda42f6f91c04b3d [file] [log] [blame]
Chris Lattner7f02f722007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner7f02f722007-08-24 05:35:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patel78ba3d42010-10-04 21:46:04 +000014#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000015#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +000017#include "CGObjCRuntime.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000018#include "CodeGenModule.h"
Devang Patel78ba3d42010-10-04 21:46:04 +000019#include "CGDebugInfo.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000023#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000024#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000025#include "llvm/Constants.h"
26#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000027#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000028#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000029#include "llvm/Module.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000030#include "llvm/Support/CFG.h"
Micah Villmow25a6a842012-10-08 16:25:52 +000031#include "llvm/DataLayout.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000032#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000033
Chris Lattner7f02f722007-08-24 05:35:26 +000034using namespace clang;
35using namespace CodeGen;
36using llvm::Value;
37
38//===----------------------------------------------------------------------===//
39// Scalar Expression Emitter
40//===----------------------------------------------------------------------===//
41
Benjamin Kramer79ba2a62010-10-22 16:48:22 +000042namespace {
Chris Lattner7f02f722007-08-24 05:35:26 +000043struct BinOpInfo {
44 Value *LHS;
45 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000046 QualType Ty; // Computation Type.
Chris Lattner9a207232010-06-26 21:48:21 +000047 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
Lang Hamesbe9af122012-10-02 04:45:10 +000048 bool FPContractable;
Chris Lattner9a207232010-06-26 21:48:21 +000049 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner7f02f722007-08-24 05:35:26 +000050};
51
John McCall404cd162010-11-13 01:35:44 +000052static bool MustVisitNullValue(const Expr *E) {
53 // If a null pointer expression's type is the C++0x nullptr_t, then
54 // it's not necessarily a simple constant and it must be evaluated
55 // for its potential side effects.
56 return E->getType()->isNullPtrType();
57}
58
Benjamin Kramer85b45212009-11-28 19:45:26 +000059class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000060 : public StmtVisitor<ScalarExprEmitter, Value*> {
61 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000062 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000063 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000064 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000065public:
66
Mike Stump7f79f9b2009-05-29 15:46:01 +000067 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000068 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000069 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000070 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000071
Chris Lattner7f02f722007-08-24 05:35:26 +000072 //===--------------------------------------------------------------------===//
73 // Utilities
74 //===--------------------------------------------------------------------===//
75
Mike Stump7f79f9b2009-05-29 15:46:01 +000076 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000077 bool I = IgnoreResultAssign;
78 IgnoreResultAssign = false;
79 return I;
80 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000081
Chris Lattner2acc6e32011-07-18 04:24:23 +000082 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner7f02f722007-08-24 05:35:26 +000083 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Richard Smith7ac9ef12012-09-08 02:08:36 +000084 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
85 return CGF.EmitCheckedLValue(E, TCK);
Richard Smith2c9f87c2012-08-24 00:54:33 +000086 }
Chris Lattner7f02f722007-08-24 05:35:26 +000087
Richard Smith4def70d2012-10-09 19:52:38 +000088 void EmitBinOpCheck(Value *Check, const BinOpInfo &Info);
89
John McCall545d9962011-06-25 02:11:03 +000090 Value *EmitLoadOfLValue(LValue LV) {
91 return CGF.EmitLoadOfLValue(LV).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000092 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000093
Chris Lattner7f02f722007-08-24 05:35:26 +000094 /// EmitLoadOfLValue - Given an expression with complex type that represents a
95 /// value l-value, this method emits the address of the l-value, then loads
96 /// and returns the result.
97 Value *EmitLoadOfLValue(const Expr *E) {
Richard Smith7ac9ef12012-09-08 02:08:36 +000098 return EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load));
Chris Lattner7f02f722007-08-24 05:35:26 +000099 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000100
Chris Lattner9abc84e2007-08-26 16:42:57 +0000101 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000102 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000103 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000104
Richard Smithb2aa66c2012-10-12 22:57:06 +0000105 /// \brief Emit a check that a conversion to or from a floating-point type
106 /// does not overflow.
107 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
108 Value *Src, QualType SrcType,
109 QualType DstType, llvm::Type *DstTy);
110
Chris Lattner3707b252007-08-26 06:48:56 +0000111 /// EmitScalarConversion - Emit a conversion from the specified type to the
112 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000113 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
114
115 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000116 /// complex type to the specified destination type, where the destination type
117 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000118 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
119 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000120
Anders Carlssona40a9f32010-05-22 17:45:10 +0000121 /// EmitNullValue - Emit a value that corresponds to null for the given type.
122 Value *EmitNullValue(QualType Ty);
123
John McCalldaa8e4e2010-11-15 09:13:47 +0000124 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
125 Value *EmitFloatToBoolConversion(Value *V) {
126 // Compare against 0.0 for fp scalars.
127 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
128 return Builder.CreateFCmpUNE(V, Zero, "tobool");
129 }
130
131 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
132 Value *EmitPointerToBoolConversion(Value *V) {
133 Value *Zero = llvm::ConstantPointerNull::get(
134 cast<llvm::PointerType>(V->getType()));
135 return Builder.CreateICmpNE(V, Zero, "tobool");
136 }
137
138 Value *EmitIntToBoolConversion(Value *V) {
139 // Because of the type rules of C, we often end up computing a
140 // logical value, then zero extending it to int, then wanting it
141 // as a logical value again. Optimize this common case.
142 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
143 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
144 Value *Result = ZI->getOperand(0);
145 // If there aren't any more uses, zap the instruction to save space.
146 // Note that there can be more uses, for example if this
147 // is the result of an assignment.
148 if (ZI->use_empty())
149 ZI->eraseFromParent();
150 return Result;
151 }
152 }
153
Chris Lattner48431f92011-04-19 22:55:03 +0000154 return Builder.CreateIsNotNull(V, "tobool");
John McCalldaa8e4e2010-11-15 09:13:47 +0000155 }
156
Chris Lattner7f02f722007-08-24 05:35:26 +0000157 //===--------------------------------------------------------------------===//
158 // Visitor Methods
159 //===--------------------------------------------------------------------===//
160
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000161 Value *Visit(Expr *E) {
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000162 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
163 }
164
Chris Lattner7f02f722007-08-24 05:35:26 +0000165 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000166 S->dump(CGF.getContext().getSourceManager());
David Blaikieb219cfc2011-09-23 05:06:16 +0000167 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner7f02f722007-08-24 05:35:26 +0000168 }
169 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000170
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000171 Value *VisitParenExpr(ParenExpr *PE) {
172 return Visit(PE->getSubExpr());
173 }
John McCall91a57552011-07-15 05:09:51 +0000174 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
175 return Visit(E->getReplacement());
176 }
Peter Collingbournef111d932011-04-15 00:35:48 +0000177 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
178 return Visit(GE->getResultExpr());
179 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000180
181 // Leaves.
182 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000183 return Builder.getInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000184 }
185 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000186 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000187 }
188 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000189 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000190 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000191 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
192 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
193 }
Nate Begemane7579b52007-11-15 05:40:03 +0000194 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000195 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000196 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000197 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000198 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000199 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000200 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000201 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000202 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000203 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000204 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000205 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000206 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
207 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000208 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000209
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000210 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000211 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000212 }
John McCalle996ffd2011-02-16 08:02:54 +0000213
John McCall4b9c2d22011-11-06 09:01:30 +0000214 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
215 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
216 }
217
John McCalle996ffd2011-02-16 08:02:54 +0000218 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000219 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +0000220 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
John McCalle996ffd2011-02-16 08:02:54 +0000221
222 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000223 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000224 }
John McCalldd2ecee2012-03-10 03:05:10 +0000225
Chris Lattner7f02f722007-08-24 05:35:26 +0000226 // l-values.
John McCallf4b88a42012-03-10 09:33:50 +0000227 Value *VisitDeclRefExpr(DeclRefExpr *E) {
228 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
John McCalldd2ecee2012-03-10 03:05:10 +0000229 if (result.isReference())
John McCallf4b88a42012-03-10 09:33:50 +0000230 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
John McCalldd2ecee2012-03-10 03:05:10 +0000231 return result.getValue();
Richard Smitha3ca41f2012-03-02 23:27:11 +0000232 }
John McCallf4b88a42012-03-10 09:33:50 +0000233 return EmitLoadOfLValue(E);
John McCalldd2ecee2012-03-10 03:05:10 +0000234 }
235
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000236 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
237 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000238 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000239 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
240 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000241 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000242 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000243 return EmitLoadOfLValue(E);
244 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000245 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000246 if (E->getMethodDecl() &&
247 E->getMethodDecl()->getResultType()->isReferenceType())
248 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000249 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000250 }
251
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000252 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000253 LValue LV = CGF.EmitObjCIsaExpr(E);
John McCall545d9962011-06-25 02:11:03 +0000254 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000255 return V;
256 }
257
Chris Lattner7f02f722007-08-24 05:35:26 +0000258 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000259 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000260 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000261 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000262 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
263 return EmitLoadOfLValue(E);
264 }
Devang Patel35634f52007-10-24 17:18:43 +0000265
Nate Begeman0533b302009-10-18 20:10:40 +0000266 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000267
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000268 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000269 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000270 }
John McCallbc8d40d2011-06-24 21:55:10 +0000271 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000272 if (E->getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000273 CGF.EmitVariablyModifiedType(E->getType());
274 return VisitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000275 }
John McCallbc8d40d2011-06-24 21:55:10 +0000276 Value *VisitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000277
278 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000279 if (E->getCallReturnType()->isReferenceType())
280 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000281
Chris Lattner9b655512007-08-31 22:49:20 +0000282 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000283 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000284
Chris Lattner33793202007-08-31 22:09:40 +0000285 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000286
Chris Lattner7f02f722007-08-24 05:35:26 +0000287 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000288 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000289 LValue LV = EmitLValue(E->getSubExpr());
290 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000291 }
292 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000293 LValue LV = EmitLValue(E->getSubExpr());
294 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000295 }
296 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000297 LValue LV = EmitLValue(E->getSubExpr());
298 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000299 }
300 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000301 LValue LV = EmitLValue(E->getSubExpr());
302 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000303 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000304
Anton Yartsev683564a2011-02-07 02:17:30 +0000305 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
306 llvm::Value *InVal,
307 llvm::Value *NextVal,
308 bool IsInc);
309
Chris Lattner8c11a652010-06-26 22:09:34 +0000310 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
311 bool isInc, bool isPre);
312
313
Chris Lattner7f02f722007-08-24 05:35:26 +0000314 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000315 if (isa<MemberPointerType>(E->getType())) // never sugared
316 return CGF.CGM.getMemberPointerConstant(E);
317
Chris Lattner7f02f722007-08-24 05:35:26 +0000318 return EmitLValue(E->getSubExpr()).getAddress();
319 }
John McCallfd569002010-12-04 12:43:24 +0000320 Value *VisitUnaryDeref(const UnaryOperator *E) {
321 if (E->getType()->isVoidType())
322 return Visit(E->getSubExpr()); // the actual value should be unused
323 return EmitLoadOfLValue(E);
324 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000325 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000326 // This differs from gcc, though, most likely due to a bug in gcc.
327 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000328 return Visit(E->getSubExpr());
329 }
330 Value *VisitUnaryMinus (const UnaryOperator *E);
331 Value *VisitUnaryNot (const UnaryOperator *E);
332 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000333 Value *VisitUnaryReal (const UnaryOperator *E);
334 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000335 Value *VisitUnaryExtension(const UnaryOperator *E) {
336 return Visit(E->getSubExpr());
337 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000338
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000339 // C++
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000340 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedmanec24b0e2011-08-14 04:50:34 +0000341 return EmitLoadOfLValue(E);
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000342 }
343
Chris Lattner04421082008-04-08 04:40:51 +0000344 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
345 return Visit(DAE->getExpr());
346 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000347 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
348 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000349 }
350
John McCall4765fa02010-12-06 08:20:24 +0000351 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +0000352 CGF.enterFullExpression(E);
353 CodeGenFunction::RunCleanupsScope Scope(CGF);
354 return Visit(E->getSubExpr());
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000355 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000356 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
357 return CGF.EmitCXXNewExpr(E);
358 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000359 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
360 CGF.EmitCXXDeleteExpr(E);
361 return 0;
362 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000363 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000364 return Builder.getInt1(E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000365 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000366
Francois Pichet6ad6f282010-12-07 00:08:36 +0000367 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000368 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000369 }
370
John Wiegley21ff2e52011-04-28 00:16:57 +0000371 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
372 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
373 }
374
John Wiegley55262202011-04-25 06:54:41 +0000375 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
376 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
377 }
378
Douglas Gregora71d8192009-09-04 17:36:40 +0000379 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
380 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000381 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000382 // operator (), and the result of such a call has type void. The only
383 // effect is the evaluation of the postfix-expression before the dot or
384 // arrow.
385 CGF.EmitScalarExpr(E->getBase());
386 return 0;
387 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000388
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000389 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000390 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000391 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000392
393 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
394 CGF.EmitCXXThrowExpr(E);
395 return 0;
396 }
397
Sebastian Redl98294de2010-09-10 21:04:00 +0000398 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000399 return Builder.getInt1(E->getValue());
Sebastian Redl98294de2010-09-10 21:04:00 +0000400 }
401
Chris Lattner7f02f722007-08-24 05:35:26 +0000402 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000403 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000404 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000405 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000406 case LangOptions::SOB_Defined:
407 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith9d3e2262012-08-25 00:32:28 +0000408 case LangOptions::SOB_Undefined:
409 if (!CGF.CatchUndefined)
410 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
411 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +0000412 case LangOptions::SOB_Trapping:
413 return EmitOverflowCheckedBinOp(Ops);
414 }
415 }
416
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000417 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000418 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000419 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
420 }
Chris Lattner80230302010-09-11 21:47:09 +0000421 bool isTrapvOverflowBehavior() {
Richard Smith9d3e2262012-08-25 00:32:28 +0000422 return CGF.getContext().getLangOpts().getSignedOverflowBehavior()
423 == LangOptions::SOB_Trapping || CGF.CatchUndefined;
Chris Lattner80230302010-09-11 21:47:09 +0000424 }
Mike Stump2add4732009-04-01 20:28:16 +0000425 /// Create a binary op that checks for overflow.
426 /// Currently only supports +, - and *.
427 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith7ac9ef12012-09-08 02:08:36 +0000428
Chris Lattner80230302010-09-11 21:47:09 +0000429 // Check for undefined division and modulus behaviors.
430 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
431 llvm::Value *Zero,bool isDiv);
Chris Lattner7f02f722007-08-24 05:35:26 +0000432 Value *EmitDiv(const BinOpInfo &Ops);
433 Value *EmitRem(const BinOpInfo &Ops);
434 Value *EmitAdd(const BinOpInfo &Ops);
435 Value *EmitSub(const BinOpInfo &Ops);
436 Value *EmitShl(const BinOpInfo &Ops);
437 Value *EmitShr(const BinOpInfo &Ops);
438 Value *EmitAnd(const BinOpInfo &Ops) {
439 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
440 }
441 Value *EmitXor(const BinOpInfo &Ops) {
442 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
443 }
444 Value *EmitOr (const BinOpInfo &Ops) {
445 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
446 }
447
Chris Lattner1f1ded92007-08-24 21:00:35 +0000448 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000449 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
450 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000451 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000452
Chris Lattner3ccf7742007-08-26 21:41:21 +0000453 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000454 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
455
456 // Binary operators and binary compound assignment operators.
457#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000458 Value *VisitBin ## OP(const BinaryOperator *E) { \
459 return Emit ## OP(EmitBinOps(E)); \
460 } \
461 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
462 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000463 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000464 HANDLEBINOP(Mul)
465 HANDLEBINOP(Div)
466 HANDLEBINOP(Rem)
467 HANDLEBINOP(Add)
468 HANDLEBINOP(Sub)
469 HANDLEBINOP(Shl)
470 HANDLEBINOP(Shr)
471 HANDLEBINOP(And)
472 HANDLEBINOP(Xor)
473 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000474#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000475
Chris Lattner7f02f722007-08-24 05:35:26 +0000476 // Comparisons.
477 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
478 unsigned SICmpOpc, unsigned FCmpOpc);
479#define VISITCOMP(CODE, UI, SI, FP) \
480 Value *VisitBin##CODE(const BinaryOperator *E) { \
481 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
482 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000483 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
484 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
485 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
486 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
487 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
488 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000489#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000490
Chris Lattner7f02f722007-08-24 05:35:26 +0000491 Value *VisitBinAssign (const BinaryOperator *E);
492
493 Value *VisitBinLAnd (const BinaryOperator *E);
494 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000495 Value *VisitBinComma (const BinaryOperator *E);
496
Eli Friedman25b825d2009-11-18 09:41:26 +0000497 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
498 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
499
Chris Lattner7f02f722007-08-24 05:35:26 +0000500 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000501 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000502 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000503 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000504 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000505 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
506 return CGF.EmitObjCStringLiteral(E);
507 }
Patrick Beardeb382ec2012-04-19 00:25:12 +0000508 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
509 return CGF.EmitObjCBoxedExpr(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000510 }
511 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
512 return CGF.EmitObjCArrayLiteral(E);
513 }
514 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
515 return CGF.EmitObjCDictionaryLiteral(E);
516 }
Tanya Lattner61eee0c2011-06-04 00:47:47 +0000517 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedman276b0612011-10-11 02:20:01 +0000518 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000519};
520} // end anonymous namespace.
521
522//===----------------------------------------------------------------------===//
523// Utilities
524//===----------------------------------------------------------------------===//
525
Chris Lattner9abc84e2007-08-26 16:42:57 +0000526/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000527/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000528Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000529 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000530
John McCalldaa8e4e2010-11-15 09:13:47 +0000531 if (SrcType->isRealFloatingType())
532 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000533
John McCall0bab0cd2010-08-23 01:21:21 +0000534 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
535 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000536
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000537 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000538 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000539
John McCalldaa8e4e2010-11-15 09:13:47 +0000540 if (isa<llvm::IntegerType>(Src->getType()))
541 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000542
John McCalldaa8e4e2010-11-15 09:13:47 +0000543 assert(isa<llvm::PointerType>(Src->getType()));
544 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000545}
546
Richard Smithb2aa66c2012-10-12 22:57:06 +0000547void ScalarExprEmitter::EmitFloatConversionCheck(Value *OrigSrc,
548 QualType OrigSrcType,
549 Value *Src, QualType SrcType,
550 QualType DstType,
551 llvm::Type *DstTy) {
552 using llvm::APFloat;
553 using llvm::APSInt;
554
555 llvm::Type *SrcTy = Src->getType();
556
557 llvm::Value *Check = 0;
558 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
559 // Integer to floating-point. This can fail for unsigned short -> __half
560 // or unsigned __int128 -> float.
561 assert(DstType->isFloatingType());
562 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
563
564 APFloat LargestFloat =
565 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
566 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
567
568 bool IsExact;
569 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
570 &IsExact) != APFloat::opOK)
571 // The range of representable values of this floating point type includes
572 // all values of this integer type. Don't need an overflow check.
573 return;
574
575 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
576 if (SrcIsUnsigned)
577 Check = Builder.CreateICmpULE(Src, Max);
578 else {
579 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
580 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
581 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
582 Check = Builder.CreateAnd(GE, LE);
583 }
584 } else {
585 // Floating-point to integer or floating-point to floating-point. This has
586 // undefined behavior if the source is +-Inf, NaN, or doesn't fit into the
587 // destination type.
588 const llvm::fltSemantics &SrcSema =
589 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
590 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
591 APFloat MinSrc(SrcSema, APFloat::uninitialized);
592
593 if (isa<llvm::IntegerType>(DstTy)) {
594 unsigned Width = CGF.getContext().getIntWidth(DstType);
595 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
596
597 APSInt Min = APSInt::getMinValue(Width, Unsigned);
598 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
599 APFloat::opOverflow)
600 // Don't need an overflow check for lower bound. Just check for
601 // -Inf/NaN.
602 MinSrc = APFloat::getLargest(SrcSema, true);
603
604 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
605 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
606 APFloat::opOverflow)
607 // Don't need an overflow check for upper bound. Just check for
608 // +Inf/NaN.
609 MaxSrc = APFloat::getLargest(SrcSema, false);
610 } else {
611 const llvm::fltSemantics &DstSema =
612 CGF.getContext().getFloatTypeSemantics(DstType);
613 bool IsInexact;
614
615 MinSrc = APFloat::getLargest(DstSema, true);
616 if (MinSrc.convert(SrcSema, APFloat::rmTowardZero, &IsInexact) &
617 APFloat::opOverflow)
618 MinSrc = APFloat::getLargest(SrcSema, true);
619
620 MaxSrc = APFloat::getLargest(DstSema, false);
621 if (MaxSrc.convert(SrcSema, APFloat::rmTowardZero, &IsInexact) &
622 APFloat::opOverflow)
623 MaxSrc = APFloat::getLargest(SrcSema, false);
624 }
625
626 // If we're converting from __half, convert the range to float to match
627 // the type of src.
628 if (OrigSrcType->isHalfType()) {
629 const llvm::fltSemantics &Sema =
630 CGF.getContext().getFloatTypeSemantics(SrcType);
631 bool IsInexact;
632 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
633 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
634 }
635
636 llvm::Value *GE =
637 Builder.CreateFCmpOGE(Src, llvm::ConstantFP::get(VMContext, MinSrc));
638 llvm::Value *LE =
639 Builder.CreateFCmpOLE(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
640 Check = Builder.CreateAnd(GE, LE);
641 }
642
643 // FIXME: Provide a SourceLocation.
644 llvm::Constant *StaticArgs[] = {
645 CGF.EmitCheckTypeDescriptor(OrigSrcType),
646 CGF.EmitCheckTypeDescriptor(DstType)
647 };
648 CGF.EmitCheck(Check, "float_cast_overflow", StaticArgs, OrigSrc);
649}
650
Chris Lattner3707b252007-08-26 06:48:56 +0000651/// EmitScalarConversion - Emit a conversion from the specified type to the
652/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000653Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
654 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000655 SrcType = CGF.getContext().getCanonicalType(SrcType);
656 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000657 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000658
Chris Lattnercf289082007-08-26 07:21:11 +0000659 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000660
Richard Smithb2aa66c2012-10-12 22:57:06 +0000661 llvm::Value *OrigSrc = Src;
662 QualType OrigSrcType = SrcType;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000663 llvm::Type *SrcTy = Src->getType();
664
665 // Floating casts might be a bit special: if we're doing casts to / from half
666 // FP, we should go via special intrinsics.
667 if (SrcType->isHalfType()) {
668 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
669 SrcType = CGF.getContext().FloatTy;
Chris Lattner8b418682012-02-07 00:39:47 +0000670 SrcTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000671 }
672
Chris Lattner3707b252007-08-26 06:48:56 +0000673 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000674 if (DstType->isBooleanType())
675 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000676
Chris Lattner2acc6e32011-07-18 04:24:23 +0000677 llvm::Type *DstTy = ConvertType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000678
679 // Ignore conversions like int -> uint.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000680 if (SrcTy == DstTy)
Chris Lattner3707b252007-08-26 06:48:56 +0000681 return Src;
682
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000683 // Handle pointer conversions next: pointers can only be converted to/from
684 // other pointers and integers. Check for pointer types in terms of LLVM, as
685 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000686 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000687 // The source value may be an integer, or a pointer.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000688 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3707b252007-08-26 06:48:56 +0000689 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000690
Chris Lattner3707b252007-08-26 06:48:56 +0000691 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000692 // First, convert to the correct width so that we control the kind of
693 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000694 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000695 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman25615422009-03-04 04:02:35 +0000696 llvm::Value* IntResult =
697 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
698 // Then, cast to pointer.
699 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000700 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000701
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000702 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000703 // Must be an ptr to int cast.
704 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000705 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000706 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000707
Nate Begeman213541a2008-04-18 23:10:10 +0000708 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000709 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000710 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000711 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000712 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
713
714 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000715 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +0000716 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +0000717 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000718
719 // Splat the element across to all elements
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000720 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner2ce88422012-01-25 05:34:41 +0000721 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements,
722 Builder.getInt32(0));
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000723 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
724 return Yay;
725 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000726
Chris Lattner3b1ae002008-02-02 04:51:41 +0000727 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000728 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000729 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000730 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000731
Chris Lattner3707b252007-08-26 06:48:56 +0000732 // Finally, we have the arithmetic types: real int/float.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000733 Value *Res = NULL;
734 llvm::Type *ResTy = DstTy;
735
Richard Smithb2aa66c2012-10-12 22:57:06 +0000736 // An overflowing conversion has undefined behavior if either the source type
737 // or the destination type is a floating-point type.
738 if (CGF.CatchUndefined &&
739 (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
740 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy);
741
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000742 // Cast to half via float
743 if (DstType->isHalfType())
Chris Lattner8b418682012-02-07 00:39:47 +0000744 DstTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000745
746 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000747 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000748 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000749 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000750 else if (InputSigned)
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000751 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000752 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000753 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
754 } else if (isa<llvm::IntegerType>(DstTy)) {
755 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor575a1c92011-05-20 16:38:50 +0000756 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000757 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000758 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000759 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
760 } else {
761 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
762 "Unknown real conversion");
763 if (DstTy->getTypeID() < SrcTy->getTypeID())
764 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
765 else
766 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000767 }
768
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000769 if (DstTy != ResTy) {
770 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
771 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
772 }
773
774 return Res;
Chris Lattner3707b252007-08-26 06:48:56 +0000775}
776
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000777/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
778/// type to the specified destination type, where the destination type is an
779/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000780Value *ScalarExprEmitter::
781EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
782 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000783 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000784 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000785
Chris Lattnered70f0a2007-08-26 16:52:28 +0000786 // Handle conversions to bool first, they are special: comparisons against 0.
787 if (DstTy->isBooleanType()) {
788 // Complex != 0 -> (Real != 0) | (Imag != 0)
789 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
790 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
791 return Builder.CreateOr(Src.first, Src.second, "tobool");
792 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000793
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000794 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
795 // the imaginary part of the complex value is discarded and the value of the
796 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000797 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000798 return EmitScalarConversion(Src.first, SrcTy, DstTy);
799}
800
Anders Carlssona40a9f32010-05-22 17:45:10 +0000801Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000802 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
803 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
804
805 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000806}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000807
Richard Smith4def70d2012-10-09 19:52:38 +0000808/// \brief Emit a sanitization check for the given "binary" operation (which
809/// might actually be a unary increment which has been lowered to a binary
810/// operation). The check passes if \p Check, which is an \c i1, is \c true.
811void ScalarExprEmitter::EmitBinOpCheck(Value *Check, const BinOpInfo &Info) {
812 StringRef CheckName;
813 llvm::SmallVector<llvm::Constant *, 4> StaticData;
814 llvm::SmallVector<llvm::Value *, 2> DynamicData;
815
816 BinaryOperatorKind Opcode = Info.Opcode;
817 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
818 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
819
820 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
821 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
822 if (UO && UO->getOpcode() == UO_Minus) {
823 CheckName = "negate_overflow";
824 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
825 DynamicData.push_back(Info.RHS);
826 } else {
827 if (BinaryOperator::isShiftOp(Opcode)) {
828 // Shift LHS negative or too large, or RHS out of bounds.
829 CheckName = "shift_out_of_bounds";
830 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
831 StaticData.push_back(
832 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
833 StaticData.push_back(
834 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
835 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
836 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
837 CheckName = "divrem_overflow";
838 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.E->getType()));
839 } else {
840 // Signed arithmetic overflow (+, -, *).
841 switch (Opcode) {
842 case BO_Add: CheckName = "add_overflow"; break;
843 case BO_Sub: CheckName = "sub_overflow"; break;
844 case BO_Mul: CheckName = "mul_overflow"; break;
845 default: llvm_unreachable("unexpected opcode for bin op check");
846 }
847 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.E->getType()));
848 }
849 DynamicData.push_back(Info.LHS);
850 DynamicData.push_back(Info.RHS);
851 }
852
853 CGF.EmitCheck(Check, CheckName, StaticData, DynamicData);
854}
855
Chris Lattner7f02f722007-08-24 05:35:26 +0000856//===----------------------------------------------------------------------===//
857// Visitor Methods
858//===----------------------------------------------------------------------===//
859
860Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000861 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000862 if (E->getType()->isVoidType())
863 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000864 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000865}
866
Eli Friedmand38617c2008-05-14 19:38:39 +0000867Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000868 // Vector Mask Case
869 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000870 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000871 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
872 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
873 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000874
Chris Lattner2acc6e32011-07-18 04:24:23 +0000875 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000876 unsigned LHSElts = LTy->getNumElements();
877
878 if (E->getNumSubExprs() == 3) {
879 Mask = CGF.EmitScalarExpr(E->getExpr(2));
880
881 // Shuffle LHS & RHS into one input vector.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000882 SmallVector<llvm::Constant*, 32> concat;
Nate Begeman37b6a572010-06-08 00:16:34 +0000883 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000884 concat.push_back(Builder.getInt32(2*i));
885 concat.push_back(Builder.getInt32(2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000886 }
887
Chris Lattnerfb018d12011-02-15 00:14:06 +0000888 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000889 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
890 LHSElts *= 2;
891 } else {
892 Mask = RHS;
893 }
894
Chris Lattner2acc6e32011-07-18 04:24:23 +0000895 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000896 llvm::Constant* EltMask;
897
898 // Treat vec3 like vec4.
899 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
900 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
901 (1 << llvm::Log2_32(LHSElts+2))-1);
902 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
903 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
904 (1 << llvm::Log2_32(LHSElts+1))-1);
905 else
906 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
907 (1 << llvm::Log2_32(LHSElts))-1);
908
909 // Mask off the high bits of each shuffle index.
Chris Lattner2ce88422012-01-25 05:34:41 +0000910 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
911 EltMask);
Nate Begeman37b6a572010-06-08 00:16:34 +0000912 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
913
914 // newv = undef
915 // mask = mask & maskbits
916 // for each elt
917 // n = extract mask i
918 // x = extract val n
919 // newv = insert newv, x, i
Chris Lattner2acc6e32011-07-18 04:24:23 +0000920 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000921 MTy->getNumElements());
922 Value* NewV = llvm::UndefValue::get(RTy);
923 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Eli Friedman87b9c032012-04-05 21:48:40 +0000924 Value *IIndx = Builder.getInt32(i);
925 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000926 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000927
928 // Handle vec3 special since the index will be off by one for the RHS.
929 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
930 Value *cmpIndx, *newIndx;
Chris Lattner48431f92011-04-19 22:55:03 +0000931 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000932 "cmp_shuf_idx");
Chris Lattner48431f92011-04-19 22:55:03 +0000933 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
Nate Begeman37b6a572010-06-08 00:16:34 +0000934 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
935 }
936 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman87b9c032012-04-05 21:48:40 +0000937 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begeman37b6a572010-06-08 00:16:34 +0000938 }
939 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000940 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000941
Eli Friedmand38617c2008-05-14 19:38:39 +0000942 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
943 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000944
945 // Handle vec3 special since the index will be off by one for the RHS.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000946 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000947 SmallVector<llvm::Constant*, 32> indices;
Nate Begeman37b6a572010-06-08 00:16:34 +0000948 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
Eli Friedman0eb47fc2011-05-19 00:37:32 +0000949 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
950 if (VTy->getNumElements() == 3 && Idx > 3)
951 Idx -= 1;
952 indices.push_back(Builder.getInt32(Idx));
Nate Begeman37b6a572010-06-08 00:16:34 +0000953 }
954
Chris Lattnerfb018d12011-02-15 00:14:06 +0000955 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000956 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
957}
Eli Friedman28665272009-11-26 03:22:21 +0000958Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Richard Smith80d4b552011-12-28 19:48:30 +0000959 llvm::APSInt Value;
960 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
Eli Friedman28665272009-11-26 03:22:21 +0000961 if (E->isArrow())
962 CGF.EmitScalarExpr(E->getBase());
963 else
964 EmitLValue(E->getBase());
Richard Smith80d4b552011-12-28 19:48:30 +0000965 return Builder.getInt(Value);
Eli Friedman28665272009-11-26 03:22:21 +0000966 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000967
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000968 // Emit debug info for aggregate now, if it was delayed to reduce
Devang Patel78ba3d42010-10-04 21:46:04 +0000969 // debug info size.
970 CGDebugInfo *DI = CGF.getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000971 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +0000972 CGF.CGM.getCodeGenOpts().getDebugInfo()
973 == CodeGenOptions::LimitedDebugInfo) {
Devang Patel78ba3d42010-10-04 21:46:04 +0000974 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
975 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000976 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000977 DI->getOrCreateRecordType(PTy->getPointeeType(),
Devang Patel78ba3d42010-10-04 21:46:04 +0000978 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000979 }
Eli Friedman28665272009-11-26 03:22:21 +0000980 return EmitLoadOfLValue(E);
981}
Eli Friedmand38617c2008-05-14 19:38:39 +0000982
Chris Lattner7f02f722007-08-24 05:35:26 +0000983Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000984 TestAndClearIgnoreResultAssign();
985
Chris Lattner7f02f722007-08-24 05:35:26 +0000986 // Emit subscript expressions in rvalue context's. For most cases, this just
987 // loads the lvalue formed by the subscript expr. However, we have to be
988 // careful, because the base of a vector subscript is occasionally an rvalue,
989 // so we can't get it as an lvalue.
990 if (!E->getBase()->getType()->isVectorType())
991 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000992
Chris Lattner7f02f722007-08-24 05:35:26 +0000993 // Handle the vector case. The base must be a vector, the index must be an
994 // integer value.
995 Value *Base = Visit(E->getBase());
996 Value *Idx = Visit(E->getIdx());
Douglas Gregor575a1c92011-05-20 16:38:50 +0000997 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000998 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000999 return Builder.CreateExtractElement(Base, Idx, "vecext");
1000}
1001
Nate Begeman0533b302009-10-18 20:10:40 +00001002static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001003 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman0533b302009-10-18 20:10:40 +00001004 int MV = SVI->getMaskValue(Idx);
1005 if (MV == -1)
1006 return llvm::UndefValue::get(I32Ty);
1007 return llvm::ConstantInt::get(I32Ty, Off+MV);
1008}
1009
1010Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1011 bool Ignore = TestAndClearIgnoreResultAssign();
1012 (void)Ignore;
1013 assert (Ignore == false && "init list ignored");
1014 unsigned NumInitElements = E->getNumInits();
1015
1016 if (E->hadArrayRangeDesignator())
1017 CGF.ErrorUnsupported(E, "GNU array range designator extension");
1018
Chris Lattner2acc6e32011-07-18 04:24:23 +00001019 llvm::VectorType *VType =
Nate Begeman0533b302009-10-18 20:10:40 +00001020 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
1021
Sebastian Redlcea8d962011-09-24 17:48:14 +00001022 if (!VType) {
1023 if (NumInitElements == 0) {
1024 // C++11 value-initialization for the scalar.
1025 return EmitNullValue(E->getType());
1026 }
1027 // We have a scalar in braces. Just use the first element.
Nate Begeman0533b302009-10-18 20:10:40 +00001028 return Visit(E->getInit(0));
Sebastian Redlcea8d962011-09-24 17:48:14 +00001029 }
Nate Begeman0533b302009-10-18 20:10:40 +00001030
1031 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +00001032
1033 // Loop over initializers collecting the Value for each, and remembering
1034 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1035 // us to fold the shuffle for the swizzle into the shuffle for the vector
1036 // initializer, since LLVM optimizers generally do not want to touch
1037 // shuffles.
1038 unsigned CurIdx = 0;
1039 bool VIsUndefShuffle = false;
1040 llvm::Value *V = llvm::UndefValue::get(VType);
1041 for (unsigned i = 0; i != NumInitElements; ++i) {
1042 Expr *IE = E->getInit(i);
1043 Value *Init = Visit(IE);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001044 SmallVector<llvm::Constant*, 16> Args;
Nate Begeman0533b302009-10-18 20:10:40 +00001045
Chris Lattner2acc6e32011-07-18 04:24:23 +00001046 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Nate Begeman0533b302009-10-18 20:10:40 +00001047
1048 // Handle scalar elements. If the scalar initializer is actually one
1049 // element of a different vector of the same width, use shuffle instead of
1050 // extract+insert.
1051 if (!VVT) {
1052 if (isa<ExtVectorElementExpr>(IE)) {
1053 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1054
1055 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1056 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1057 Value *LHS = 0, *RHS = 0;
1058 if (CurIdx == 0) {
1059 // insert into undef -> shuffle (src, undef)
1060 Args.push_back(C);
Benjamin Kramer14c59822012-02-14 12:06:21 +00001061 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001062
1063 LHS = EI->getVectorOperand();
1064 RHS = V;
1065 VIsUndefShuffle = true;
1066 } else if (VIsUndefShuffle) {
1067 // insert into undefshuffle && size match -> shuffle (v, src)
1068 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1069 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +00001070 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner48431f92011-04-19 22:55:03 +00001071 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001072 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1073
Nate Begeman0533b302009-10-18 20:10:40 +00001074 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1075 RHS = EI->getVectorOperand();
1076 VIsUndefShuffle = false;
1077 }
1078 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +00001079 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001080 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1081 ++CurIdx;
1082 continue;
1083 }
1084 }
1085 }
Chris Lattner48431f92011-04-19 22:55:03 +00001086 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1087 "vecinit");
Nate Begeman0533b302009-10-18 20:10:40 +00001088 VIsUndefShuffle = false;
1089 ++CurIdx;
1090 continue;
1091 }
1092
1093 unsigned InitElts = VVT->getNumElements();
1094
1095 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
1096 // input is the same width as the vector being constructed, generate an
1097 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +00001098 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +00001099 if (isa<ExtVectorElementExpr>(IE)) {
1100 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1101 Value *SVOp = SVI->getOperand(0);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001102 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Nate Begeman0533b302009-10-18 20:10:40 +00001103
1104 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +00001105 for (unsigned j = 0; j != CurIdx; ++j) {
1106 // If the current vector initializer is a shuffle with undef, merge
1107 // this shuffle directly into it.
1108 if (VIsUndefShuffle) {
1109 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +00001110 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001111 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001112 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +00001113 }
1114 }
1115 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +00001116 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001117 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001118
1119 if (VIsUndefShuffle)
1120 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1121
1122 Init = SVOp;
1123 }
1124 }
1125
1126 // Extend init to result vector length, and then shuffle its contribution
1127 // to the vector initializer into V.
1128 if (Args.empty()) {
1129 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001130 Args.push_back(Builder.getInt32(j));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001131 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +00001132 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001133 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +00001134 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +00001135
1136 Args.clear();
1137 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001138 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +00001139 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001140 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001141 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001142 }
1143
1144 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1145 // merging subsequent shuffles into this one.
1146 if (CurIdx == 0)
1147 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +00001148 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001149 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1150 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1151 CurIdx += InitElts;
1152 }
1153
1154 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1155 // Emit remaining default initializers.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001156 llvm::Type *EltTy = VType->getElementType();
Nate Begeman0533b302009-10-18 20:10:40 +00001157
1158 // Emit remaining default initializers
1159 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner48431f92011-04-19 22:55:03 +00001160 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +00001161 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1162 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1163 }
1164 return V;
1165}
1166
Anders Carlssona3697c92009-11-23 17:57:54 +00001167static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1168 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +00001169
John McCall2de56d12010-08-25 11:45:40 +00001170 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +00001171 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +00001172
1173 if (isa<CXXThisExpr>(E)) {
1174 // We always assume that 'this' is never null.
1175 return false;
1176 }
1177
1178 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00001179 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +00001180 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +00001181 return false;
1182 }
1183
1184 return true;
1185}
1186
Chris Lattner7f02f722007-08-24 05:35:26 +00001187// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1188// have to handle a more broad range of conversions than explicit casts, as they
1189// handle things like function to ptr-to-function decay etc.
John McCallbc8d40d2011-06-24 21:55:10 +00001190Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmand8889622009-11-27 04:41:50 +00001191 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001192 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001193 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001194
Mike Stump7f79f9b2009-05-29 15:46:01 +00001195 if (!DestTy->isVoidType())
1196 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001197
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001198 // Since almost all cast kinds apply to scalars, this switch doesn't have
1199 // a default case, so the compiler will warn on a missing case. The cases
1200 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001201 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001202 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001203 case CK_BuiltinFnToFnPtr:
1204 llvm_unreachable("builtin functions are handled elsewhere");
1205
John McCall2de56d12010-08-25 11:45:40 +00001206 case CK_LValueBitCast:
1207 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001208 Value *V = EmitLValue(E).getAddress();
1209 V = Builder.CreateBitCast(V,
1210 ConvertType(CGF.getContext().getPointerType(DestTy)));
Eli Friedmand71f4422011-12-19 23:03:09 +00001211 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
Douglas Gregore39a3892010-07-13 23:17:26 +00001212 }
John McCalldc05b112011-09-10 01:16:55 +00001213
John McCall1d9b3b22011-09-09 05:25:32 +00001214 case CK_CPointerToObjCPointerCast:
1215 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001216 case CK_AnyPointerToBlockPointerCast:
1217 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001218 Value *Src = Visit(const_cast<Expr*>(E));
1219 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1220 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001221 case CK_AtomicToNonAtomic:
1222 case CK_NonAtomicToAtomic:
John McCall2de56d12010-08-25 11:45:40 +00001223 case CK_NoOp:
1224 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001225 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001226
John McCall2de56d12010-08-25 11:45:40 +00001227 case CK_BaseToDerived: {
Jordan Rose041ce8e2012-10-03 01:08:28 +00001228 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1229 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1230
1231 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001232 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001233 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001234 }
John McCall2de56d12010-08-25 11:45:40 +00001235 case CK_UncheckedDerivedToBase:
1236 case CK_DerivedToBase: {
Jordan Rose041ce8e2012-10-03 01:08:28 +00001237 const CXXRecordDecl *DerivedClassDecl =
1238 E->getType()->getPointeeCXXRecordDecl();
1239 assert(DerivedClassDecl && "DerivedToBase arg isn't a C++ object pointer!");
Anders Carlsson191dfe92009-09-12 04:57:16 +00001240
Anders Carlsson34a2d382010-04-24 21:06:20 +00001241 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001242 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001243 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001244 }
Anders Carlsson575b3742011-04-11 02:03:26 +00001245 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001246 Value *V = Visit(const_cast<Expr*>(E));
1247 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1248 return CGF.EmitDynamicCast(V, DCE);
1249 }
Eli Friedmand8889622009-11-27 04:41:50 +00001250
John McCall2de56d12010-08-25 11:45:40 +00001251 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001252 assert(E->getType()->isArrayType() &&
1253 "Array to pointer decay must have array source type!");
1254
1255 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1256
1257 // Note that VLA pointers are always decayed, so we don't need to do
1258 // anything here.
1259 if (!E->getType()->isVariableArrayType()) {
1260 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1261 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1262 ->getElementType()) &&
1263 "Expected pointer to array");
1264 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1265 }
1266
Chris Lattner410b12e2011-07-20 04:31:01 +00001267 // Make sure the array decay ends up being the right type. This matters if
1268 // the array type was of an incomplete type.
Chris Lattnercb8095f2011-07-20 04:59:57 +00001269 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
Eli Friedmanad35a832009-11-16 21:33:53 +00001270 }
John McCall2de56d12010-08-25 11:45:40 +00001271 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001272 return EmitLValue(E).getAddress();
1273
John McCall404cd162010-11-13 01:35:44 +00001274 case CK_NullToPointer:
1275 if (MustVisitNullValue(E))
1276 (void) Visit(E);
1277
1278 return llvm::ConstantPointerNull::get(
1279 cast<llvm::PointerType>(ConvertType(DestTy)));
1280
John McCall2de56d12010-08-25 11:45:40 +00001281 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001282 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001283 (void) Visit(E);
1284
John McCall0bab0cd2010-08-23 01:21:21 +00001285 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1286 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1287 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001288
John McCall4d4e5c12012-02-15 01:22:51 +00001289 case CK_ReinterpretMemberPointer:
John McCall2de56d12010-08-25 11:45:40 +00001290 case CK_BaseToDerivedMemberPointer:
1291 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001292 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001293
1294 // Note that the AST doesn't distinguish between checked and
1295 // unchecked member pointer conversions, so we always have to
1296 // implement checked conversions here. This is inefficient when
1297 // actual control flow may be required in order to perform the
1298 // check, which it is for data member pointers (but not member
1299 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001300 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001301 }
John McCallf85e1932011-06-15 23:02:42 +00001302
John McCall33e56f32011-09-10 06:18:15 +00001303 case CK_ARCProduceObject:
John McCallf85e1932011-06-15 23:02:42 +00001304 return CGF.EmitARCRetainScalarExpr(E);
John McCall33e56f32011-09-10 06:18:15 +00001305 case CK_ARCConsumeObject:
John McCallf85e1932011-06-15 23:02:42 +00001306 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall33e56f32011-09-10 06:18:15 +00001307 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00001308 llvm::Value *value = Visit(E);
1309 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1310 return CGF.EmitObjCConsumeObject(E->getType(), value);
1311 }
John McCall348f16f2011-10-04 06:23:45 +00001312 case CK_ARCExtendBlockObject:
1313 return CGF.EmitARCExtendBlockObject(E);
John McCallf85e1932011-06-15 23:02:42 +00001314
Douglas Gregorac1303e2012-02-22 05:02:47 +00001315 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmancae40c42012-02-28 01:08:45 +00001316 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Douglas Gregorac1303e2012-02-22 05:02:47 +00001317
John McCall2bb5d002010-11-13 09:02:35 +00001318 case CK_FloatingRealToComplex:
1319 case CK_FloatingComplexCast:
1320 case CK_IntegralRealToComplex:
1321 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001322 case CK_IntegralComplexToFloatingComplex:
1323 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001324 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001325 case CK_ToUnion:
1326 llvm_unreachable("scalar cast to non-scalar value");
John McCallf6a16482010-12-04 03:47:34 +00001327
John McCall0ae287a2010-12-01 04:43:34 +00001328 case CK_LValueToRValue:
1329 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001330 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001331 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001332
John McCall2de56d12010-08-25 11:45:40 +00001333 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001334 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001335
Anders Carlsson82debc72009-10-18 18:12:03 +00001336 // First, convert to the correct width so that we control the kind of
1337 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001338 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +00001339 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson82debc72009-10-18 18:12:03 +00001340 llvm::Value* IntResult =
1341 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001342
Anders Carlsson82debc72009-10-18 18:12:03 +00001343 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001344 }
Eli Friedman65949422011-06-25 02:58:47 +00001345 case CK_PointerToIntegral:
1346 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1347 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001348
John McCall2de56d12010-08-25 11:45:40 +00001349 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001350 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001351 return 0;
1352 }
John McCall2de56d12010-08-25 11:45:40 +00001353 case CK_VectorSplat: {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001354 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001355 Value *Elt = Visit(const_cast<Expr*>(E));
Craig Topper5fa56082012-02-06 05:05:50 +00001356 Elt = EmitScalarConversion(Elt, E->getType(),
1357 DestTy->getAs<VectorType>()->getElementType());
Eli Friedmanad35a832009-11-16 21:33:53 +00001358
1359 // Insert the element in element zero of an undef vector
1360 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +00001361 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +00001362 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Eli Friedmanad35a832009-11-16 21:33:53 +00001363
1364 // Splat the element across to all elements
Eli Friedmanad35a832009-11-16 21:33:53 +00001365 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner48431f92011-04-19 22:55:03 +00001366 llvm::Constant *Zero = Builder.getInt32(0);
Chris Lattner2ce88422012-01-25 05:34:41 +00001367 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero);
Eli Friedmanad35a832009-11-16 21:33:53 +00001368 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1369 return Yay;
1370 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001371
John McCall2de56d12010-08-25 11:45:40 +00001372 case CK_IntegralCast:
1373 case CK_IntegralToFloating:
1374 case CK_FloatingToIntegral:
1375 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001376 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
John McCalldaa8e4e2010-11-15 09:13:47 +00001377 case CK_IntegralToBoolean:
1378 return EmitIntToBoolConversion(Visit(E));
1379 case CK_PointerToBoolean:
1380 return EmitPointerToBoolConversion(Visit(E));
1381 case CK_FloatingToBoolean:
1382 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001383 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001384 llvm::Value *MemPtr = Visit(E);
1385 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1386 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001387 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001388
1389 case CK_FloatingComplexToReal:
1390 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001391 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001392
1393 case CK_FloatingComplexToBoolean:
1394 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001395 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001396
1397 // TODO: kill this function off, inline appropriate case here
1398 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1399 }
1400
John McCall0bab0cd2010-08-23 01:21:21 +00001401 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001402
John McCall61ad0e62010-11-16 06:21:14 +00001403 llvm_unreachable("unknown scalar cast");
Chris Lattner7f02f722007-08-24 05:35:26 +00001404}
1405
Chris Lattner33793202007-08-31 22:09:40 +00001406Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001407 CodeGenFunction::StmtExprEvaluation eval(CGF);
1408 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1409 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001410}
1411
Chris Lattner7f02f722007-08-24 05:35:26 +00001412//===----------------------------------------------------------------------===//
1413// Unary Operators
1414//===----------------------------------------------------------------------===//
1415
Chris Lattner8c11a652010-06-26 22:09:34 +00001416llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001417EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1418 llvm::Value *InVal,
1419 llvm::Value *NextVal, bool IsInc) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001420 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00001421 case LangOptions::SOB_Defined:
1422 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
Richard Smith9d3e2262012-08-25 00:32:28 +00001423 case LangOptions::SOB_Undefined:
1424 if (!CGF.CatchUndefined)
1425 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1426 // Fall through.
Anton Yartsev683564a2011-02-07 02:17:30 +00001427 case LangOptions::SOB_Trapping:
1428 BinOpInfo BinOp;
1429 BinOp.LHS = InVal;
1430 BinOp.RHS = NextVal;
1431 BinOp.Ty = E->getType();
1432 BinOp.Opcode = BO_Add;
Benjamin Kramerddc57332012-10-03 20:58:04 +00001433 BinOp.FPContractable = false;
Anton Yartsev683564a2011-02-07 02:17:30 +00001434 BinOp.E = E;
1435 return EmitOverflowCheckedBinOp(BinOp);
Anton Yartsev683564a2011-02-07 02:17:30 +00001436 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001437 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev683564a2011-02-07 02:17:30 +00001438}
1439
John McCall5936e332011-02-15 09:22:45 +00001440llvm::Value *
1441ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1442 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001443
John McCall5936e332011-02-15 09:22:45 +00001444 QualType type = E->getSubExpr()->getType();
John McCall545d9962011-06-25 02:11:03 +00001445 llvm::Value *value = EmitLoadOfLValue(LV);
John McCall5936e332011-02-15 09:22:45 +00001446 llvm::Value *input = value;
David Chisnall7a7ee302012-01-16 17:27:18 +00001447 llvm::PHINode *atomicPHI = 0;
Anton Yartsev683564a2011-02-07 02:17:30 +00001448
John McCall5936e332011-02-15 09:22:45 +00001449 int amount = (isInc ? 1 : -1);
1450
David Chisnall7a7ee302012-01-16 17:27:18 +00001451 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1452 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1453 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1454 Builder.CreateBr(opBB);
1455 Builder.SetInsertPoint(opBB);
1456 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1457 atomicPHI->addIncoming(value, startBB);
1458 type = atomicTy->getValueType();
1459 value = atomicPHI;
1460 }
1461
John McCall5936e332011-02-15 09:22:45 +00001462 // Special case of integer increment that we have to check first: bool++.
1463 // Due to promotion rules, we get:
1464 // bool++ -> bool = bool + 1
1465 // -> bool = (int)bool + 1
1466 // -> bool = ((int)bool + 1 != 0)
1467 // An interesting aspect of this is that increment is always true.
1468 // Decrement does not have this property.
1469 if (isInc && type->isBooleanType()) {
1470 value = Builder.getTrue();
1471
1472 // Most common case by far: integer increment.
1473 } else if (type->isIntegerType()) {
1474
Michael Liao36d5cea2012-08-28 16:55:13 +00001475 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCall5936e332011-02-15 09:22:45 +00001476
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001477 // Note that signed integer inc/dec with width less than int can't
1478 // overflow because of promotion rules; we're just eliding a few steps here.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001479 if (type->isSignedIntegerOrEnumerationType() &&
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001480 value->getType()->getPrimitiveSizeInBits() >=
John McCall913dab22011-06-25 01:32:37 +00001481 CGF.IntTy->getBitWidth())
John McCall5936e332011-02-15 09:22:45 +00001482 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
John McCall5936e332011-02-15 09:22:45 +00001483 else
1484 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1485
1486 // Next most common: pointer increment.
1487 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1488 QualType type = ptr->getPointeeType();
1489
1490 // VLA types don't have constant size.
John McCall913dab22011-06-25 01:32:37 +00001491 if (const VariableArrayType *vla
1492 = CGF.getContext().getAsVariableArrayType(type)) {
1493 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCallbc8d40d2011-06-24 21:55:10 +00001494 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
David Blaikie4e4d0842012-03-11 07:00:24 +00001495 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
John McCallbc8d40d2011-06-24 21:55:10 +00001496 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2cb42222011-03-01 00:03:48 +00001497 else
John McCallbc8d40d2011-06-24 21:55:10 +00001498 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
John McCall5936e332011-02-15 09:22:45 +00001499
1500 // Arithmetic on function pointers (!) is just +-1.
1501 } else if (type->isFunctionType()) {
Chris Lattner48431f92011-04-19 22:55:03 +00001502 llvm::Value *amt = Builder.getInt32(amount);
John McCall5936e332011-02-15 09:22:45 +00001503
1504 value = CGF.EmitCastToVoidPtr(value);
David Blaikie4e4d0842012-03-11 07:00:24 +00001505 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001506 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1507 else
1508 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001509 value = Builder.CreateBitCast(value, input->getType());
1510
1511 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001512 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001513 llvm::Value *amt = Builder.getInt32(amount);
David Blaikie4e4d0842012-03-11 07:00:24 +00001514 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001515 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1516 else
1517 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001518 }
1519
1520 // Vector increment/decrement.
1521 } else if (type->isVectorType()) {
1522 if (type->hasIntegerRepresentation()) {
1523 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1524
Eli Friedmand4b9ee32011-05-06 18:04:18 +00001525 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCall5936e332011-02-15 09:22:45 +00001526 } else {
1527 value = Builder.CreateFAdd(
1528 value,
1529 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001530 isInc ? "inc" : "dec");
1531 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001532
John McCall5936e332011-02-15 09:22:45 +00001533 // Floating point.
1534 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001535 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001536 llvm::Value *amt;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001537
1538 if (type->isHalfType()) {
1539 // Another special case: half FP increment should be done via float
1540 value =
1541 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1542 input);
1543 }
1544
John McCall5936e332011-02-15 09:22:45 +00001545 if (value->getType()->isFloatTy())
1546 amt = llvm::ConstantFP::get(VMContext,
1547 llvm::APFloat(static_cast<float>(amount)));
1548 else if (value->getType()->isDoubleTy())
1549 amt = llvm::ConstantFP::get(VMContext,
1550 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001551 else {
John McCall5936e332011-02-15 09:22:45 +00001552 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001553 bool ignored;
1554 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1555 &ignored);
John McCall5936e332011-02-15 09:22:45 +00001556 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001557 }
John McCall5936e332011-02-15 09:22:45 +00001558 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1559
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001560 if (type->isHalfType())
1561 value =
1562 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1563 value);
1564
John McCall5936e332011-02-15 09:22:45 +00001565 // Objective-C pointer types.
1566 } else {
1567 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1568 value = CGF.EmitCastToVoidPtr(value);
1569
1570 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1571 if (!isInc) size = -size;
1572 llvm::Value *sizeValue =
1573 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1574
David Blaikie4e4d0842012-03-11 07:00:24 +00001575 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001576 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1577 else
1578 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001579 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001580 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001581
1582 if (atomicPHI) {
1583 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1584 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1585 llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
1586 value, llvm::SequentiallyConsistent);
1587 atomicPHI->addIncoming(old, opBB);
1588 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1589 Builder.CreateCondBr(success, contBB, opBB);
1590 Builder.SetInsertPoint(contBB);
1591 return isPre ? value : input;
1592 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001593
Chris Lattner8c11a652010-06-26 22:09:34 +00001594 // Store the updated result through the lvalue.
1595 if (LV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001596 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001597 else
John McCall545d9962011-06-25 02:11:03 +00001598 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001599
Chris Lattner8c11a652010-06-26 22:09:34 +00001600 // If this is a postinc, return the value read from memory, otherwise use the
1601 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001602 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001603}
1604
1605
1606
Chris Lattner7f02f722007-08-24 05:35:26 +00001607Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001608 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001609 // Emit unary minus with EmitSub so we handle overflow cases etc.
1610 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001611 BinOp.RHS = Visit(E->getSubExpr());
1612
1613 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1614 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1615 else
1616 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001617 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001618 BinOp.Opcode = BO_Sub;
Benjamin Kramerddc57332012-10-03 20:58:04 +00001619 BinOp.FPContractable = false;
Chris Lattner9a207232010-06-26 21:48:21 +00001620 BinOp.E = E;
1621 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001622}
1623
1624Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001625 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001626 Value *Op = Visit(E->getSubExpr());
1627 return Builder.CreateNot(Op, "neg");
1628}
1629
1630Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00001631
1632 // Perform vector logical not on comparison with zero vector.
1633 if (E->getType()->isExtVectorType()) {
1634 Value *Oper = Visit(E->getSubExpr());
1635 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1636 Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1637 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1638 }
1639
Chris Lattner7f02f722007-08-24 05:35:26 +00001640 // Compare operand to zero.
1641 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001642
Chris Lattner7f02f722007-08-24 05:35:26 +00001643 // Invert value.
1644 // TODO: Could dynamically modify easy computations here. For example, if
1645 // the operand is an icmp ne, turn into icmp eq.
1646 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001647
Anders Carlsson9f84d882009-05-19 18:44:53 +00001648 // ZExt result to the expr type.
1649 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001650}
1651
Eli Friedman0027d2b2010-08-05 09:58:49 +00001652Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1653 // Try folding the offsetof to a constant.
Richard Smith80d4b552011-12-28 19:48:30 +00001654 llvm::APSInt Value;
1655 if (E->EvaluateAsInt(Value, CGF.getContext()))
1656 return Builder.getInt(Value);
Eli Friedman0027d2b2010-08-05 09:58:49 +00001657
1658 // Loop over the components of the offsetof to compute the value.
1659 unsigned n = E->getNumComponents();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001660 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001661 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1662 QualType CurrentType = E->getTypeSourceInfo()->getType();
1663 for (unsigned i = 0; i != n; ++i) {
1664 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001665 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001666 switch (ON.getKind()) {
1667 case OffsetOfExpr::OffsetOfNode::Array: {
1668 // Compute the index
1669 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1670 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001671 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedman0027d2b2010-08-05 09:58:49 +00001672 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1673
1674 // Save the element type
1675 CurrentType =
1676 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1677
1678 // Compute the element size
1679 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1680 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1681
1682 // Multiply out to compute the result
1683 Offset = Builder.CreateMul(Idx, ElemSize);
1684 break;
1685 }
1686
1687 case OffsetOfExpr::OffsetOfNode::Field: {
1688 FieldDecl *MemberDecl = ON.getField();
1689 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1690 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1691
1692 // Compute the index of the field in its parent.
1693 unsigned i = 0;
1694 // FIXME: It would be nice if we didn't have to loop here!
1695 for (RecordDecl::field_iterator Field = RD->field_begin(),
1696 FieldEnd = RD->field_end();
David Blaikie262bc182012-04-30 02:36:29 +00001697 Field != FieldEnd; ++Field, ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00001698 if (*Field == MemberDecl)
Eli Friedman0027d2b2010-08-05 09:58:49 +00001699 break;
1700 }
1701 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1702
1703 // Compute the offset to the field
1704 int64_t OffsetInt = RL.getFieldOffset(i) /
1705 CGF.getContext().getCharWidth();
1706 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1707
1708 // Save the element type.
1709 CurrentType = MemberDecl->getType();
1710 break;
1711 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001712
Eli Friedman0027d2b2010-08-05 09:58:49 +00001713 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001714 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001715
Eli Friedman0027d2b2010-08-05 09:58:49 +00001716 case OffsetOfExpr::OffsetOfNode::Base: {
1717 if (ON.getBase()->isVirtual()) {
1718 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1719 continue;
1720 }
1721
1722 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1723 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1724
1725 // Save the element type.
1726 CurrentType = ON.getBase()->getType();
1727
1728 // Compute the offset to the base.
1729 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1730 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001731 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1732 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001733 break;
1734 }
1735 }
1736 Result = Builder.CreateAdd(Result, Offset);
1737 }
1738 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001739}
1740
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001741/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001742/// argument of the sizeof expression as an integer.
1743Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001744ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1745 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001746 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001747 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001748 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001749 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1750 if (E->isArgumentType()) {
1751 // sizeof(type) - make sure to emit the VLA size.
John McCallbc8d40d2011-06-24 21:55:10 +00001752 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001753 } else {
1754 // C99 6.5.3.4p2: If the argument is an expression of type
1755 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001756 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001757 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001758
John McCallbc8d40d2011-06-24 21:55:10 +00001759 QualType eltType;
1760 llvm::Value *numElts;
1761 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1762
1763 llvm::Value *size = numElts;
1764
1765 // Scale the number of non-VLA elements by the non-VLA element size.
1766 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1767 if (!eltSize.isOne())
1768 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1769
1770 return size;
Anders Carlssonb50525b2008-12-21 03:33:21 +00001771 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001772 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001773
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001774 // If this isn't sizeof(vla), the result must be constant; use the constant
1775 // folding logic so we don't have to duplicate it here.
Richard Smith80d4b552011-12-28 19:48:30 +00001776 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001777}
1778
Chris Lattner46f93d02007-08-24 21:20:17 +00001779Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1780 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001781 if (Op->getType()->isAnyComplexType()) {
1782 // If it's an l-value, load through the appropriate subobject l-value.
1783 // Note that we have to ask E because Op might be an l-value that
1784 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001785 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001786 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001787
1788 // Otherwise, calculate and project.
1789 return CGF.EmitComplexExpr(Op, false, true).first;
1790 }
1791
Chris Lattner46f93d02007-08-24 21:20:17 +00001792 return Visit(Op);
1793}
John McCallb418d742010-11-16 10:08:07 +00001794
Chris Lattner46f93d02007-08-24 21:20:17 +00001795Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1796 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001797 if (Op->getType()->isAnyComplexType()) {
1798 // If it's an l-value, load through the appropriate subobject l-value.
1799 // Note that we have to ask E because Op might be an l-value that
1800 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001801 if (Op->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001802 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001803
1804 // Otherwise, calculate and project.
1805 return CGF.EmitComplexExpr(Op, true, false).second;
1806 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001807
Mike Stump7f79f9b2009-05-29 15:46:01 +00001808 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1809 // effects are evaluated, but not the actual value.
Richard Smithdfb80de2012-02-18 20:53:32 +00001810 if (Op->isGLValue())
1811 CGF.EmitLValue(Op);
1812 else
1813 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001814 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001815}
1816
Chris Lattner7f02f722007-08-24 05:35:26 +00001817//===----------------------------------------------------------------------===//
1818// Binary Operators
1819//===----------------------------------------------------------------------===//
1820
1821BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001822 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001823 BinOpInfo Result;
1824 Result.LHS = Visit(E->getLHS());
1825 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001826 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001827 Result.Opcode = E->getOpcode();
Lang Hamesbe9af122012-10-02 04:45:10 +00001828 Result.FPContractable = E->isFPContractable();
Chris Lattner7f02f722007-08-24 05:35:26 +00001829 Result.E = E;
1830 return Result;
1831}
1832
Douglas Gregor6a03e342010-04-23 04:16:32 +00001833LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1834 const CompoundAssignOperator *E,
1835 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001836 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001837 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001838 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001839
Eli Friedmanab3a8522009-03-28 01:22:36 +00001840 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001841 // This needs to go through the complex expression emitter, but it's a tad
1842 // complicated to do that... I'm leaving it out for now. (Note that we do
1843 // actually need the imaginary part of the RHS for multiplication and
1844 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001845 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001846 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001847 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001848 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001849
Mike Stumpcc0442f2009-05-22 19:07:20 +00001850 // Emit the RHS first. __block variables need to have the rhs evaluated
1851 // first, plus this should improve codegen a little.
1852 OpInfo.RHS = Visit(E->getRHS());
1853 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001854 OpInfo.Opcode = E->getOpcode();
Benjamin Kramerddc57332012-10-03 20:58:04 +00001855 OpInfo.FPContractable = false;
Mike Stumpcc0442f2009-05-22 19:07:20 +00001856 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001857 // Load/convert the LHS.
Richard Smith7ac9ef12012-09-08 02:08:36 +00001858 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall545d9962011-06-25 02:11:03 +00001859 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
David Chisnall7a7ee302012-01-16 17:27:18 +00001860
1861 llvm::PHINode *atomicPHI = 0;
Eli Friedman860a3192012-06-16 02:19:17 +00001862 if (LHSTy->isAtomicType()) {
David Chisnall7a7ee302012-01-16 17:27:18 +00001863 // FIXME: For floating point types, we should be saving and restoring the
1864 // floating point environment in the loop.
1865 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1866 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1867 Builder.CreateBr(opBB);
1868 Builder.SetInsertPoint(opBB);
1869 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
1870 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00001871 OpInfo.LHS = atomicPHI;
1872 }
Eli Friedman860a3192012-06-16 02:19:17 +00001873
1874 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1875 E->getComputationLHSType());
1876
Chris Lattner1f1ded92007-08-24 21:00:35 +00001877 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001878 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001879
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001880 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001881 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
David Chisnall7a7ee302012-01-16 17:27:18 +00001882
1883 if (atomicPHI) {
1884 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1885 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1886 llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
1887 Result, llvm::SequentiallyConsistent);
1888 atomicPHI->addIncoming(old, opBB);
1889 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1890 Builder.CreateCondBr(success, contBB, opBB);
1891 Builder.SetInsertPoint(contBB);
1892 return LHSLV;
1893 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001894
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001895 // Store the result value into the LHS lvalue. Bit-fields are handled
1896 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1897 // 'An assignment expression has the value of the left operand after the
1898 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001899 if (LHSLV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001900 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001901 else
John McCall545d9962011-06-25 02:11:03 +00001902 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001903
Douglas Gregor6a03e342010-04-23 04:16:32 +00001904 return LHSLV;
1905}
1906
1907Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1908 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1909 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001910 Value *RHS;
1911 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1912
1913 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001914 if (Ignore)
1915 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001916
John McCallb418d742010-11-16 10:08:07 +00001917 // The result of an assignment in C is the assigned r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00001918 if (!CGF.getContext().getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00001919 return RHS;
1920
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001921 // If the lvalue is non-volatile, return the computed value of the assignment.
1922 if (!LHS.isVolatileQualified())
1923 return RHS;
1924
1925 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00001926 return EmitLoadOfLValue(LHS);
Chris Lattner1f1ded92007-08-24 21:00:35 +00001927}
1928
Chris Lattner80230302010-09-11 21:47:09 +00001929void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith7ac9ef12012-09-08 02:08:36 +00001930 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001931 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
Chris Lattner80230302010-09-11 21:47:09 +00001932
1933 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1934 llvm::Value *IntMin =
Chris Lattner48431f92011-04-19 22:55:03 +00001935 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner80230302010-09-11 21:47:09 +00001936 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1937
Richard Smith7ac9ef12012-09-08 02:08:36 +00001938 llvm::Value *Cond1 = Builder.CreateICmpNE(Ops.RHS, Zero);
1939 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
1940 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
1941 llvm::Value *Cond2 = Builder.CreateOr(LHSCmp, RHSCmp, "or");
Richard Smith4def70d2012-10-09 19:52:38 +00001942 EmitBinOpCheck(Builder.CreateAnd(Cond1, Cond2, "and"), Ops);
Chris Lattner80230302010-09-11 21:47:09 +00001943 } else {
Richard Smith4def70d2012-10-09 19:52:38 +00001944 EmitBinOpCheck(Builder.CreateICmpNE(Ops.RHS, Zero), Ops);
Chris Lattner80230302010-09-11 21:47:09 +00001945 }
Chris Lattner80230302010-09-11 21:47:09 +00001946}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001947
Chris Lattner7f02f722007-08-24 05:35:26 +00001948Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Richard Smith7ac9ef12012-09-08 02:08:36 +00001949 if (isTrapvOverflowBehavior()) {
Chris Lattner80230302010-09-11 21:47:09 +00001950 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1951
1952 if (Ops.Ty->isIntegerType())
1953 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
Richard Smith7ac9ef12012-09-08 02:08:36 +00001954 else if (Ops.Ty->isRealFloatingType())
Richard Smith4def70d2012-10-09 19:52:38 +00001955 EmitBinOpCheck(Builder.CreateFCmpUNE(Ops.RHS, Zero), Ops);
Chris Lattner80230302010-09-11 21:47:09 +00001956 }
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001957 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
1958 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
David Blaikie4e4d0842012-03-11 07:00:24 +00001959 if (CGF.getContext().getLangOpts().OpenCL) {
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001960 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
1961 llvm::Type *ValTy = Val->getType();
1962 if (ValTy->isFloatTy() ||
1963 (isa<llvm::VectorType>(ValTy) &&
1964 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sands82500162012-04-10 08:23:07 +00001965 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001966 }
1967 return Val;
1968 }
Douglas Gregorf6094622010-07-23 15:58:24 +00001969 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001970 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1971 else
1972 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1973}
1974
1975Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1976 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner80230302010-09-11 21:47:09 +00001977 if (isTrapvOverflowBehavior()) {
1978 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1979
1980 if (Ops.Ty->isIntegerType())
1981 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1982 }
1983
Eli Friedman52d68742011-04-10 04:44:11 +00001984 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001985 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1986 else
1987 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1988}
1989
Mike Stump2add4732009-04-01 20:28:16 +00001990Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1991 unsigned IID;
1992 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001993
Chris Lattner9a207232010-06-26 21:48:21 +00001994 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001995 case BO_Add:
1996 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001997 OpID = 1;
1998 IID = llvm::Intrinsic::sadd_with_overflow;
1999 break;
John McCall2de56d12010-08-25 11:45:40 +00002000 case BO_Sub:
2001 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002002 OpID = 2;
2003 IID = llvm::Intrinsic::ssub_with_overflow;
2004 break;
John McCall2de56d12010-08-25 11:45:40 +00002005 case BO_Mul:
2006 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002007 OpID = 3;
2008 IID = llvm::Intrinsic::smul_with_overflow;
2009 break;
2010 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002011 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump2add4732009-04-01 20:28:16 +00002012 }
Mike Stump035cf892009-04-02 18:15:54 +00002013 OpID <<= 1;
2014 OpID |= 1;
2015
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002016 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump2add4732009-04-01 20:28:16 +00002017
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002018 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump2add4732009-04-01 20:28:16 +00002019
2020 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
2021 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2022 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2023
Richard Smith7ac9ef12012-09-08 02:08:36 +00002024 // Handle overflow with llvm.trap if no custom handler has been specified.
2025 const std::string *handlerName =
2026 &CGF.getContext().getLangOpts().OverflowHandler;
2027 if (handlerName->empty()) {
Richard Smith4def70d2012-10-09 19:52:38 +00002028 EmitBinOpCheck(Builder.CreateNot(overflow), Ops);
Richard Smith7ac9ef12012-09-08 02:08:36 +00002029 return result;
2030 }
2031
Mike Stump2add4732009-04-01 20:28:16 +00002032 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00002033 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendling14ef3192011-07-07 21:13:10 +00002034 llvm::Function::iterator insertPt = initialBB;
2035 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
2036 llvm::next(insertPt));
Chris Lattner93a00352010-08-07 00:20:46 +00002037 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00002038
2039 Builder.CreateCondBr(overflow, overflowBB, continueBB);
2040
David Chisnall7f18e672010-09-17 18:29:54 +00002041 // If an overflow handler is set, then we want to call it and then use its
2042 // result, if it returns.
2043 Builder.SetInsertPoint(overflowBB);
2044
2045 // Get the overflow handler.
Chris Lattner8b418682012-02-07 00:39:47 +00002046 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002047 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnall7f18e672010-09-17 18:29:54 +00002048 llvm::FunctionType *handlerTy =
2049 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2050 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2051
2052 // Sign extend the args to 64-bit, so that we can use the same handler for
2053 // all types of overflow.
2054 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2055 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2056
2057 // Call the handler with the two arguments, the operation, and the size of
2058 // the result.
2059 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
2060 Builder.getInt8(OpID),
2061 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
2062
2063 // Truncate the result back to the desired size.
2064 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2065 Builder.CreateBr(continueBB);
2066
Mike Stump2add4732009-04-01 20:28:16 +00002067 Builder.SetInsertPoint(continueBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00002068 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnall7f18e672010-09-17 18:29:54 +00002069 phi->addIncoming(result, initialBB);
2070 phi->addIncoming(handlerResult, overflowBB);
2071
2072 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00002073}
Chris Lattner7f02f722007-08-24 05:35:26 +00002074
John McCall913dab22011-06-25 01:32:37 +00002075/// Emit pointer + index arithmetic.
2076static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2077 const BinOpInfo &op,
2078 bool isSubtraction) {
2079 // Must have binary (not unary) expr here. Unary pointer
2080 // increment/decrement doesn't use this path.
2081 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2082
2083 Value *pointer = op.LHS;
2084 Expr *pointerOperand = expr->getLHS();
2085 Value *index = op.RHS;
2086 Expr *indexOperand = expr->getRHS();
2087
2088 // In a subtraction, the LHS is always the pointer.
2089 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2090 std::swap(pointer, index);
2091 std::swap(pointerOperand, indexOperand);
2092 }
2093
2094 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
2095 if (width != CGF.PointerWidthInBits) {
2096 // Zero-extend or sign-extend the pointer value according to
2097 // whether the index is signed or not.
2098 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
2099 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
2100 "idx.ext");
2101 }
2102
2103 // If this is subtraction, negate the index.
2104 if (isSubtraction)
2105 index = CGF.Builder.CreateNeg(index, "idx.neg");
2106
2107 const PointerType *pointerType
2108 = pointerOperand->getType()->getAs<PointerType>();
2109 if (!pointerType) {
2110 QualType objectType = pointerOperand->getType()
2111 ->castAs<ObjCObjectPointerType>()
2112 ->getPointeeType();
2113 llvm::Value *objectSize
2114 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2115
2116 index = CGF.Builder.CreateMul(index, objectSize);
2117
2118 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2119 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2120 return CGF.Builder.CreateBitCast(result, pointer->getType());
2121 }
2122
2123 QualType elementType = pointerType->getPointeeType();
2124 if (const VariableArrayType *vla
2125 = CGF.getContext().getAsVariableArrayType(elementType)) {
2126 // The element count here is the total number of non-VLA elements.
2127 llvm::Value *numElements = CGF.getVLASize(vla).first;
2128
2129 // Effectively, the multiply by the VLA size is part of the GEP.
2130 // GEP indexes are signed, and scaling an index isn't permitted to
2131 // signed-overflow, so we use the same semantics for our explicit
2132 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +00002133 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall913dab22011-06-25 01:32:37 +00002134 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2135 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2136 } else {
2137 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2138 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattnera4d71452010-06-26 21:25:03 +00002139 }
John McCall913dab22011-06-25 01:32:37 +00002140 return pointer;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002141 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00002142
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002143 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2144 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2145 // future proof.
John McCall913dab22011-06-25 01:32:37 +00002146 if (elementType->isVoidType() || elementType->isFunctionType()) {
2147 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2148 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2149 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002150 }
2151
David Blaikie4e4d0842012-03-11 07:00:24 +00002152 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall913dab22011-06-25 01:32:37 +00002153 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2154
2155 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00002156}
2157
Lang Hamesbe9af122012-10-02 04:45:10 +00002158// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2159// Addend. Use negMul and negAdd to negate the first operand of the Mul or
2160// the add operand respectively. This allows fmuladd to represent a*b-c, or
2161// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2162// efficient operations.
2163static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2164 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2165 bool negMul, bool negAdd) {
2166 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
2167
2168 Value *MulOp0 = MulOp->getOperand(0);
2169 Value *MulOp1 = MulOp->getOperand(1);
2170 if (negMul) {
2171 MulOp0 =
2172 Builder.CreateFSub(
2173 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2174 "neg");
2175 } else if (negAdd) {
2176 Addend =
2177 Builder.CreateFSub(
2178 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2179 "neg");
2180 }
2181
2182 Value *FMulAdd =
2183 Builder.CreateCall3(
2184 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2185 MulOp0, MulOp1, Addend);
2186 MulOp->eraseFromParent();
2187
2188 return FMulAdd;
2189}
2190
2191// Check whether it would be legal to emit an fmuladd intrinsic call to
2192// represent op and if so, build the fmuladd.
2193//
2194// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2195// Does NOT check the type of the operation - it's assumed that this function
2196// will be called from contexts where it's known that the type is contractable.
2197static Value* tryEmitFMulAdd(const BinOpInfo &op,
2198 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2199 bool isSub=false) {
2200
2201 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2202 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2203 "Only fadd/fsub can be the root of an fmuladd.");
2204
2205 // Check whether this op is marked as fusable.
2206 if (!op.FPContractable)
2207 return 0;
2208
2209 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2210 // either disabled, or handled entirely by the LLVM backend).
2211 if (CGF.getContext().getLangOpts().getFPContractMode() != LangOptions::FPC_On)
2212 return 0;
2213
2214 // We have a potentially fusable op. Look for a mul on one of the operands.
2215 if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2216 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hamesff4ae6d2012-10-04 03:23:25 +00002217 assert(LHSBinOp->getNumUses() == 0 &&
2218 "Operations with multiple uses shouldn't be contracted.");
Lang Hamesbe9af122012-10-02 04:45:10 +00002219 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2220 }
2221 } else if (llvm::BinaryOperator* RHSBinOp =
2222 dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2223 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hamesff4ae6d2012-10-04 03:23:25 +00002224 assert(RHSBinOp->getNumUses() == 0 &&
2225 "Operations with multiple uses shouldn't be contracted.");
Lang Hamesbe9af122012-10-02 04:45:10 +00002226 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2227 }
2228 }
2229
2230 return 0;
2231}
2232
John McCall913dab22011-06-25 01:32:37 +00002233Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2234 if (op.LHS->getType()->isPointerTy() ||
2235 op.RHS->getType()->isPointerTy())
2236 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2237
2238 if (op.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002239 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
John McCall913dab22011-06-25 01:32:37 +00002240 case LangOptions::SOB_Defined:
2241 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith9d3e2262012-08-25 00:32:28 +00002242 case LangOptions::SOB_Undefined:
2243 if (!CGF.CatchUndefined)
2244 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2245 // Fall through.
John McCall913dab22011-06-25 01:32:37 +00002246 case LangOptions::SOB_Trapping:
2247 return EmitOverflowCheckedBinOp(op);
2248 }
2249 }
2250
Lang Hamesbe9af122012-10-02 04:45:10 +00002251 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2252 // Try to form an fmuladd.
2253 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2254 return FMulAdd;
2255
John McCall913dab22011-06-25 01:32:37 +00002256 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
Lang Hamesbe9af122012-10-02 04:45:10 +00002257 }
John McCall913dab22011-06-25 01:32:37 +00002258
2259 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2260}
2261
2262Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2263 // The LHS is always a pointer if either side is.
2264 if (!op.LHS->getType()->isPointerTy()) {
2265 if (op.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002266 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00002267 case LangOptions::SOB_Defined:
John McCall913dab22011-06-25 01:32:37 +00002268 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith9d3e2262012-08-25 00:32:28 +00002269 case LangOptions::SOB_Undefined:
2270 if (!CGF.CatchUndefined)
2271 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2272 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +00002273 case LangOptions::SOB_Trapping:
John McCall913dab22011-06-25 01:32:37 +00002274 return EmitOverflowCheckedBinOp(op);
Chris Lattnera4d71452010-06-26 21:25:03 +00002275 }
2276 }
2277
Lang Hamesbe9af122012-10-02 04:45:10 +00002278 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2279 // Try to form an fmuladd.
2280 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2281 return FMulAdd;
John McCall913dab22011-06-25 01:32:37 +00002282 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Lang Hamesbe9af122012-10-02 04:45:10 +00002283 }
Chris Lattner2eb91e42010-03-29 17:28:16 +00002284
John McCall913dab22011-06-25 01:32:37 +00002285 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00002286 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00002287
John McCall913dab22011-06-25 01:32:37 +00002288 // If the RHS is not a pointer, then we have normal pointer
2289 // arithmetic.
2290 if (!op.RHS->getType()->isPointerTy())
2291 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmandaa24a22009-03-28 02:45:41 +00002292
John McCall913dab22011-06-25 01:32:37 +00002293 // Otherwise, this is a pointer subtraction.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00002294
John McCall913dab22011-06-25 01:32:37 +00002295 // Do the raw subtraction part.
2296 llvm::Value *LHS
2297 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2298 llvm::Value *RHS
2299 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2300 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar2a866252009-04-25 05:08:32 +00002301
John McCall913dab22011-06-25 01:32:37 +00002302 // Okay, figure out the element size.
2303 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2304 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002305
John McCall913dab22011-06-25 01:32:37 +00002306 llvm::Value *divisor = 0;
2307
2308 // For a variable-length array, this is going to be non-constant.
2309 if (const VariableArrayType *vla
2310 = CGF.getContext().getAsVariableArrayType(elementType)) {
2311 llvm::Value *numElements;
2312 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2313
2314 divisor = numElements;
2315
2316 // Scale the number of non-VLA elements by the non-VLA element size.
2317 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2318 if (!eltSize.isOne())
2319 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2320
2321 // For everything elese, we can just compute it, safe in the
2322 // assumption that Sema won't let anything through that we can't
2323 // safely compute the size of.
2324 } else {
2325 CharUnits elementSize;
2326 // Handle GCC extension for pointer arithmetic on void* and
2327 // function pointer types.
2328 if (elementType->isVoidType() || elementType->isFunctionType())
2329 elementSize = CharUnits::One();
2330 else
2331 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2332
2333 // Don't even emit the divide for element size of 1.
2334 if (elementSize.isOne())
2335 return diffInChars;
2336
2337 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner7f02f722007-08-24 05:35:26 +00002338 }
Chris Lattner2cb42222011-03-01 00:03:48 +00002339
Chris Lattner2cb42222011-03-01 00:03:48 +00002340 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2341 // pointer difference in C is only defined in the case where both operands
2342 // are pointing to elements of an array.
John McCall913dab22011-06-25 01:32:37 +00002343 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002344}
2345
2346Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2347 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2348 // RHS to the same size as the LHS.
2349 Value *RHS = Ops.RHS;
2350 if (Ops.LHS->getType() != RHS->getType())
2351 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002352
Richard Smith9d3e2262012-08-25 00:32:28 +00002353 if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
Mike Stumpbe07f602009-12-14 21:58:14 +00002354 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
Richard Smith9d3e2262012-08-25 00:32:28 +00002355 llvm::Value *WidthMinusOne =
Richard Smith5b092ef2012-08-25 05:43:00 +00002356 llvm::ConstantInt::get(RHS->getType(), Width - 1);
Richard Smith4def70d2012-10-09 19:52:38 +00002357 // FIXME: Emit the branching explicitly rather than emitting the check
2358 // twice.
2359 EmitBinOpCheck(Builder.CreateICmpULE(RHS, WidthMinusOne), Ops);
Richard Smith9d3e2262012-08-25 00:32:28 +00002360
2361 if (Ops.Ty->hasSignedIntegerRepresentation()) {
2362 // Check whether we are shifting any non-zero bits off the top of the
2363 // integer.
Richard Smith9d3e2262012-08-25 00:32:28 +00002364 llvm::Value *BitsShiftedOff =
2365 Builder.CreateLShr(Ops.LHS,
2366 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2367 /*NUW*/true, /*NSW*/true),
2368 "shl.check");
2369 if (CGF.getLangOpts().CPlusPlus) {
2370 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2371 // Under C++11's rules, shifting a 1 bit into the sign bit is
2372 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2373 // define signed left shifts, so we use the C99 and C++11 rules there).
2374 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2375 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2376 }
2377 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Richard Smith4def70d2012-10-09 19:52:38 +00002378 EmitBinOpCheck(Builder.CreateICmpEQ(BitsShiftedOff, Zero), Ops);
Richard Smith9d3e2262012-08-25 00:32:28 +00002379 }
Mike Stumpbe07f602009-12-14 21:58:14 +00002380 }
2381
Chris Lattner7f02f722007-08-24 05:35:26 +00002382 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2383}
2384
2385Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2386 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2387 // RHS to the same size as the LHS.
2388 Value *RHS = Ops.RHS;
2389 if (Ops.LHS->getType() != RHS->getType())
2390 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002391
Richard Smith9d3e2262012-08-25 00:32:28 +00002392 if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
Mike Stumpbe07f602009-12-14 21:58:14 +00002393 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
Richard Smith7ac9ef12012-09-08 02:08:36 +00002394 llvm::Value *WidthVal = llvm::ConstantInt::get(RHS->getType(), Width);
Richard Smith4def70d2012-10-09 19:52:38 +00002395 EmitBinOpCheck(Builder.CreateICmpULT(RHS, WidthVal), Ops);
Mike Stumpbe07f602009-12-14 21:58:14 +00002396 }
2397
Douglas Gregorf6094622010-07-23 15:58:24 +00002398 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002399 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2400 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2401}
2402
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002403enum IntrinsicType { VCMPEQ, VCMPGT };
2404// return corresponding comparison intrinsic for given vector type
2405static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2406 BuiltinType::Kind ElemKind) {
2407 switch (ElemKind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002408 default: llvm_unreachable("unexpected element type");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002409 case BuiltinType::Char_U:
2410 case BuiltinType::UChar:
2411 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2412 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002413 case BuiltinType::Char_S:
2414 case BuiltinType::SChar:
2415 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2416 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002417 case BuiltinType::UShort:
2418 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2419 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002420 case BuiltinType::Short:
2421 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2422 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002423 case BuiltinType::UInt:
2424 case BuiltinType::ULong:
2425 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2426 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002427 case BuiltinType::Int:
2428 case BuiltinType::Long:
2429 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2430 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002431 case BuiltinType::Float:
2432 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2433 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002434 }
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002435}
2436
Chris Lattner7f02f722007-08-24 05:35:26 +00002437Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2438 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002439 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002440 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002441 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002442 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002443 assert(E->getOpcode() == BO_EQ ||
2444 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002445 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2446 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002447 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002448 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002449 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002450 Value *LHS = Visit(E->getLHS());
2451 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002452
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002453 // If AltiVec, the comparison results in a numeric type, so we use
2454 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002455 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002456 // constants for mapping CR6 register bits to predicate result
2457 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2458
2459 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2460
2461 // in several cases vector arguments order will be reversed
2462 Value *FirstVecArg = LHS,
2463 *SecondVecArg = RHS;
2464
2465 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002466 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002467 BuiltinType::Kind ElementKind = BTy->getKind();
2468
2469 switch(E->getOpcode()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002470 default: llvm_unreachable("is not a comparison operation");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002471 case BO_EQ:
2472 CR6 = CR6_LT;
2473 ID = GetIntrinsic(VCMPEQ, ElementKind);
2474 break;
2475 case BO_NE:
2476 CR6 = CR6_EQ;
2477 ID = GetIntrinsic(VCMPEQ, ElementKind);
2478 break;
2479 case BO_LT:
2480 CR6 = CR6_LT;
2481 ID = GetIntrinsic(VCMPGT, ElementKind);
2482 std::swap(FirstVecArg, SecondVecArg);
2483 break;
2484 case BO_GT:
2485 CR6 = CR6_LT;
2486 ID = GetIntrinsic(VCMPGT, ElementKind);
2487 break;
2488 case BO_LE:
2489 if (ElementKind == BuiltinType::Float) {
2490 CR6 = CR6_LT;
2491 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2492 std::swap(FirstVecArg, SecondVecArg);
2493 }
2494 else {
2495 CR6 = CR6_EQ;
2496 ID = GetIntrinsic(VCMPGT, ElementKind);
2497 }
2498 break;
2499 case BO_GE:
2500 if (ElementKind == BuiltinType::Float) {
2501 CR6 = CR6_LT;
2502 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2503 }
2504 else {
2505 CR6 = CR6_EQ;
2506 ID = GetIntrinsic(VCMPGT, ElementKind);
2507 std::swap(FirstVecArg, SecondVecArg);
2508 }
2509 break;
2510 }
2511
Chris Lattner48431f92011-04-19 22:55:03 +00002512 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002513 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2514 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2515 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2516 }
2517
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002518 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002519 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002520 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002521 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002522 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002523 LHS, RHS, "cmp");
2524 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002525 // Unsigned integers and pointers.
2526 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002527 LHS, RHS, "cmp");
2528 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002529
2530 // If this is a vector comparison, sign extend the result to the appropriate
2531 // vector integer type and return it (don't convert to bool).
2532 if (LHSTy->isVectorType())
2533 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002534
Chris Lattner7f02f722007-08-24 05:35:26 +00002535 } else {
2536 // Complex Comparison: can only be an equality comparison.
2537 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2538 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002539
John McCall183700f2009-09-21 23:43:11 +00002540 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002541
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002542 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002543 if (CETy->isRealFloatingType()) {
2544 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2545 LHS.first, RHS.first, "cmp.r");
2546 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2547 LHS.second, RHS.second, "cmp.i");
2548 } else {
2549 // Complex comparisons can only be equality comparisons. As such, signed
2550 // and unsigned opcodes are the same.
2551 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2552 LHS.first, RHS.first, "cmp.r");
2553 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2554 LHS.second, RHS.second, "cmp.i");
2555 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002556
John McCall2de56d12010-08-25 11:45:40 +00002557 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002558 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2559 } else {
John McCall2de56d12010-08-25 11:45:40 +00002560 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002561 "Complex comparison other than == or != ?");
2562 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2563 }
2564 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002565
2566 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002567}
2568
2569Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002570 bool Ignore = TestAndClearIgnoreResultAssign();
2571
John McCallf85e1932011-06-15 23:02:42 +00002572 Value *RHS;
2573 LValue LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002574
John McCallf85e1932011-06-15 23:02:42 +00002575 switch (E->getLHS()->getType().getObjCLifetime()) {
2576 case Qualifiers::OCL_Strong:
2577 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2578 break;
2579
2580 case Qualifiers::OCL_Autoreleasing:
2581 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2582 break;
2583
2584 case Qualifiers::OCL_Weak:
2585 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002586 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002587 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2588 break;
2589
2590 // No reason to do any of these differently.
2591 case Qualifiers::OCL_None:
2592 case Qualifiers::OCL_ExplicitNone:
2593 // __block variables need to have the rhs evaluated first, plus
2594 // this should improve codegen just a little.
2595 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002596 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002597
2598 // Store the value into the LHS. Bit-fields are handled specially
2599 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2600 // 'An assignment expression has the value of the left operand after
2601 // the assignment...'.
2602 if (LHS.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002603 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCallf85e1932011-06-15 23:02:42 +00002604 else
John McCall545d9962011-06-25 02:11:03 +00002605 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCallf85e1932011-06-15 23:02:42 +00002606 }
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002607
2608 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002609 if (Ignore)
2610 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002611
John McCallb418d742010-11-16 10:08:07 +00002612 // The result of an assignment in C is the assigned r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002613 if (!CGF.getContext().getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00002614 return RHS;
2615
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002616 // If the lvalue is non-volatile, return the computed value of the assignment.
2617 if (!LHS.isVolatileQualified())
2618 return RHS;
2619
2620 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00002621 return EmitLoadOfLValue(LHS);
Chris Lattner7f02f722007-08-24 05:35:26 +00002622}
2623
2624Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002625
2626 // Perform vector logical and on comparisons with zero vectors.
2627 if (E->getType()->isVectorType()) {
2628 Value *LHS = Visit(E->getLHS());
2629 Value *RHS = Visit(E->getRHS());
2630 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2631 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2632 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2633 Value *And = Builder.CreateAnd(LHS, RHS);
2634 return Builder.CreateSExt(And, Zero->getType(), "sext");
2635 }
2636
Chris Lattner2acc6e32011-07-18 04:24:23 +00002637 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002638
Chris Lattner20eb09d2008-11-12 08:26:50 +00002639 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2640 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002641 bool LHSCondVal;
2642 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2643 if (LHSCondVal) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002644 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002645 // ZExt result to int or bool.
2646 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002647 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002648
Chris Lattner7804bcb2009-10-17 04:24:20 +00002649 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002650 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002651 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002652 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002653
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002654 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2655 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002656
John McCall150b4622011-01-26 04:00:11 +00002657 CodeGenFunction::ConditionalEvaluation eval(CGF);
2658
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002659 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2660 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2661
2662 // Any edges into the ContBlock are now from an (indeterminate number of)
2663 // edges from this first condition. All of these values will be false. Start
2664 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002665 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002666 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002667 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2668 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002669 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002670
John McCall150b4622011-01-26 04:00:11 +00002671 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002672 CGF.EmitBlock(RHSBlock);
2673 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002674 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002675
Chris Lattner7f02f722007-08-24 05:35:26 +00002676 // Reaquire the RHS block, as there may be subblocks inserted.
2677 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002678
2679 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2680 // into the phi node for the edge with the value of RHSCond.
Devang Patelacd72362011-03-30 00:08:31 +00002681 if (CGF.getDebugInfo())
2682 // There is no need to emit line number for unconditional branch.
2683 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Chris Lattner7f02f722007-08-24 05:35:26 +00002684 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002685 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002686
Chris Lattner7f02f722007-08-24 05:35:26 +00002687 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002688 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002689}
2690
2691Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002692
2693 // Perform vector logical or on comparisons with zero vectors.
2694 if (E->getType()->isVectorType()) {
2695 Value *LHS = Visit(E->getLHS());
2696 Value *RHS = Visit(E->getRHS());
2697 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2698 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2699 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2700 Value *Or = Builder.CreateOr(LHS, RHS);
2701 return Builder.CreateSExt(Or, Zero->getType(), "sext");
2702 }
2703
Chris Lattner2acc6e32011-07-18 04:24:23 +00002704 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002705
Chris Lattner20eb09d2008-11-12 08:26:50 +00002706 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2707 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002708 bool LHSCondVal;
2709 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2710 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002711 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002712 // ZExt result to int or bool.
2713 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002714 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002715
Chris Lattner7804bcb2009-10-17 04:24:20 +00002716 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002717 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002718 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002719 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002720
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002721 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2722 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002723
John McCall150b4622011-01-26 04:00:11 +00002724 CodeGenFunction::ConditionalEvaluation eval(CGF);
2725
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002726 // Branch on the LHS first. If it is true, go to the success (cont) block.
2727 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2728
2729 // Any edges into the ContBlock are now from an (indeterminate number of)
2730 // edges from this first condition. All of these values will be true. Start
2731 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002732 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002733 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002734 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2735 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002736 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002737
John McCall150b4622011-01-26 04:00:11 +00002738 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002739
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002740 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002741 CGF.EmitBlock(RHSBlock);
2742 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002743
John McCall150b4622011-01-26 04:00:11 +00002744 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002745
Chris Lattner7f02f722007-08-24 05:35:26 +00002746 // Reaquire the RHS block, as there may be subblocks inserted.
2747 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002748
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002749 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2750 // into the phi node for the edge with the value of RHSCond.
2751 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002752 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002753
Chris Lattner7f02f722007-08-24 05:35:26 +00002754 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002755 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002756}
2757
2758Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002759 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002760 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002761 return Visit(E->getRHS());
2762}
2763
2764//===----------------------------------------------------------------------===//
2765// Other Operators
2766//===----------------------------------------------------------------------===//
2767
Chris Lattner9802a512008-11-12 08:55:54 +00002768/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2769/// expression is cheap enough and side-effect-free enough to evaluate
2770/// unconditionally instead of conditionally. This is used to convert control
2771/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002772static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2773 CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002774 E = E->IgnoreParens();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002775
Chris Lattnerc6bea672011-04-16 23:15:35 +00002776 // Anything that is an integer or floating point constant is fine.
2777 if (E->isConstantInitializer(CGF.getContext(), false))
Chris Lattner9802a512008-11-12 08:55:54 +00002778 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002779
Chris Lattner9802a512008-11-12 08:55:54 +00002780 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2781 // X and Y are local variables.
2782 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2783 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002784 if (VD->hasLocalStorage() && !(CGF.getContext()
2785 .getCanonicalType(VD->getType())
2786 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002787 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002788
Chris Lattner9802a512008-11-12 08:55:54 +00002789 return false;
2790}
2791
2792
Chris Lattner7f02f722007-08-24 05:35:26 +00002793Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00002794VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002795 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00002796
2797 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +00002798 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCall56ca35d2011-02-17 10:25:35 +00002799
2800 Expr *condExpr = E->getCond();
2801 Expr *lhsExpr = E->getTrueExpr();
2802 Expr *rhsExpr = E->getFalseExpr();
2803
Chris Lattner31a09842008-11-12 08:04:58 +00002804 // If the condition constant folds and can be elided, try to avoid emitting
2805 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002806 bool CondExprBool;
2807 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00002808 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00002809 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002810
Eli Friedmanc8645e32011-10-15 02:10:40 +00002811 // If the dead side doesn't have labels we need, just emit the Live part.
2812 if (!CGF.ContainsLabel(dead)) {
2813 Value *Result = Visit(live);
2814
2815 // If the live part is a throw expression, it acts like it has a void
2816 // type, so evaluating it returns a null Value*. However, a conditional
2817 // with non-void type must return a non-null Value*.
2818 if (!Result && !E->getType()->isVoidType())
2819 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
2820
2821 return Result;
2822 }
Chris Lattnerc657e922008-11-11 18:56:45 +00002823 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002824
Nate Begeman6155d732010-09-20 22:41:17 +00002825 // OpenCL: If the condition is a vector, we can treat this condition like
2826 // the select function.
David Blaikie4e4d0842012-03-11 07:00:24 +00002827 if (CGF.getContext().getLangOpts().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00002828 && condExpr->getType()->isVectorType()) {
2829 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2830 llvm::Value *LHS = Visit(lhsExpr);
2831 llvm::Value *RHS = Visit(rhsExpr);
Nate Begeman6155d732010-09-20 22:41:17 +00002832
Chris Lattner2acc6e32011-07-18 04:24:23 +00002833 llvm::Type *condType = ConvertType(condExpr->getType());
2834 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Nate Begeman6155d732010-09-20 22:41:17 +00002835
2836 unsigned numElem = vecTy->getNumElements();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002837 llvm::Type *elemType = vecTy->getElementType();
Nate Begeman6155d732010-09-20 22:41:17 +00002838
Chris Lattner2ce88422012-01-25 05:34:41 +00002839 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begeman6155d732010-09-20 22:41:17 +00002840 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2841 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2842 llvm::VectorType::get(elemType,
2843 numElem),
2844 "sext");
2845 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2846
2847 // Cast float to int to perform ANDs if necessary.
2848 llvm::Value *RHSTmp = RHS;
2849 llvm::Value *LHSTmp = LHS;
2850 bool wasCast = false;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002851 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourne565204d2012-05-29 00:35:18 +00002852 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begeman6155d732010-09-20 22:41:17 +00002853 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2854 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2855 wasCast = true;
2856 }
2857
2858 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2859 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2860 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2861 if (wasCast)
2862 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2863
2864 return tmp5;
2865 }
2866
Chris Lattner9802a512008-11-12 08:55:54 +00002867 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2868 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002869 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00002870 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2871 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2872 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2873 llvm::Value *LHS = Visit(lhsExpr);
2874 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman1e4f68c2011-12-08 22:01:56 +00002875 if (!LHS) {
2876 // If the conditional has void type, make sure we return a null Value*.
2877 assert(!RHS && "LHS and RHS types must match");
2878 return 0;
2879 }
Chris Lattner9802a512008-11-12 08:55:54 +00002880 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2881 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002882
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002883 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2884 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002885 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002886
2887 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002888 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002889
Chris Lattner7f02f722007-08-24 05:35:26 +00002890 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002891 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002892 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002893 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002894
Chris Lattner7f02f722007-08-24 05:35:26 +00002895 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002896 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002897
Chris Lattner7f02f722007-08-24 05:35:26 +00002898 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002899 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002900 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002901 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002902
John McCall150b4622011-01-26 04:00:11 +00002903 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002904 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002905
Eli Friedman48daf592009-12-07 20:25:53 +00002906 // If the LHS or RHS is a throw expression, it will be legitimately null.
2907 if (!LHS)
2908 return RHS;
2909 if (!RHS)
2910 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002911
Chris Lattner7f02f722007-08-24 05:35:26 +00002912 // Create a PHI node for the real part.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002913 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner7f02f722007-08-24 05:35:26 +00002914 PN->addIncoming(LHS, LHSBlock);
2915 PN->addIncoming(RHS, RHSBlock);
2916 return PN;
2917}
2918
2919Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002920 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002921}
2922
Chris Lattner2202bce2007-11-30 17:56:23 +00002923Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002924 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002925 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2926
2927 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002928 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002929 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2930
Mike Stump7f79f9b2009-05-29 15:46:01 +00002931 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002932 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002933}
2934
John McCall6b5a61b2011-02-07 10:33:21 +00002935Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2936 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002937}
2938
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002939Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2940 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2acc6e32011-07-18 04:24:23 +00002941 llvm::Type *DstTy = ConvertType(E->getType());
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002942
2943 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2944 // a shuffle vector instead of a bitcast.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002945 llvm::Type *SrcTy = Src->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002946 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2947 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2948 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2949 if ((numElementsDst == 3 && numElementsSrc == 4)
2950 || (numElementsDst == 4 && numElementsSrc == 3)) {
2951
2952
2953 // In the case of going from int4->float3, a bitcast is needed before
2954 // doing a shuffle.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002955 llvm::Type *srcElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002956 cast<llvm::VectorType>(SrcTy)->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002957 llvm::Type *dstElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002958 cast<llvm::VectorType>(DstTy)->getElementType();
2959
2960 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2961 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2962 // Create a float type of the same size as the source or destination.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002963 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002964 numElementsSrc);
2965
2966 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2967 }
2968
2969 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2970
Chris Lattner5f9e2722011-07-23 10:55:15 +00002971 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002972 Args.push_back(Builder.getInt32(0));
2973 Args.push_back(Builder.getInt32(1));
2974 Args.push_back(Builder.getInt32(2));
2975
2976 if (numElementsDst == 4)
Chris Lattner8b418682012-02-07 00:39:47 +00002977 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002978
2979 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2980
2981 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2982 }
2983 }
2984
2985 return Builder.CreateBitCast(Src, DstTy, "astype");
2986}
2987
Eli Friedman276b0612011-10-11 02:20:01 +00002988Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
2989 return CGF.EmitAtomicExpr(E).getScalarVal();
2990}
2991
Chris Lattner7f02f722007-08-24 05:35:26 +00002992//===----------------------------------------------------------------------===//
2993// Entry Point into this File
2994//===----------------------------------------------------------------------===//
2995
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002996/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2997/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002998Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002999 assert(E && !hasAggregateLLVMType(E->getType()) &&
3000 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003001
Devang Patel5de7a0e2011-03-07 18:29:53 +00003002 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00003003 disableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00003004 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stump7f79f9b2009-05-29 15:46:01 +00003005 .Visit(const_cast<Expr*>(E));
Devang Patel5de7a0e2011-03-07 18:29:53 +00003006 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00003007 enableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00003008 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +00003009}
Chris Lattner3707b252007-08-26 06:48:56 +00003010
3011/// EmitScalarConversion - Emit a conversion from the specified type to the
3012/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003013Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3014 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00003015 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
3016 "Invalid scalar expression to emit");
3017 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
3018}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003019
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003020/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
3021/// type to the specified destination type, where the destination type is an
3022/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003023Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3024 QualType SrcTy,
3025 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00003026 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003027 "Invalid complex -> scalar conversion");
3028 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
3029 DstTy);
3030}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00003031
Chris Lattner8c11a652010-06-26 22:09:34 +00003032
3033llvm::Value *CodeGenFunction::
3034EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3035 bool isInc, bool isPre) {
3036 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3037}
3038
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003039LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3040 llvm::Value *V;
3041 // object->isa or (*object).isa
3042 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003043 // build Class* type
Chris Lattner2acc6e32011-07-18 04:24:23 +00003044 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003045
3046 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00003047 if (BaseExpr->isRValue()) {
Eli Friedmand71f4422011-12-19 23:03:09 +00003048 V = CreateMemTemp(E->getType(), "resval");
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003049 llvm::Value *Src = EmitScalarExpr(BaseExpr);
3050 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00003051 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
Eli Friedmand71f4422011-12-19 23:03:09 +00003052 MakeNaturalAlignAddrLValue(V, E->getType()));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00003053 } else {
3054 if (E->isArrow())
3055 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
3056 else
3057 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003058 }
3059
3060 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003061 ClassPtrTy = ClassPtrTy->getPointerTo();
3062 V = Builder.CreateBitCast(V, ClassPtrTy);
Eli Friedmand71f4422011-12-19 23:03:09 +00003063 return MakeNaturalAlignAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003064}
3065
Douglas Gregor6a03e342010-04-23 04:16:32 +00003066
John McCall2a416372010-12-05 02:00:02 +00003067LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00003068 const CompoundAssignOperator *E) {
3069 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00003070 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00003071 switch (E->getOpcode()) {
3072#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00003073 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00003074 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00003075 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00003076 COMPOUND_OP(Mul);
3077 COMPOUND_OP(Div);
3078 COMPOUND_OP(Rem);
3079 COMPOUND_OP(Add);
3080 COMPOUND_OP(Sub);
3081 COMPOUND_OP(Shl);
3082 COMPOUND_OP(Shr);
3083 COMPOUND_OP(And);
3084 COMPOUND_OP(Xor);
3085 COMPOUND_OP(Or);
3086#undef COMPOUND_OP
3087
John McCall2de56d12010-08-25 11:45:40 +00003088 case BO_PtrMemD:
3089 case BO_PtrMemI:
3090 case BO_Mul:
3091 case BO_Div:
3092 case BO_Rem:
3093 case BO_Add:
3094 case BO_Sub:
3095 case BO_Shl:
3096 case BO_Shr:
3097 case BO_LT:
3098 case BO_GT:
3099 case BO_LE:
3100 case BO_GE:
3101 case BO_EQ:
3102 case BO_NE:
3103 case BO_And:
3104 case BO_Xor:
3105 case BO_Or:
3106 case BO_LAnd:
3107 case BO_LOr:
3108 case BO_Assign:
3109 case BO_Comma:
David Blaikieb219cfc2011-09-23 05:06:16 +00003110 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor6a03e342010-04-23 04:16:32 +00003111 }
3112
3113 llvm_unreachable("Unhandled compound assignment operator");
3114}