blob: a6ba79803d44b42f8731a8f4867188621ba04737 [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"
Mike Stump4e7a1f72009-02-21 20:00:35 +000031#include "llvm/Target/TargetData.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
48 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner7f02f722007-08-24 05:35:26 +000049};
50
John McCall404cd162010-11-13 01:35:44 +000051static bool MustVisitNullValue(const Expr *E) {
52 // If a null pointer expression's type is the C++0x nullptr_t, then
53 // it's not necessarily a simple constant and it must be evaluated
54 // for its potential side effects.
55 return E->getType()->isNullPtrType();
56}
57
Benjamin Kramer85b45212009-11-28 19:45:26 +000058class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000059 : public StmtVisitor<ScalarExprEmitter, Value*> {
60 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000061 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000062 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000063 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000064public:
65
Mike Stump7f79f9b2009-05-29 15:46:01 +000066 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000067 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000068 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000069 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000070
Chris Lattner7f02f722007-08-24 05:35:26 +000071 //===--------------------------------------------------------------------===//
72 // Utilities
73 //===--------------------------------------------------------------------===//
74
Mike Stump7f79f9b2009-05-29 15:46:01 +000075 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000076 bool I = IgnoreResultAssign;
77 IgnoreResultAssign = false;
78 return I;
79 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000080
Chris Lattner2acc6e32011-07-18 04:24:23 +000081 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner7f02f722007-08-24 05:35:26 +000082 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Mike Stumpb14e62d2009-12-16 02:57:00 +000083 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
Chris Lattner7f02f722007-08-24 05:35:26 +000084
John McCall545d9962011-06-25 02:11:03 +000085 Value *EmitLoadOfLValue(LValue LV) {
86 return CGF.EmitLoadOfLValue(LV).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000087 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000088
Chris Lattner7f02f722007-08-24 05:35:26 +000089 /// EmitLoadOfLValue - Given an expression with complex type that represents a
90 /// value l-value, this method emits the address of the l-value, then loads
91 /// and returns the result.
92 Value *EmitLoadOfLValue(const Expr *E) {
John McCall545d9962011-06-25 02:11:03 +000093 return EmitLoadOfLValue(EmitCheckedLValue(E));
Chris Lattner7f02f722007-08-24 05:35:26 +000094 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000095
Chris Lattner9abc84e2007-08-26 16:42:57 +000096 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000097 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000098 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +000099
Chris Lattner3707b252007-08-26 06:48:56 +0000100 /// EmitScalarConversion - Emit a conversion from the specified type to the
101 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000102 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
103
104 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000105 /// complex type to the specified destination type, where the destination type
106 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000107 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
108 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000109
Anders Carlssona40a9f32010-05-22 17:45:10 +0000110 /// EmitNullValue - Emit a value that corresponds to null for the given type.
111 Value *EmitNullValue(QualType Ty);
112
John McCalldaa8e4e2010-11-15 09:13:47 +0000113 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
114 Value *EmitFloatToBoolConversion(Value *V) {
115 // Compare against 0.0 for fp scalars.
116 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
117 return Builder.CreateFCmpUNE(V, Zero, "tobool");
118 }
119
120 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
121 Value *EmitPointerToBoolConversion(Value *V) {
122 Value *Zero = llvm::ConstantPointerNull::get(
123 cast<llvm::PointerType>(V->getType()));
124 return Builder.CreateICmpNE(V, Zero, "tobool");
125 }
126
127 Value *EmitIntToBoolConversion(Value *V) {
128 // Because of the type rules of C, we often end up computing a
129 // logical value, then zero extending it to int, then wanting it
130 // as a logical value again. Optimize this common case.
131 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
132 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
133 Value *Result = ZI->getOperand(0);
134 // If there aren't any more uses, zap the instruction to save space.
135 // Note that there can be more uses, for example if this
136 // is the result of an assignment.
137 if (ZI->use_empty())
138 ZI->eraseFromParent();
139 return Result;
140 }
141 }
142
Chris Lattner48431f92011-04-19 22:55:03 +0000143 return Builder.CreateIsNotNull(V, "tobool");
John McCalldaa8e4e2010-11-15 09:13:47 +0000144 }
145
Chris Lattner7f02f722007-08-24 05:35:26 +0000146 //===--------------------------------------------------------------------===//
147 // Visitor Methods
148 //===--------------------------------------------------------------------===//
149
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000150 Value *Visit(Expr *E) {
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000151 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
152 }
153
Chris Lattner7f02f722007-08-24 05:35:26 +0000154 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000155 S->dump(CGF.getContext().getSourceManager());
David Blaikieb219cfc2011-09-23 05:06:16 +0000156 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner7f02f722007-08-24 05:35:26 +0000157 }
158 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000159
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000160 Value *VisitParenExpr(ParenExpr *PE) {
161 return Visit(PE->getSubExpr());
162 }
John McCall91a57552011-07-15 05:09:51 +0000163 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
164 return Visit(E->getReplacement());
165 }
Peter Collingbournef111d932011-04-15 00:35:48 +0000166 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
167 return Visit(GE->getResultExpr());
168 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000169
170 // Leaves.
171 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000172 return Builder.getInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000173 }
174 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000175 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000176 }
177 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000178 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000179 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000180 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
181 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
182 }
Nate Begemane7579b52007-11-15 05:40:03 +0000183 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000184 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000185 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000186 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000187 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000188 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000189 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000190 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000191 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000192 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000193 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000194 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000195 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
196 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000197 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000198
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000199 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000200 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000201 }
John McCalle996ffd2011-02-16 08:02:54 +0000202
John McCall4b9c2d22011-11-06 09:01:30 +0000203 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
204 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
205 }
206
John McCalle996ffd2011-02-16 08:02:54 +0000207 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000208 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +0000209 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
John McCalle996ffd2011-02-16 08:02:54 +0000210
211 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000212 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000213 }
John McCalldd2ecee2012-03-10 03:05:10 +0000214
Chris Lattner7f02f722007-08-24 05:35:26 +0000215 // l-values.
John McCalldd2ecee2012-03-10 03:05:10 +0000216 Value *emitDeclRef(ValueDecl *VD, Expr *refExpr) {
217 if (CodeGenFunction::ConstantEmission result
218 = CGF.tryEmitAsConstant(VD, refExpr)) {
219 if (result.isReference())
220 return EmitLoadOfLValue(result.getReferenceLValue(CGF, refExpr));
221 return result.getValue();
Richard Smitha3ca41f2012-03-02 23:27:11 +0000222 }
John McCalldd2ecee2012-03-10 03:05:10 +0000223 return EmitLoadOfLValue(refExpr);
Chris Lattner7f02f722007-08-24 05:35:26 +0000224 }
John McCalldd2ecee2012-03-10 03:05:10 +0000225 Value *VisitDeclRefExpr(DeclRefExpr *E) {
226 return emitDeclRef(E->getDecl(), E);
227 }
228 Value *VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
229 return emitDeclRef(E->getDecl(), E);
230 }
231
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000232 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
233 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000234 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000235 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
236 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000237 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000238 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000239 return EmitLoadOfLValue(E);
240 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000241 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000242 if (E->getMethodDecl() &&
243 E->getMethodDecl()->getResultType()->isReferenceType())
244 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000245 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000246 }
247
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000248 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000249 LValue LV = CGF.EmitObjCIsaExpr(E);
John McCall545d9962011-06-25 02:11:03 +0000250 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000251 return V;
252 }
253
Chris Lattner7f02f722007-08-24 05:35:26 +0000254 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000255 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000256 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000257 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000258 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
259 return EmitLoadOfLValue(E);
260 }
Devang Patel35634f52007-10-24 17:18:43 +0000261
Nate Begeman0533b302009-10-18 20:10:40 +0000262 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000263
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000264 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000265 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000266 }
John McCallbc8d40d2011-06-24 21:55:10 +0000267 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000268 if (E->getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000269 CGF.EmitVariablyModifiedType(E->getType());
270 return VisitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000271 }
John McCallbc8d40d2011-06-24 21:55:10 +0000272 Value *VisitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000273
274 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000275 if (E->getCallReturnType()->isReferenceType())
276 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000277
Chris Lattner9b655512007-08-31 22:49:20 +0000278 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000279 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000280
Chris Lattner33793202007-08-31 22:09:40 +0000281 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000282
Chris Lattner7f02f722007-08-24 05:35:26 +0000283 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000284 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000285 LValue LV = EmitLValue(E->getSubExpr());
286 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000287 }
288 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000289 LValue LV = EmitLValue(E->getSubExpr());
290 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000291 }
292 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000293 LValue LV = EmitLValue(E->getSubExpr());
294 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000295 }
296 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000297 LValue LV = EmitLValue(E->getSubExpr());
298 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000299 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000300
Anton Yartsev683564a2011-02-07 02:17:30 +0000301 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
302 llvm::Value *InVal,
303 llvm::Value *NextVal,
304 bool IsInc);
305
Chris Lattner8c11a652010-06-26 22:09:34 +0000306 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
307 bool isInc, bool isPre);
308
309
Chris Lattner7f02f722007-08-24 05:35:26 +0000310 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000311 if (isa<MemberPointerType>(E->getType())) // never sugared
312 return CGF.CGM.getMemberPointerConstant(E);
313
Chris Lattner7f02f722007-08-24 05:35:26 +0000314 return EmitLValue(E->getSubExpr()).getAddress();
315 }
John McCallfd569002010-12-04 12:43:24 +0000316 Value *VisitUnaryDeref(const UnaryOperator *E) {
317 if (E->getType()->isVoidType())
318 return Visit(E->getSubExpr()); // the actual value should be unused
319 return EmitLoadOfLValue(E);
320 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000321 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000322 // This differs from gcc, though, most likely due to a bug in gcc.
323 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000324 return Visit(E->getSubExpr());
325 }
326 Value *VisitUnaryMinus (const UnaryOperator *E);
327 Value *VisitUnaryNot (const UnaryOperator *E);
328 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000329 Value *VisitUnaryReal (const UnaryOperator *E);
330 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000331 Value *VisitUnaryExtension(const UnaryOperator *E) {
332 return Visit(E->getSubExpr());
333 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000334
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000335 // C++
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000336 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedmanec24b0e2011-08-14 04:50:34 +0000337 return EmitLoadOfLValue(E);
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000338 }
339
Chris Lattner04421082008-04-08 04:40:51 +0000340 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
341 return Visit(DAE->getExpr());
342 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000343 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
344 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000345 }
346
John McCall4765fa02010-12-06 08:20:24 +0000347 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +0000348 CGF.enterFullExpression(E);
349 CodeGenFunction::RunCleanupsScope Scope(CGF);
350 return Visit(E->getSubExpr());
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000351 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000352 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
353 return CGF.EmitCXXNewExpr(E);
354 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000355 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
356 CGF.EmitCXXDeleteExpr(E);
357 return 0;
358 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000359 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000360 return Builder.getInt1(E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000361 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000362
Francois Pichet6ad6f282010-12-07 00:08:36 +0000363 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000364 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000365 }
366
John Wiegley21ff2e52011-04-28 00:16:57 +0000367 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
368 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
369 }
370
John Wiegley55262202011-04-25 06:54:41 +0000371 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
372 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
373 }
374
Douglas Gregora71d8192009-09-04 17:36:40 +0000375 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
376 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000377 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000378 // operator (), and the result of such a call has type void. The only
379 // effect is the evaluation of the postfix-expression before the dot or
380 // arrow.
381 CGF.EmitScalarExpr(E->getBase());
382 return 0;
383 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000384
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000385 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000386 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000387 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000388
389 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
390 CGF.EmitCXXThrowExpr(E);
391 return 0;
392 }
393
Sebastian Redl98294de2010-09-10 21:04:00 +0000394 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000395 return Builder.getInt1(E->getValue());
Sebastian Redl98294de2010-09-10 21:04:00 +0000396 }
397
Chris Lattner7f02f722007-08-24 05:35:26 +0000398 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000399 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000400 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000401 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
402 case LangOptions::SOB_Undefined:
403 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
404 case LangOptions::SOB_Defined:
405 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
406 case LangOptions::SOB_Trapping:
407 return EmitOverflowCheckedBinOp(Ops);
408 }
409 }
410
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000411 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000412 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000413 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
414 }
Chris Lattner80230302010-09-11 21:47:09 +0000415 bool isTrapvOverflowBehavior() {
416 return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
417 == LangOptions::SOB_Trapping;
418 }
Mike Stump2add4732009-04-01 20:28:16 +0000419 /// Create a binary op that checks for overflow.
420 /// Currently only supports +, - and *.
421 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner80230302010-09-11 21:47:09 +0000422 // Emit the overflow BB when -ftrapv option is activated.
423 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
424 Builder.SetInsertPoint(overflowBB);
425 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
426 Builder.CreateCall(Trap);
427 Builder.CreateUnreachable();
428 }
429 // 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 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000508 Value *VisitObjCNumericLiteral(ObjCNumericLiteral *E) {
509 return CGF.EmitObjCNumericLiteral(E);
510 }
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
Chris Lattner3707b252007-08-26 06:48:56 +0000547/// EmitScalarConversion - Emit a conversion from the specified type to the
548/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000549Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
550 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000551 SrcType = CGF.getContext().getCanonicalType(SrcType);
552 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000553 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000554
Chris Lattnercf289082007-08-26 07:21:11 +0000555 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000556
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000557 llvm::Type *SrcTy = Src->getType();
558
559 // Floating casts might be a bit special: if we're doing casts to / from half
560 // FP, we should go via special intrinsics.
561 if (SrcType->isHalfType()) {
562 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
563 SrcType = CGF.getContext().FloatTy;
Chris Lattner8b418682012-02-07 00:39:47 +0000564 SrcTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000565 }
566
Chris Lattner3707b252007-08-26 06:48:56 +0000567 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000568 if (DstType->isBooleanType())
569 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000570
Chris Lattner2acc6e32011-07-18 04:24:23 +0000571 llvm::Type *DstTy = ConvertType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000572
573 // Ignore conversions like int -> uint.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000574 if (SrcTy == DstTy)
Chris Lattner3707b252007-08-26 06:48:56 +0000575 return Src;
576
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000577 // Handle pointer conversions next: pointers can only be converted to/from
578 // other pointers and integers. Check for pointer types in terms of LLVM, as
579 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000580 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000581 // The source value may be an integer, or a pointer.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000582 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3707b252007-08-26 06:48:56 +0000583 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000584
Chris Lattner3707b252007-08-26 06:48:56 +0000585 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000586 // First, convert to the correct width so that we control the kind of
587 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000588 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000589 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman25615422009-03-04 04:02:35 +0000590 llvm::Value* IntResult =
591 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
592 // Then, cast to pointer.
593 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000594 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000595
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000596 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000597 // Must be an ptr to int cast.
598 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000599 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000600 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000601
Nate Begeman213541a2008-04-18 23:10:10 +0000602 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000603 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000604 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000605 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000606 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
607
608 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000609 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +0000610 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +0000611 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000612
613 // Splat the element across to all elements
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000614 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner2ce88422012-01-25 05:34:41 +0000615 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements,
616 Builder.getInt32(0));
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000617 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
618 return Yay;
619 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000620
Chris Lattner3b1ae002008-02-02 04:51:41 +0000621 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000622 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000623 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000624 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000625
Chris Lattner3707b252007-08-26 06:48:56 +0000626 // Finally, we have the arithmetic types: real int/float.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000627 Value *Res = NULL;
628 llvm::Type *ResTy = DstTy;
629
630 // Cast to half via float
631 if (DstType->isHalfType())
Chris Lattner8b418682012-02-07 00:39:47 +0000632 DstTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000633
634 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000635 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000636 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000637 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000638 else if (InputSigned)
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000639 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000640 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000641 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
642 } else if (isa<llvm::IntegerType>(DstTy)) {
643 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor575a1c92011-05-20 16:38:50 +0000644 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000645 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000646 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000647 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
648 } else {
649 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
650 "Unknown real conversion");
651 if (DstTy->getTypeID() < SrcTy->getTypeID())
652 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
653 else
654 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000655 }
656
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000657 if (DstTy != ResTy) {
658 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
659 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
660 }
661
662 return Res;
Chris Lattner3707b252007-08-26 06:48:56 +0000663}
664
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000665/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
666/// type to the specified destination type, where the destination type is an
667/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000668Value *ScalarExprEmitter::
669EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
670 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000671 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000672 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000673
Chris Lattnered70f0a2007-08-26 16:52:28 +0000674 // Handle conversions to bool first, they are special: comparisons against 0.
675 if (DstTy->isBooleanType()) {
676 // Complex != 0 -> (Real != 0) | (Imag != 0)
677 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
678 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
679 return Builder.CreateOr(Src.first, Src.second, "tobool");
680 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000681
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000682 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
683 // the imaginary part of the complex value is discarded and the value of the
684 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000685 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000686 return EmitScalarConversion(Src.first, SrcTy, DstTy);
687}
688
Anders Carlssona40a9f32010-05-22 17:45:10 +0000689Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000690 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
691 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
692
693 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000694}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000695
Chris Lattner7f02f722007-08-24 05:35:26 +0000696//===----------------------------------------------------------------------===//
697// Visitor Methods
698//===----------------------------------------------------------------------===//
699
700Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000701 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000702 if (E->getType()->isVoidType())
703 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000704 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000705}
706
Eli Friedmand38617c2008-05-14 19:38:39 +0000707Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000708 // Vector Mask Case
709 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000710 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000711 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
712 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
713 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000714
Chris Lattner2acc6e32011-07-18 04:24:23 +0000715 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000716 unsigned LHSElts = LTy->getNumElements();
717
718 if (E->getNumSubExprs() == 3) {
719 Mask = CGF.EmitScalarExpr(E->getExpr(2));
720
721 // Shuffle LHS & RHS into one input vector.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000722 SmallVector<llvm::Constant*, 32> concat;
Nate Begeman37b6a572010-06-08 00:16:34 +0000723 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000724 concat.push_back(Builder.getInt32(2*i));
725 concat.push_back(Builder.getInt32(2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000726 }
727
Chris Lattnerfb018d12011-02-15 00:14:06 +0000728 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000729 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
730 LHSElts *= 2;
731 } else {
732 Mask = RHS;
733 }
734
Chris Lattner2acc6e32011-07-18 04:24:23 +0000735 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000736 llvm::Constant* EltMask;
737
738 // Treat vec3 like vec4.
739 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
740 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
741 (1 << llvm::Log2_32(LHSElts+2))-1);
742 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
743 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
744 (1 << llvm::Log2_32(LHSElts+1))-1);
745 else
746 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
747 (1 << llvm::Log2_32(LHSElts))-1);
748
749 // Mask off the high bits of each shuffle index.
Chris Lattner2ce88422012-01-25 05:34:41 +0000750 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
751 EltMask);
Nate Begeman37b6a572010-06-08 00:16:34 +0000752 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
753
754 // newv = undef
755 // mask = mask & maskbits
756 // for each elt
757 // n = extract mask i
758 // x = extract val n
759 // newv = insert newv, x, i
Chris Lattner2acc6e32011-07-18 04:24:23 +0000760 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000761 MTy->getNumElements());
762 Value* NewV = llvm::UndefValue::get(RTy);
763 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000764 Value *Indx = Builder.getInt32(i);
Nate Begeman37b6a572010-06-08 00:16:34 +0000765 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000766 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000767
768 // Handle vec3 special since the index will be off by one for the RHS.
769 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
770 Value *cmpIndx, *newIndx;
Chris Lattner48431f92011-04-19 22:55:03 +0000771 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000772 "cmp_shuf_idx");
Chris Lattner48431f92011-04-19 22:55:03 +0000773 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
Nate Begeman37b6a572010-06-08 00:16:34 +0000774 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
775 }
776 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
777 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
778 }
779 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000780 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000781
Eli Friedmand38617c2008-05-14 19:38:39 +0000782 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
783 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000784
785 // Handle vec3 special since the index will be off by one for the RHS.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000786 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000787 SmallVector<llvm::Constant*, 32> indices;
Nate Begeman37b6a572010-06-08 00:16:34 +0000788 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
Eli Friedman0eb47fc2011-05-19 00:37:32 +0000789 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
790 if (VTy->getNumElements() == 3 && Idx > 3)
791 Idx -= 1;
792 indices.push_back(Builder.getInt32(Idx));
Nate Begeman37b6a572010-06-08 00:16:34 +0000793 }
794
Chris Lattnerfb018d12011-02-15 00:14:06 +0000795 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000796 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
797}
Eli Friedman28665272009-11-26 03:22:21 +0000798Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Richard Smith80d4b552011-12-28 19:48:30 +0000799 llvm::APSInt Value;
800 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
Eli Friedman28665272009-11-26 03:22:21 +0000801 if (E->isArrow())
802 CGF.EmitScalarExpr(E->getBase());
803 else
804 EmitLValue(E->getBase());
Richard Smith80d4b552011-12-28 19:48:30 +0000805 return Builder.getInt(Value);
Eli Friedman28665272009-11-26 03:22:21 +0000806 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000807
808 // Emit debug info for aggregate now, if it was delayed to reduce
809 // debug info size.
810 CGDebugInfo *DI = CGF.getDebugInfo();
811 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
812 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
813 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000814 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Devang Patel78ba3d42010-10-04 21:46:04 +0000815 DI->getOrCreateRecordType(PTy->getPointeeType(),
816 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000817 }
Eli Friedman28665272009-11-26 03:22:21 +0000818 return EmitLoadOfLValue(E);
819}
Eli Friedmand38617c2008-05-14 19:38:39 +0000820
Chris Lattner7f02f722007-08-24 05:35:26 +0000821Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000822 TestAndClearIgnoreResultAssign();
823
Chris Lattner7f02f722007-08-24 05:35:26 +0000824 // Emit subscript expressions in rvalue context's. For most cases, this just
825 // loads the lvalue formed by the subscript expr. However, we have to be
826 // careful, because the base of a vector subscript is occasionally an rvalue,
827 // so we can't get it as an lvalue.
828 if (!E->getBase()->getType()->isVectorType())
829 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000830
Chris Lattner7f02f722007-08-24 05:35:26 +0000831 // Handle the vector case. The base must be a vector, the index must be an
832 // integer value.
833 Value *Base = Visit(E->getBase());
834 Value *Idx = Visit(E->getIdx());
Douglas Gregor575a1c92011-05-20 16:38:50 +0000835 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000836 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000837 return Builder.CreateExtractElement(Base, Idx, "vecext");
838}
839
Nate Begeman0533b302009-10-18 20:10:40 +0000840static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000841 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman0533b302009-10-18 20:10:40 +0000842 int MV = SVI->getMaskValue(Idx);
843 if (MV == -1)
844 return llvm::UndefValue::get(I32Ty);
845 return llvm::ConstantInt::get(I32Ty, Off+MV);
846}
847
848Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
849 bool Ignore = TestAndClearIgnoreResultAssign();
850 (void)Ignore;
851 assert (Ignore == false && "init list ignored");
852 unsigned NumInitElements = E->getNumInits();
853
854 if (E->hadArrayRangeDesignator())
855 CGF.ErrorUnsupported(E, "GNU array range designator extension");
856
Chris Lattner2acc6e32011-07-18 04:24:23 +0000857 llvm::VectorType *VType =
Nate Begeman0533b302009-10-18 20:10:40 +0000858 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
859
Sebastian Redlcea8d962011-09-24 17:48:14 +0000860 if (!VType) {
861 if (NumInitElements == 0) {
862 // C++11 value-initialization for the scalar.
863 return EmitNullValue(E->getType());
864 }
865 // We have a scalar in braces. Just use the first element.
Nate Begeman0533b302009-10-18 20:10:40 +0000866 return Visit(E->getInit(0));
Sebastian Redlcea8d962011-09-24 17:48:14 +0000867 }
Nate Begeman0533b302009-10-18 20:10:40 +0000868
869 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000870
871 // Loop over initializers collecting the Value for each, and remembering
872 // whether the source was swizzle (ExtVectorElementExpr). This will allow
873 // us to fold the shuffle for the swizzle into the shuffle for the vector
874 // initializer, since LLVM optimizers generally do not want to touch
875 // shuffles.
876 unsigned CurIdx = 0;
877 bool VIsUndefShuffle = false;
878 llvm::Value *V = llvm::UndefValue::get(VType);
879 for (unsigned i = 0; i != NumInitElements; ++i) {
880 Expr *IE = E->getInit(i);
881 Value *Init = Visit(IE);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000882 SmallVector<llvm::Constant*, 16> Args;
Nate Begeman0533b302009-10-18 20:10:40 +0000883
Chris Lattner2acc6e32011-07-18 04:24:23 +0000884 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000885
886 // Handle scalar elements. If the scalar initializer is actually one
887 // element of a different vector of the same width, use shuffle instead of
888 // extract+insert.
889 if (!VVT) {
890 if (isa<ExtVectorElementExpr>(IE)) {
891 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
892
893 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
894 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
895 Value *LHS = 0, *RHS = 0;
896 if (CurIdx == 0) {
897 // insert into undef -> shuffle (src, undef)
898 Args.push_back(C);
Benjamin Kramer14c59822012-02-14 12:06:21 +0000899 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000900
901 LHS = EI->getVectorOperand();
902 RHS = V;
903 VIsUndefShuffle = true;
904 } else if (VIsUndefShuffle) {
905 // insert into undefshuffle && size match -> shuffle (v, src)
906 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
907 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000908 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner48431f92011-04-19 22:55:03 +0000909 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000910 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
911
Nate Begeman0533b302009-10-18 20:10:40 +0000912 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
913 RHS = EI->getVectorOperand();
914 VIsUndefShuffle = false;
915 }
916 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +0000917 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000918 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
919 ++CurIdx;
920 continue;
921 }
922 }
923 }
Chris Lattner48431f92011-04-19 22:55:03 +0000924 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
925 "vecinit");
Nate Begeman0533b302009-10-18 20:10:40 +0000926 VIsUndefShuffle = false;
927 ++CurIdx;
928 continue;
929 }
930
931 unsigned InitElts = VVT->getNumElements();
932
933 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
934 // input is the same width as the vector being constructed, generate an
935 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000936 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000937 if (isa<ExtVectorElementExpr>(IE)) {
938 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
939 Value *SVOp = SVI->getOperand(0);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000940 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000941
942 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000943 for (unsigned j = 0; j != CurIdx; ++j) {
944 // If the current vector initializer is a shuffle with undef, merge
945 // this shuffle directly into it.
946 if (VIsUndefShuffle) {
947 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000948 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000949 } else {
Chris Lattner48431f92011-04-19 22:55:03 +0000950 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000951 }
952 }
953 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000954 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000955 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000956
957 if (VIsUndefShuffle)
958 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
959
960 Init = SVOp;
961 }
962 }
963
964 // Extend init to result vector length, and then shuffle its contribution
965 // to the vector initializer into V.
966 if (Args.empty()) {
967 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000968 Args.push_back(Builder.getInt32(j));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000969 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +0000970 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000971 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000972 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000973
974 Args.clear();
975 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000976 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000977 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000978 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000979 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000980 }
981
982 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
983 // merging subsequent shuffles into this one.
984 if (CurIdx == 0)
985 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +0000986 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000987 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
988 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
989 CurIdx += InitElts;
990 }
991
992 // FIXME: evaluate codegen vs. shuffling against constant null vector.
993 // Emit remaining default initializers.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000994 llvm::Type *EltTy = VType->getElementType();
Nate Begeman0533b302009-10-18 20:10:40 +0000995
996 // Emit remaining default initializers
997 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner48431f92011-04-19 22:55:03 +0000998 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000999 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1000 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1001 }
1002 return V;
1003}
1004
Anders Carlssona3697c92009-11-23 17:57:54 +00001005static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1006 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +00001007
John McCall2de56d12010-08-25 11:45:40 +00001008 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +00001009 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +00001010
1011 if (isa<CXXThisExpr>(E)) {
1012 // We always assume that 'this' is never null.
1013 return false;
1014 }
1015
1016 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00001017 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +00001018 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +00001019 return false;
1020 }
1021
1022 return true;
1023}
1024
Chris Lattner7f02f722007-08-24 05:35:26 +00001025// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1026// have to handle a more broad range of conversions than explicit casts, as they
1027// handle things like function to ptr-to-function decay etc.
John McCallbc8d40d2011-06-24 21:55:10 +00001028Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmand8889622009-11-27 04:41:50 +00001029 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001030 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001031 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001032
Mike Stump7f79f9b2009-05-29 15:46:01 +00001033 if (!DestTy->isVoidType())
1034 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001035
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001036 // Since almost all cast kinds apply to scalars, this switch doesn't have
1037 // a default case, so the compiler will warn on a missing case. The cases
1038 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001039 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001040 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1041
John McCall2de56d12010-08-25 11:45:40 +00001042 case CK_LValueBitCast:
1043 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001044 Value *V = EmitLValue(E).getAddress();
1045 V = Builder.CreateBitCast(V,
1046 ConvertType(CGF.getContext().getPointerType(DestTy)));
Eli Friedmand71f4422011-12-19 23:03:09 +00001047 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
Douglas Gregore39a3892010-07-13 23:17:26 +00001048 }
John McCalldc05b112011-09-10 01:16:55 +00001049
John McCall1d9b3b22011-09-09 05:25:32 +00001050 case CK_CPointerToObjCPointerCast:
1051 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001052 case CK_AnyPointerToBlockPointerCast:
1053 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001054 Value *Src = Visit(const_cast<Expr*>(E));
1055 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1056 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001057 case CK_AtomicToNonAtomic:
1058 case CK_NonAtomicToAtomic:
John McCall2de56d12010-08-25 11:45:40 +00001059 case CK_NoOp:
1060 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001061 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001062
John McCall2de56d12010-08-25 11:45:40 +00001063 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +00001064 const CXXRecordDecl *DerivedClassDecl =
1065 DestTy->getCXXRecordDeclForPointerType();
1066
Anders Carlssona04efdf2010-04-24 21:23:59 +00001067 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001068 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001069 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001070 }
John McCall2de56d12010-08-25 11:45:40 +00001071 case CK_UncheckedDerivedToBase:
1072 case CK_DerivedToBase: {
Anders Carlsson191dfe92009-09-12 04:57:16 +00001073 const RecordType *DerivedClassTy =
1074 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1075 CXXRecordDecl *DerivedClassDecl =
1076 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1077
Anders Carlsson34a2d382010-04-24 21:06:20 +00001078 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001079 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001080 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001081 }
Anders Carlsson575b3742011-04-11 02:03:26 +00001082 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001083 Value *V = Visit(const_cast<Expr*>(E));
1084 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1085 return CGF.EmitDynamicCast(V, DCE);
1086 }
Eli Friedmand8889622009-11-27 04:41:50 +00001087
John McCall2de56d12010-08-25 11:45:40 +00001088 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001089 assert(E->getType()->isArrayType() &&
1090 "Array to pointer decay must have array source type!");
1091
1092 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1093
1094 // Note that VLA pointers are always decayed, so we don't need to do
1095 // anything here.
1096 if (!E->getType()->isVariableArrayType()) {
1097 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1098 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1099 ->getElementType()) &&
1100 "Expected pointer to array");
1101 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1102 }
1103
Chris Lattner410b12e2011-07-20 04:31:01 +00001104 // Make sure the array decay ends up being the right type. This matters if
1105 // the array type was of an incomplete type.
Chris Lattnercb8095f2011-07-20 04:59:57 +00001106 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
Eli Friedmanad35a832009-11-16 21:33:53 +00001107 }
John McCall2de56d12010-08-25 11:45:40 +00001108 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001109 return EmitLValue(E).getAddress();
1110
John McCall404cd162010-11-13 01:35:44 +00001111 case CK_NullToPointer:
1112 if (MustVisitNullValue(E))
1113 (void) Visit(E);
1114
1115 return llvm::ConstantPointerNull::get(
1116 cast<llvm::PointerType>(ConvertType(DestTy)));
1117
John McCall2de56d12010-08-25 11:45:40 +00001118 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001119 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001120 (void) Visit(E);
1121
John McCall0bab0cd2010-08-23 01:21:21 +00001122 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1123 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1124 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001125
John McCall4d4e5c12012-02-15 01:22:51 +00001126 case CK_ReinterpretMemberPointer:
John McCall2de56d12010-08-25 11:45:40 +00001127 case CK_BaseToDerivedMemberPointer:
1128 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001129 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001130
1131 // Note that the AST doesn't distinguish between checked and
1132 // unchecked member pointer conversions, so we always have to
1133 // implement checked conversions here. This is inefficient when
1134 // actual control flow may be required in order to perform the
1135 // check, which it is for data member pointers (but not member
1136 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001137 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001138 }
John McCallf85e1932011-06-15 23:02:42 +00001139
John McCall33e56f32011-09-10 06:18:15 +00001140 case CK_ARCProduceObject:
John McCallf85e1932011-06-15 23:02:42 +00001141 return CGF.EmitARCRetainScalarExpr(E);
John McCall33e56f32011-09-10 06:18:15 +00001142 case CK_ARCConsumeObject:
John McCallf85e1932011-06-15 23:02:42 +00001143 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall33e56f32011-09-10 06:18:15 +00001144 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00001145 llvm::Value *value = Visit(E);
1146 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1147 return CGF.EmitObjCConsumeObject(E->getType(), value);
1148 }
John McCall348f16f2011-10-04 06:23:45 +00001149 case CK_ARCExtendBlockObject:
1150 return CGF.EmitARCExtendBlockObject(E);
John McCallf85e1932011-06-15 23:02:42 +00001151
Douglas Gregorac1303e2012-02-22 05:02:47 +00001152 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmancae40c42012-02-28 01:08:45 +00001153 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Douglas Gregorac1303e2012-02-22 05:02:47 +00001154
John McCall2bb5d002010-11-13 09:02:35 +00001155 case CK_FloatingRealToComplex:
1156 case CK_FloatingComplexCast:
1157 case CK_IntegralRealToComplex:
1158 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001159 case CK_IntegralComplexToFloatingComplex:
1160 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001161 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001162 case CK_ToUnion:
1163 llvm_unreachable("scalar cast to non-scalar value");
John McCallf6a16482010-12-04 03:47:34 +00001164
John McCall0ae287a2010-12-01 04:43:34 +00001165 case CK_LValueToRValue:
1166 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001167 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001168 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001169
John McCall2de56d12010-08-25 11:45:40 +00001170 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001171 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001172
Anders Carlsson82debc72009-10-18 18:12:03 +00001173 // First, convert to the correct width so that we control the kind of
1174 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001175 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +00001176 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson82debc72009-10-18 18:12:03 +00001177 llvm::Value* IntResult =
1178 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001179
Anders Carlsson82debc72009-10-18 18:12:03 +00001180 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001181 }
Eli Friedman65949422011-06-25 02:58:47 +00001182 case CK_PointerToIntegral:
1183 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1184 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001185
John McCall2de56d12010-08-25 11:45:40 +00001186 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001187 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001188 return 0;
1189 }
John McCall2de56d12010-08-25 11:45:40 +00001190 case CK_VectorSplat: {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001191 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001192 Value *Elt = Visit(const_cast<Expr*>(E));
Craig Topper5fa56082012-02-06 05:05:50 +00001193 Elt = EmitScalarConversion(Elt, E->getType(),
1194 DestTy->getAs<VectorType>()->getElementType());
Eli Friedmanad35a832009-11-16 21:33:53 +00001195
1196 // Insert the element in element zero of an undef vector
1197 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +00001198 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +00001199 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Eli Friedmanad35a832009-11-16 21:33:53 +00001200
1201 // Splat the element across to all elements
Eli Friedmanad35a832009-11-16 21:33:53 +00001202 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner48431f92011-04-19 22:55:03 +00001203 llvm::Constant *Zero = Builder.getInt32(0);
Chris Lattner2ce88422012-01-25 05:34:41 +00001204 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero);
Eli Friedmanad35a832009-11-16 21:33:53 +00001205 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1206 return Yay;
1207 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001208
John McCall2de56d12010-08-25 11:45:40 +00001209 case CK_IntegralCast:
1210 case CK_IntegralToFloating:
1211 case CK_FloatingToIntegral:
1212 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001213 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
John McCalldaa8e4e2010-11-15 09:13:47 +00001214 case CK_IntegralToBoolean:
1215 return EmitIntToBoolConversion(Visit(E));
1216 case CK_PointerToBoolean:
1217 return EmitPointerToBoolConversion(Visit(E));
1218 case CK_FloatingToBoolean:
1219 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001220 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001221 llvm::Value *MemPtr = Visit(E);
1222 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1223 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001224 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001225
1226 case CK_FloatingComplexToReal:
1227 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001228 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001229
1230 case CK_FloatingComplexToBoolean:
1231 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001232 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001233
1234 // TODO: kill this function off, inline appropriate case here
1235 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1236 }
1237
John McCall0bab0cd2010-08-23 01:21:21 +00001238 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001239
John McCall61ad0e62010-11-16 06:21:14 +00001240 llvm_unreachable("unknown scalar cast");
Chris Lattner7f02f722007-08-24 05:35:26 +00001241}
1242
Chris Lattner33793202007-08-31 22:09:40 +00001243Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001244 CodeGenFunction::StmtExprEvaluation eval(CGF);
1245 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1246 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001247}
1248
Chris Lattner7f02f722007-08-24 05:35:26 +00001249//===----------------------------------------------------------------------===//
1250// Unary Operators
1251//===----------------------------------------------------------------------===//
1252
Chris Lattner8c11a652010-06-26 22:09:34 +00001253llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001254EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1255 llvm::Value *InVal,
1256 llvm::Value *NextVal, bool IsInc) {
1257 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1258 case LangOptions::SOB_Undefined:
1259 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
Anton Yartsev683564a2011-02-07 02:17:30 +00001260 case LangOptions::SOB_Defined:
1261 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
Anton Yartsev683564a2011-02-07 02:17:30 +00001262 case LangOptions::SOB_Trapping:
1263 BinOpInfo BinOp;
1264 BinOp.LHS = InVal;
1265 BinOp.RHS = NextVal;
1266 BinOp.Ty = E->getType();
1267 BinOp.Opcode = BO_Add;
1268 BinOp.E = E;
1269 return EmitOverflowCheckedBinOp(BinOp);
Anton Yartsev683564a2011-02-07 02:17:30 +00001270 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001271 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev683564a2011-02-07 02:17:30 +00001272}
1273
John McCall5936e332011-02-15 09:22:45 +00001274llvm::Value *
1275ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1276 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001277
John McCall5936e332011-02-15 09:22:45 +00001278 QualType type = E->getSubExpr()->getType();
John McCall545d9962011-06-25 02:11:03 +00001279 llvm::Value *value = EmitLoadOfLValue(LV);
John McCall5936e332011-02-15 09:22:45 +00001280 llvm::Value *input = value;
David Chisnall7a7ee302012-01-16 17:27:18 +00001281 llvm::PHINode *atomicPHI = 0;
Anton Yartsev683564a2011-02-07 02:17:30 +00001282
John McCall5936e332011-02-15 09:22:45 +00001283 int amount = (isInc ? 1 : -1);
1284
David Chisnall7a7ee302012-01-16 17:27:18 +00001285 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1286 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1287 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1288 Builder.CreateBr(opBB);
1289 Builder.SetInsertPoint(opBB);
1290 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1291 atomicPHI->addIncoming(value, startBB);
1292 type = atomicTy->getValueType();
1293 value = atomicPHI;
1294 }
1295
John McCall5936e332011-02-15 09:22:45 +00001296 // Special case of integer increment that we have to check first: bool++.
1297 // Due to promotion rules, we get:
1298 // bool++ -> bool = bool + 1
1299 // -> bool = (int)bool + 1
1300 // -> bool = ((int)bool + 1 != 0)
1301 // An interesting aspect of this is that increment is always true.
1302 // Decrement does not have this property.
1303 if (isInc && type->isBooleanType()) {
1304 value = Builder.getTrue();
1305
1306 // Most common case by far: integer increment.
1307 } else if (type->isIntegerType()) {
1308
1309 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1310
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001311 // Note that signed integer inc/dec with width less than int can't
1312 // overflow because of promotion rules; we're just eliding a few steps here.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001313 if (type->isSignedIntegerOrEnumerationType() &&
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001314 value->getType()->getPrimitiveSizeInBits() >=
John McCall913dab22011-06-25 01:32:37 +00001315 CGF.IntTy->getBitWidth())
John McCall5936e332011-02-15 09:22:45 +00001316 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
John McCall5936e332011-02-15 09:22:45 +00001317 else
1318 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1319
1320 // Next most common: pointer increment.
1321 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1322 QualType type = ptr->getPointeeType();
1323
1324 // VLA types don't have constant size.
John McCall913dab22011-06-25 01:32:37 +00001325 if (const VariableArrayType *vla
1326 = CGF.getContext().getAsVariableArrayType(type)) {
1327 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCallbc8d40d2011-06-24 21:55:10 +00001328 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Chris Lattner2cb42222011-03-01 00:03:48 +00001329 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
John McCallbc8d40d2011-06-24 21:55:10 +00001330 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2cb42222011-03-01 00:03:48 +00001331 else
John McCallbc8d40d2011-06-24 21:55:10 +00001332 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
John McCall5936e332011-02-15 09:22:45 +00001333
1334 // Arithmetic on function pointers (!) is just +-1.
1335 } else if (type->isFunctionType()) {
Chris Lattner48431f92011-04-19 22:55:03 +00001336 llvm::Value *amt = Builder.getInt32(amount);
John McCall5936e332011-02-15 09:22:45 +00001337
1338 value = CGF.EmitCastToVoidPtr(value);
Chris Lattner2cb42222011-03-01 00:03:48 +00001339 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1340 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1341 else
1342 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001343 value = Builder.CreateBitCast(value, input->getType());
1344
1345 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001346 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001347 llvm::Value *amt = Builder.getInt32(amount);
Chris Lattner2cb42222011-03-01 00:03:48 +00001348 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1349 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1350 else
1351 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001352 }
1353
1354 // Vector increment/decrement.
1355 } else if (type->isVectorType()) {
1356 if (type->hasIntegerRepresentation()) {
1357 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1358
Eli Friedmand4b9ee32011-05-06 18:04:18 +00001359 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCall5936e332011-02-15 09:22:45 +00001360 } else {
1361 value = Builder.CreateFAdd(
1362 value,
1363 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001364 isInc ? "inc" : "dec");
1365 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001366
John McCall5936e332011-02-15 09:22:45 +00001367 // Floating point.
1368 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001369 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001370 llvm::Value *amt;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001371
1372 if (type->isHalfType()) {
1373 // Another special case: half FP increment should be done via float
1374 value =
1375 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1376 input);
1377 }
1378
John McCall5936e332011-02-15 09:22:45 +00001379 if (value->getType()->isFloatTy())
1380 amt = llvm::ConstantFP::get(VMContext,
1381 llvm::APFloat(static_cast<float>(amount)));
1382 else if (value->getType()->isDoubleTy())
1383 amt = llvm::ConstantFP::get(VMContext,
1384 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001385 else {
John McCall5936e332011-02-15 09:22:45 +00001386 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001387 bool ignored;
1388 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1389 &ignored);
John McCall5936e332011-02-15 09:22:45 +00001390 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001391 }
John McCall5936e332011-02-15 09:22:45 +00001392 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1393
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001394 if (type->isHalfType())
1395 value =
1396 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1397 value);
1398
John McCall5936e332011-02-15 09:22:45 +00001399 // Objective-C pointer types.
1400 } else {
1401 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1402 value = CGF.EmitCastToVoidPtr(value);
1403
1404 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1405 if (!isInc) size = -size;
1406 llvm::Value *sizeValue =
1407 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1408
Chris Lattner2cb42222011-03-01 00:03:48 +00001409 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1410 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1411 else
1412 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001413 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001414 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001415
1416 if (atomicPHI) {
1417 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1418 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1419 llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
1420 value, llvm::SequentiallyConsistent);
1421 atomicPHI->addIncoming(old, opBB);
1422 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1423 Builder.CreateCondBr(success, contBB, opBB);
1424 Builder.SetInsertPoint(contBB);
1425 return isPre ? value : input;
1426 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001427
Chris Lattner8c11a652010-06-26 22:09:34 +00001428 // Store the updated result through the lvalue.
1429 if (LV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001430 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001431 else
John McCall545d9962011-06-25 02:11:03 +00001432 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001433
Chris Lattner8c11a652010-06-26 22:09:34 +00001434 // If this is a postinc, return the value read from memory, otherwise use the
1435 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001436 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001437}
1438
1439
1440
Chris Lattner7f02f722007-08-24 05:35:26 +00001441Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001442 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001443 // Emit unary minus with EmitSub so we handle overflow cases etc.
1444 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001445 BinOp.RHS = Visit(E->getSubExpr());
1446
1447 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1448 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1449 else
1450 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001451 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001452 BinOp.Opcode = BO_Sub;
Chris Lattner9a207232010-06-26 21:48:21 +00001453 BinOp.E = E;
1454 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001455}
1456
1457Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001458 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001459 Value *Op = Visit(E->getSubExpr());
1460 return Builder.CreateNot(Op, "neg");
1461}
1462
1463Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00001464
1465 // Perform vector logical not on comparison with zero vector.
1466 if (E->getType()->isExtVectorType()) {
1467 Value *Oper = Visit(E->getSubExpr());
1468 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1469 Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1470 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1471 }
1472
Chris Lattner7f02f722007-08-24 05:35:26 +00001473 // Compare operand to zero.
1474 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001475
Chris Lattner7f02f722007-08-24 05:35:26 +00001476 // Invert value.
1477 // TODO: Could dynamically modify easy computations here. For example, if
1478 // the operand is an icmp ne, turn into icmp eq.
1479 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001480
Anders Carlsson9f84d882009-05-19 18:44:53 +00001481 // ZExt result to the expr type.
1482 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001483}
1484
Eli Friedman0027d2b2010-08-05 09:58:49 +00001485Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1486 // Try folding the offsetof to a constant.
Richard Smith80d4b552011-12-28 19:48:30 +00001487 llvm::APSInt Value;
1488 if (E->EvaluateAsInt(Value, CGF.getContext()))
1489 return Builder.getInt(Value);
Eli Friedman0027d2b2010-08-05 09:58:49 +00001490
1491 // Loop over the components of the offsetof to compute the value.
1492 unsigned n = E->getNumComponents();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001493 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001494 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1495 QualType CurrentType = E->getTypeSourceInfo()->getType();
1496 for (unsigned i = 0; i != n; ++i) {
1497 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001498 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001499 switch (ON.getKind()) {
1500 case OffsetOfExpr::OffsetOfNode::Array: {
1501 // Compute the index
1502 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1503 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001504 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedman0027d2b2010-08-05 09:58:49 +00001505 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1506
1507 // Save the element type
1508 CurrentType =
1509 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1510
1511 // Compute the element size
1512 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1513 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1514
1515 // Multiply out to compute the result
1516 Offset = Builder.CreateMul(Idx, ElemSize);
1517 break;
1518 }
1519
1520 case OffsetOfExpr::OffsetOfNode::Field: {
1521 FieldDecl *MemberDecl = ON.getField();
1522 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1523 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1524
1525 // Compute the index of the field in its parent.
1526 unsigned i = 0;
1527 // FIXME: It would be nice if we didn't have to loop here!
1528 for (RecordDecl::field_iterator Field = RD->field_begin(),
1529 FieldEnd = RD->field_end();
1530 Field != FieldEnd; (void)++Field, ++i) {
1531 if (*Field == MemberDecl)
1532 break;
1533 }
1534 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1535
1536 // Compute the offset to the field
1537 int64_t OffsetInt = RL.getFieldOffset(i) /
1538 CGF.getContext().getCharWidth();
1539 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1540
1541 // Save the element type.
1542 CurrentType = MemberDecl->getType();
1543 break;
1544 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001545
Eli Friedman0027d2b2010-08-05 09:58:49 +00001546 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001547 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001548
Eli Friedman0027d2b2010-08-05 09:58:49 +00001549 case OffsetOfExpr::OffsetOfNode::Base: {
1550 if (ON.getBase()->isVirtual()) {
1551 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1552 continue;
1553 }
1554
1555 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1556 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1557
1558 // Save the element type.
1559 CurrentType = ON.getBase()->getType();
1560
1561 // Compute the offset to the base.
1562 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1563 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Anders Carlssona14f5972010-10-31 23:22:37 +00001564 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
Eli Friedman0027d2b2010-08-05 09:58:49 +00001565 CGF.getContext().getCharWidth();
1566 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1567 break;
1568 }
1569 }
1570 Result = Builder.CreateAdd(Result, Offset);
1571 }
1572 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001573}
1574
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001575/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001576/// argument of the sizeof expression as an integer.
1577Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001578ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1579 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001580 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001581 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001582 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001583 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1584 if (E->isArgumentType()) {
1585 // sizeof(type) - make sure to emit the VLA size.
John McCallbc8d40d2011-06-24 21:55:10 +00001586 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001587 } else {
1588 // C99 6.5.3.4p2: If the argument is an expression of type
1589 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001590 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001591 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001592
John McCallbc8d40d2011-06-24 21:55:10 +00001593 QualType eltType;
1594 llvm::Value *numElts;
1595 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1596
1597 llvm::Value *size = numElts;
1598
1599 // Scale the number of non-VLA elements by the non-VLA element size.
1600 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1601 if (!eltSize.isOne())
1602 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1603
1604 return size;
Anders Carlssonb50525b2008-12-21 03:33:21 +00001605 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001606 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001607
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001608 // If this isn't sizeof(vla), the result must be constant; use the constant
1609 // folding logic so we don't have to duplicate it here.
Richard Smith80d4b552011-12-28 19:48:30 +00001610 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001611}
1612
Chris Lattner46f93d02007-08-24 21:20:17 +00001613Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1614 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001615 if (Op->getType()->isAnyComplexType()) {
1616 // If it's an l-value, load through the appropriate subobject l-value.
1617 // Note that we have to ask E because Op might be an l-value that
1618 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001619 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001620 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001621
1622 // Otherwise, calculate and project.
1623 return CGF.EmitComplexExpr(Op, false, true).first;
1624 }
1625
Chris Lattner46f93d02007-08-24 21:20:17 +00001626 return Visit(Op);
1627}
John McCallb418d742010-11-16 10:08:07 +00001628
Chris Lattner46f93d02007-08-24 21:20:17 +00001629Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1630 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001631 if (Op->getType()->isAnyComplexType()) {
1632 // If it's an l-value, load through the appropriate subobject l-value.
1633 // Note that we have to ask E because Op might be an l-value that
1634 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001635 if (Op->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001636 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001637
1638 // Otherwise, calculate and project.
1639 return CGF.EmitComplexExpr(Op, true, false).second;
1640 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001641
Mike Stump7f79f9b2009-05-29 15:46:01 +00001642 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1643 // effects are evaluated, but not the actual value.
Richard Smithdfb80de2012-02-18 20:53:32 +00001644 if (Op->isGLValue())
1645 CGF.EmitLValue(Op);
1646 else
1647 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001648 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001649}
1650
Chris Lattner7f02f722007-08-24 05:35:26 +00001651//===----------------------------------------------------------------------===//
1652// Binary Operators
1653//===----------------------------------------------------------------------===//
1654
1655BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001656 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001657 BinOpInfo Result;
1658 Result.LHS = Visit(E->getLHS());
1659 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001660 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001661 Result.Opcode = E->getOpcode();
Chris Lattner7f02f722007-08-24 05:35:26 +00001662 Result.E = E;
1663 return Result;
1664}
1665
Douglas Gregor6a03e342010-04-23 04:16:32 +00001666LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1667 const CompoundAssignOperator *E,
1668 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001669 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001670 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001671 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001672
Eli Friedmanab3a8522009-03-28 01:22:36 +00001673 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001674 // This needs to go through the complex expression emitter, but it's a tad
1675 // complicated to do that... I'm leaving it out for now. (Note that we do
1676 // actually need the imaginary part of the RHS for multiplication and
1677 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001678 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001679 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001680 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001681 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001682
Mike Stumpcc0442f2009-05-22 19:07:20 +00001683 // Emit the RHS first. __block variables need to have the rhs evaluated
1684 // first, plus this should improve codegen a little.
1685 OpInfo.RHS = Visit(E->getRHS());
1686 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001687 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001688 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001689 // Load/convert the LHS.
Mike Stumpb14e62d2009-12-16 02:57:00 +00001690 LValue LHSLV = EmitCheckedLValue(E->getLHS());
John McCall545d9962011-06-25 02:11:03 +00001691 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
Eli Friedmanab3a8522009-03-28 01:22:36 +00001692 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1693 E->getComputationLHSType());
David Chisnall7a7ee302012-01-16 17:27:18 +00001694
1695 llvm::PHINode *atomicPHI = 0;
1696 if (const AtomicType *atomicTy = OpInfo.Ty->getAs<AtomicType>()) {
1697 // FIXME: For floating point types, we should be saving and restoring the
1698 // floating point environment in the loop.
1699 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1700 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1701 Builder.CreateBr(opBB);
1702 Builder.SetInsertPoint(opBB);
1703 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
1704 atomicPHI->addIncoming(OpInfo.LHS, startBB);
1705 OpInfo.Ty = atomicTy->getValueType();
1706 OpInfo.LHS = atomicPHI;
1707 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001708
Chris Lattner1f1ded92007-08-24 21:00:35 +00001709 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001710 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001711
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001712 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001713 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
David Chisnall7a7ee302012-01-16 17:27:18 +00001714
1715 if (atomicPHI) {
1716 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1717 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1718 llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
1719 Result, llvm::SequentiallyConsistent);
1720 atomicPHI->addIncoming(old, opBB);
1721 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1722 Builder.CreateCondBr(success, contBB, opBB);
1723 Builder.SetInsertPoint(contBB);
1724 return LHSLV;
1725 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001726
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001727 // Store the result value into the LHS lvalue. Bit-fields are handled
1728 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1729 // 'An assignment expression has the value of the left operand after the
1730 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001731 if (LHSLV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001732 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001733 else
John McCall545d9962011-06-25 02:11:03 +00001734 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001735
Douglas Gregor6a03e342010-04-23 04:16:32 +00001736 return LHSLV;
1737}
1738
1739Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1740 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1741 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001742 Value *RHS;
1743 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1744
1745 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001746 if (Ignore)
1747 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001748
John McCallb418d742010-11-16 10:08:07 +00001749 // The result of an assignment in C is the assigned r-value.
1750 if (!CGF.getContext().getLangOptions().CPlusPlus)
1751 return RHS;
1752
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001753 // If the lvalue is non-volatile, return the computed value of the assignment.
1754 if (!LHS.isVolatileQualified())
1755 return RHS;
1756
1757 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00001758 return EmitLoadOfLValue(LHS);
Chris Lattner1f1ded92007-08-24 21:00:35 +00001759}
1760
Chris Lattner80230302010-09-11 21:47:09 +00001761void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1762 const BinOpInfo &Ops,
1763 llvm::Value *Zero, bool isDiv) {
Bill Wendling14ef3192011-07-07 21:13:10 +00001764 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
Chris Lattner80230302010-09-11 21:47:09 +00001765 llvm::BasicBlock *contBB =
Bill Wendling14ef3192011-07-07 21:13:10 +00001766 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn,
1767 llvm::next(insertPt));
1768 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Chris Lattner80230302010-09-11 21:47:09 +00001769
Chris Lattner2acc6e32011-07-18 04:24:23 +00001770 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
Chris Lattner80230302010-09-11 21:47:09 +00001771
1772 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1773 llvm::Value *IntMin =
Chris Lattner48431f92011-04-19 22:55:03 +00001774 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner80230302010-09-11 21:47:09 +00001775 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1776
1777 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1778 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1779 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1780 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1781 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1782 overflowBB, contBB);
1783 } else {
1784 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1785 overflowBB, contBB);
1786 }
1787 EmitOverflowBB(overflowBB);
1788 Builder.SetInsertPoint(contBB);
1789}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001790
Chris Lattner7f02f722007-08-24 05:35:26 +00001791Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Chris Lattner80230302010-09-11 21:47:09 +00001792 if (isTrapvOverflowBehavior()) {
1793 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1794
1795 if (Ops.Ty->isIntegerType())
1796 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1797 else if (Ops.Ty->isRealFloatingType()) {
Bill Wendling14ef3192011-07-07 21:13:10 +00001798 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
1799 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn,
1800 llvm::next(insertPt));
Chris Lattner80230302010-09-11 21:47:09 +00001801 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1802 CGF.CurFn);
Chris Lattner80230302010-09-11 21:47:09 +00001803 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1804 overflowBB, DivCont);
1805 EmitOverflowBB(overflowBB);
1806 Builder.SetInsertPoint(DivCont);
1807 }
1808 }
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001809 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
1810 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1811 if (CGF.getContext().getLangOptions().OpenCL) {
1812 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
1813 llvm::Type *ValTy = Val->getType();
1814 if (ValTy->isFloatTy() ||
1815 (isa<llvm::VectorType>(ValTy) &&
1816 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
1817 CGF.SetFPAccuracy(Val, 5, 2);
1818 }
1819 return Val;
1820 }
Douglas Gregorf6094622010-07-23 15:58:24 +00001821 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001822 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1823 else
1824 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1825}
1826
1827Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1828 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner80230302010-09-11 21:47:09 +00001829 if (isTrapvOverflowBehavior()) {
1830 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1831
1832 if (Ops.Ty->isIntegerType())
1833 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1834 }
1835
Eli Friedman52d68742011-04-10 04:44:11 +00001836 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001837 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1838 else
1839 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1840}
1841
Mike Stump2add4732009-04-01 20:28:16 +00001842Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1843 unsigned IID;
1844 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001845
Chris Lattner9a207232010-06-26 21:48:21 +00001846 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001847 case BO_Add:
1848 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001849 OpID = 1;
1850 IID = llvm::Intrinsic::sadd_with_overflow;
1851 break;
John McCall2de56d12010-08-25 11:45:40 +00001852 case BO_Sub:
1853 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001854 OpID = 2;
1855 IID = llvm::Intrinsic::ssub_with_overflow;
1856 break;
John McCall2de56d12010-08-25 11:45:40 +00001857 case BO_Mul:
1858 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001859 OpID = 3;
1860 IID = llvm::Intrinsic::smul_with_overflow;
1861 break;
1862 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001863 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump2add4732009-04-01 20:28:16 +00001864 }
Mike Stump035cf892009-04-02 18:15:54 +00001865 OpID <<= 1;
1866 OpID |= 1;
1867
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001868 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump2add4732009-04-01 20:28:16 +00001869
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00001870 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump2add4732009-04-01 20:28:16 +00001871
1872 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1873 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1874 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1875
1876 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00001877 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendling14ef3192011-07-07 21:13:10 +00001878 llvm::Function::iterator insertPt = initialBB;
1879 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
1880 llvm::next(insertPt));
Chris Lattner93a00352010-08-07 00:20:46 +00001881 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001882
1883 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1884
Chris Lattner93a00352010-08-07 00:20:46 +00001885 // Handle overflow with llvm.trap.
David Chisnall7f18e672010-09-17 18:29:54 +00001886 const std::string *handlerName =
1887 &CGF.getContext().getLangOptions().OverflowHandler;
1888 if (handlerName->empty()) {
1889 EmitOverflowBB(overflowBB);
1890 Builder.SetInsertPoint(continueBB);
1891 return result;
1892 }
1893
1894 // If an overflow handler is set, then we want to call it and then use its
1895 // result, if it returns.
1896 Builder.SetInsertPoint(overflowBB);
1897
1898 // Get the overflow handler.
Chris Lattner8b418682012-02-07 00:39:47 +00001899 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001900 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnall7f18e672010-09-17 18:29:54 +00001901 llvm::FunctionType *handlerTy =
1902 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1903 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1904
1905 // Sign extend the args to 64-bit, so that we can use the same handler for
1906 // all types of overflow.
1907 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1908 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1909
1910 // Call the handler with the two arguments, the operation, and the size of
1911 // the result.
1912 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1913 Builder.getInt8(OpID),
1914 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1915
1916 // Truncate the result back to the desired size.
1917 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1918 Builder.CreateBr(continueBB);
1919
Mike Stump2add4732009-04-01 20:28:16 +00001920 Builder.SetInsertPoint(continueBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001921 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnall7f18e672010-09-17 18:29:54 +00001922 phi->addIncoming(result, initialBB);
1923 phi->addIncoming(handlerResult, overflowBB);
1924
1925 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00001926}
Chris Lattner7f02f722007-08-24 05:35:26 +00001927
John McCall913dab22011-06-25 01:32:37 +00001928/// Emit pointer + index arithmetic.
1929static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1930 const BinOpInfo &op,
1931 bool isSubtraction) {
1932 // Must have binary (not unary) expr here. Unary pointer
1933 // increment/decrement doesn't use this path.
1934 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1935
1936 Value *pointer = op.LHS;
1937 Expr *pointerOperand = expr->getLHS();
1938 Value *index = op.RHS;
1939 Expr *indexOperand = expr->getRHS();
1940
1941 // In a subtraction, the LHS is always the pointer.
1942 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1943 std::swap(pointer, index);
1944 std::swap(pointerOperand, indexOperand);
1945 }
1946
1947 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1948 if (width != CGF.PointerWidthInBits) {
1949 // Zero-extend or sign-extend the pointer value according to
1950 // whether the index is signed or not.
1951 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1952 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1953 "idx.ext");
1954 }
1955
1956 // If this is subtraction, negate the index.
1957 if (isSubtraction)
1958 index = CGF.Builder.CreateNeg(index, "idx.neg");
1959
1960 const PointerType *pointerType
1961 = pointerOperand->getType()->getAs<PointerType>();
1962 if (!pointerType) {
1963 QualType objectType = pointerOperand->getType()
1964 ->castAs<ObjCObjectPointerType>()
1965 ->getPointeeType();
1966 llvm::Value *objectSize
1967 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1968
1969 index = CGF.Builder.CreateMul(index, objectSize);
1970
1971 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1972 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1973 return CGF.Builder.CreateBitCast(result, pointer->getType());
1974 }
1975
1976 QualType elementType = pointerType->getPointeeType();
1977 if (const VariableArrayType *vla
1978 = CGF.getContext().getAsVariableArrayType(elementType)) {
1979 // The element count here is the total number of non-VLA elements.
1980 llvm::Value *numElements = CGF.getVLASize(vla).first;
1981
1982 // Effectively, the multiply by the VLA size is part of the GEP.
1983 // GEP indexes are signed, and scaling an index isn't permitted to
1984 // signed-overflow, so we use the same semantics for our explicit
1985 // multiply. We suppress this if overflow is not undefined behavior.
1986 if (CGF.getLangOptions().isSignedOverflowDefined()) {
1987 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
1988 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1989 } else {
1990 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
1991 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattnera4d71452010-06-26 21:25:03 +00001992 }
John McCall913dab22011-06-25 01:32:37 +00001993 return pointer;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001994 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001995
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001996 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1997 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1998 // future proof.
John McCall913dab22011-06-25 01:32:37 +00001999 if (elementType->isVoidType() || elementType->isFunctionType()) {
2000 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2001 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2002 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002003 }
2004
John McCall913dab22011-06-25 01:32:37 +00002005 if (CGF.getLangOptions().isSignedOverflowDefined())
2006 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2007
2008 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00002009}
2010
John McCall913dab22011-06-25 01:32:37 +00002011Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2012 if (op.LHS->getType()->isPointerTy() ||
2013 op.RHS->getType()->isPointerTy())
2014 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2015
2016 if (op.Ty->isSignedIntegerOrEnumerationType()) {
2017 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
2018 case LangOptions::SOB_Undefined:
2019 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2020 case LangOptions::SOB_Defined:
2021 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2022 case LangOptions::SOB_Trapping:
2023 return EmitOverflowCheckedBinOp(op);
2024 }
2025 }
2026
2027 if (op.LHS->getType()->isFPOrFPVectorTy())
2028 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
2029
2030 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2031}
2032
2033Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2034 // The LHS is always a pointer if either side is.
2035 if (!op.LHS->getType()->isPointerTy()) {
2036 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00002037 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
2038 case LangOptions::SOB_Undefined:
John McCall913dab22011-06-25 01:32:37 +00002039 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
Chris Lattnera4d71452010-06-26 21:25:03 +00002040 case LangOptions::SOB_Defined:
John McCall913dab22011-06-25 01:32:37 +00002041 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Chris Lattnera4d71452010-06-26 21:25:03 +00002042 case LangOptions::SOB_Trapping:
John McCall913dab22011-06-25 01:32:37 +00002043 return EmitOverflowCheckedBinOp(op);
Chris Lattnera4d71452010-06-26 21:25:03 +00002044 }
2045 }
2046
John McCall913dab22011-06-25 01:32:37 +00002047 if (op.LHS->getType()->isFPOrFPVectorTy())
2048 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Chris Lattner2eb91e42010-03-29 17:28:16 +00002049
John McCall913dab22011-06-25 01:32:37 +00002050 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00002051 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00002052
John McCall913dab22011-06-25 01:32:37 +00002053 // If the RHS is not a pointer, then we have normal pointer
2054 // arithmetic.
2055 if (!op.RHS->getType()->isPointerTy())
2056 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmandaa24a22009-03-28 02:45:41 +00002057
John McCall913dab22011-06-25 01:32:37 +00002058 // Otherwise, this is a pointer subtraction.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00002059
John McCall913dab22011-06-25 01:32:37 +00002060 // Do the raw subtraction part.
2061 llvm::Value *LHS
2062 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2063 llvm::Value *RHS
2064 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2065 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar2a866252009-04-25 05:08:32 +00002066
John McCall913dab22011-06-25 01:32:37 +00002067 // Okay, figure out the element size.
2068 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2069 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002070
John McCall913dab22011-06-25 01:32:37 +00002071 llvm::Value *divisor = 0;
2072
2073 // For a variable-length array, this is going to be non-constant.
2074 if (const VariableArrayType *vla
2075 = CGF.getContext().getAsVariableArrayType(elementType)) {
2076 llvm::Value *numElements;
2077 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2078
2079 divisor = numElements;
2080
2081 // Scale the number of non-VLA elements by the non-VLA element size.
2082 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2083 if (!eltSize.isOne())
2084 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2085
2086 // For everything elese, we can just compute it, safe in the
2087 // assumption that Sema won't let anything through that we can't
2088 // safely compute the size of.
2089 } else {
2090 CharUnits elementSize;
2091 // Handle GCC extension for pointer arithmetic on void* and
2092 // function pointer types.
2093 if (elementType->isVoidType() || elementType->isFunctionType())
2094 elementSize = CharUnits::One();
2095 else
2096 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2097
2098 // Don't even emit the divide for element size of 1.
2099 if (elementSize.isOne())
2100 return diffInChars;
2101
2102 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner7f02f722007-08-24 05:35:26 +00002103 }
Chris Lattner2cb42222011-03-01 00:03:48 +00002104
Chris Lattner2cb42222011-03-01 00:03:48 +00002105 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2106 // pointer difference in C is only defined in the case where both operands
2107 // are pointing to elements of an array.
John McCall913dab22011-06-25 01:32:37 +00002108 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002109}
2110
2111Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2112 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2113 // RHS to the same size as the LHS.
2114 Value *RHS = Ops.RHS;
2115 if (Ops.LHS->getType() != RHS->getType())
2116 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002117
Mike Stumpbe07f602009-12-14 21:58:14 +00002118 if (CGF.CatchUndefined
2119 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2120 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2121 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2122 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2123 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002124 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002125 CGF.EmitBlock(Cont);
2126 }
2127
Chris Lattner7f02f722007-08-24 05:35:26 +00002128 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2129}
2130
2131Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2132 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2133 // RHS to the same size as the LHS.
2134 Value *RHS = Ops.RHS;
2135 if (Ops.LHS->getType() != RHS->getType())
2136 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002137
Mike Stumpbe07f602009-12-14 21:58:14 +00002138 if (CGF.CatchUndefined
2139 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2140 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2141 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2142 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2143 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002144 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002145 CGF.EmitBlock(Cont);
2146 }
2147
Douglas Gregorf6094622010-07-23 15:58:24 +00002148 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002149 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2150 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2151}
2152
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002153enum IntrinsicType { VCMPEQ, VCMPGT };
2154// return corresponding comparison intrinsic for given vector type
2155static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2156 BuiltinType::Kind ElemKind) {
2157 switch (ElemKind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002158 default: llvm_unreachable("unexpected element type");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002159 case BuiltinType::Char_U:
2160 case BuiltinType::UChar:
2161 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2162 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002163 case BuiltinType::Char_S:
2164 case BuiltinType::SChar:
2165 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2166 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002167 case BuiltinType::UShort:
2168 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2169 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002170 case BuiltinType::Short:
2171 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2172 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002173 case BuiltinType::UInt:
2174 case BuiltinType::ULong:
2175 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2176 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002177 case BuiltinType::Int:
2178 case BuiltinType::Long:
2179 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2180 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002181 case BuiltinType::Float:
2182 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2183 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002184 }
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002185}
2186
Chris Lattner7f02f722007-08-24 05:35:26 +00002187Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2188 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002189 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002190 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002191 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002192 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002193 assert(E->getOpcode() == BO_EQ ||
2194 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002195 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2196 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002197 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002198 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002199 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002200 Value *LHS = Visit(E->getLHS());
2201 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002202
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002203 // If AltiVec, the comparison results in a numeric type, so we use
2204 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002205 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002206 // constants for mapping CR6 register bits to predicate result
2207 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2208
2209 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2210
2211 // in several cases vector arguments order will be reversed
2212 Value *FirstVecArg = LHS,
2213 *SecondVecArg = RHS;
2214
2215 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002216 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002217 BuiltinType::Kind ElementKind = BTy->getKind();
2218
2219 switch(E->getOpcode()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002220 default: llvm_unreachable("is not a comparison operation");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002221 case BO_EQ:
2222 CR6 = CR6_LT;
2223 ID = GetIntrinsic(VCMPEQ, ElementKind);
2224 break;
2225 case BO_NE:
2226 CR6 = CR6_EQ;
2227 ID = GetIntrinsic(VCMPEQ, ElementKind);
2228 break;
2229 case BO_LT:
2230 CR6 = CR6_LT;
2231 ID = GetIntrinsic(VCMPGT, ElementKind);
2232 std::swap(FirstVecArg, SecondVecArg);
2233 break;
2234 case BO_GT:
2235 CR6 = CR6_LT;
2236 ID = GetIntrinsic(VCMPGT, ElementKind);
2237 break;
2238 case BO_LE:
2239 if (ElementKind == BuiltinType::Float) {
2240 CR6 = CR6_LT;
2241 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2242 std::swap(FirstVecArg, SecondVecArg);
2243 }
2244 else {
2245 CR6 = CR6_EQ;
2246 ID = GetIntrinsic(VCMPGT, ElementKind);
2247 }
2248 break;
2249 case BO_GE:
2250 if (ElementKind == BuiltinType::Float) {
2251 CR6 = CR6_LT;
2252 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2253 }
2254 else {
2255 CR6 = CR6_EQ;
2256 ID = GetIntrinsic(VCMPGT, ElementKind);
2257 std::swap(FirstVecArg, SecondVecArg);
2258 }
2259 break;
2260 }
2261
Chris Lattner48431f92011-04-19 22:55:03 +00002262 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002263 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2264 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2265 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2266 }
2267
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002268 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002269 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002270 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002271 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002272 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002273 LHS, RHS, "cmp");
2274 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002275 // Unsigned integers and pointers.
2276 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002277 LHS, RHS, "cmp");
2278 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002279
2280 // If this is a vector comparison, sign extend the result to the appropriate
2281 // vector integer type and return it (don't convert to bool).
2282 if (LHSTy->isVectorType())
2283 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002284
Chris Lattner7f02f722007-08-24 05:35:26 +00002285 } else {
2286 // Complex Comparison: can only be an equality comparison.
2287 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2288 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002289
John McCall183700f2009-09-21 23:43:11 +00002290 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002291
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002292 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002293 if (CETy->isRealFloatingType()) {
2294 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2295 LHS.first, RHS.first, "cmp.r");
2296 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2297 LHS.second, RHS.second, "cmp.i");
2298 } else {
2299 // Complex comparisons can only be equality comparisons. As such, signed
2300 // and unsigned opcodes are the same.
2301 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2302 LHS.first, RHS.first, "cmp.r");
2303 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2304 LHS.second, RHS.second, "cmp.i");
2305 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002306
John McCall2de56d12010-08-25 11:45:40 +00002307 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002308 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2309 } else {
John McCall2de56d12010-08-25 11:45:40 +00002310 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002311 "Complex comparison other than == or != ?");
2312 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2313 }
2314 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002315
2316 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002317}
2318
2319Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002320 bool Ignore = TestAndClearIgnoreResultAssign();
2321
John McCallf85e1932011-06-15 23:02:42 +00002322 Value *RHS;
2323 LValue LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002324
John McCallf85e1932011-06-15 23:02:42 +00002325 switch (E->getLHS()->getType().getObjCLifetime()) {
2326 case Qualifiers::OCL_Strong:
2327 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2328 break;
2329
2330 case Qualifiers::OCL_Autoreleasing:
2331 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2332 break;
2333
2334 case Qualifiers::OCL_Weak:
2335 RHS = Visit(E->getRHS());
2336 LHS = EmitCheckedLValue(E->getLHS());
2337 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2338 break;
2339
2340 // No reason to do any of these differently.
2341 case Qualifiers::OCL_None:
2342 case Qualifiers::OCL_ExplicitNone:
2343 // __block variables need to have the rhs evaluated first, plus
2344 // this should improve codegen just a little.
2345 RHS = Visit(E->getRHS());
2346 LHS = EmitCheckedLValue(E->getLHS());
2347
2348 // Store the value into the LHS. Bit-fields are handled specially
2349 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2350 // 'An assignment expression has the value of the left operand after
2351 // the assignment...'.
2352 if (LHS.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002353 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCallf85e1932011-06-15 23:02:42 +00002354 else
John McCall545d9962011-06-25 02:11:03 +00002355 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCallf85e1932011-06-15 23:02:42 +00002356 }
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002357
2358 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002359 if (Ignore)
2360 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002361
John McCallb418d742010-11-16 10:08:07 +00002362 // The result of an assignment in C is the assigned r-value.
2363 if (!CGF.getContext().getLangOptions().CPlusPlus)
2364 return RHS;
2365
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002366 // If the lvalue is non-volatile, return the computed value of the assignment.
2367 if (!LHS.isVolatileQualified())
2368 return RHS;
2369
2370 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00002371 return EmitLoadOfLValue(LHS);
Chris Lattner7f02f722007-08-24 05:35:26 +00002372}
2373
2374Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002375
2376 // Perform vector logical and on comparisons with zero vectors.
2377 if (E->getType()->isVectorType()) {
2378 Value *LHS = Visit(E->getLHS());
2379 Value *RHS = Visit(E->getRHS());
2380 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2381 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2382 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2383 Value *And = Builder.CreateAnd(LHS, RHS);
2384 return Builder.CreateSExt(And, Zero->getType(), "sext");
2385 }
2386
Chris Lattner2acc6e32011-07-18 04:24:23 +00002387 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002388
Chris Lattner20eb09d2008-11-12 08:26:50 +00002389 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2390 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002391 bool LHSCondVal;
2392 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2393 if (LHSCondVal) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002394 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002395 // ZExt result to int or bool.
2396 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002397 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002398
Chris Lattner7804bcb2009-10-17 04:24:20 +00002399 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002400 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002401 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002402 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002403
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002404 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2405 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002406
John McCall150b4622011-01-26 04:00:11 +00002407 CodeGenFunction::ConditionalEvaluation eval(CGF);
2408
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002409 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2410 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2411
2412 // Any edges into the ContBlock are now from an (indeterminate number of)
2413 // edges from this first condition. All of these values will be false. Start
2414 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002415 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002416 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002417 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2418 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002419 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002420
John McCall150b4622011-01-26 04:00:11 +00002421 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002422 CGF.EmitBlock(RHSBlock);
2423 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002424 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002425
Chris Lattner7f02f722007-08-24 05:35:26 +00002426 // Reaquire the RHS block, as there may be subblocks inserted.
2427 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002428
2429 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2430 // into the phi node for the edge with the value of RHSCond.
Devang Patelacd72362011-03-30 00:08:31 +00002431 if (CGF.getDebugInfo())
2432 // There is no need to emit line number for unconditional branch.
2433 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Chris Lattner7f02f722007-08-24 05:35:26 +00002434 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002435 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002436
Chris Lattner7f02f722007-08-24 05:35:26 +00002437 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002438 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002439}
2440
2441Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002442
2443 // Perform vector logical or on comparisons with zero vectors.
2444 if (E->getType()->isVectorType()) {
2445 Value *LHS = Visit(E->getLHS());
2446 Value *RHS = Visit(E->getRHS());
2447 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2448 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2449 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2450 Value *Or = Builder.CreateOr(LHS, RHS);
2451 return Builder.CreateSExt(Or, Zero->getType(), "sext");
2452 }
2453
Chris Lattner2acc6e32011-07-18 04:24:23 +00002454 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002455
Chris Lattner20eb09d2008-11-12 08:26:50 +00002456 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2457 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002458 bool LHSCondVal;
2459 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2460 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002461 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002462 // ZExt result to int or bool.
2463 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002464 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002465
Chris Lattner7804bcb2009-10-17 04:24:20 +00002466 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002467 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002468 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002469 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002470
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002471 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2472 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002473
John McCall150b4622011-01-26 04:00:11 +00002474 CodeGenFunction::ConditionalEvaluation eval(CGF);
2475
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002476 // Branch on the LHS first. If it is true, go to the success (cont) block.
2477 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2478
2479 // Any edges into the ContBlock are now from an (indeterminate number of)
2480 // edges from this first condition. All of these values will be true. Start
2481 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002482 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002483 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002484 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2485 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002486 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002487
John McCall150b4622011-01-26 04:00:11 +00002488 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002489
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002490 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002491 CGF.EmitBlock(RHSBlock);
2492 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002493
John McCall150b4622011-01-26 04:00:11 +00002494 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002495
Chris Lattner7f02f722007-08-24 05:35:26 +00002496 // Reaquire the RHS block, as there may be subblocks inserted.
2497 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002498
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002499 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2500 // into the phi node for the edge with the value of RHSCond.
2501 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002502 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002503
Chris Lattner7f02f722007-08-24 05:35:26 +00002504 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002505 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002506}
2507
2508Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002509 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002510 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002511 return Visit(E->getRHS());
2512}
2513
2514//===----------------------------------------------------------------------===//
2515// Other Operators
2516//===----------------------------------------------------------------------===//
2517
Chris Lattner9802a512008-11-12 08:55:54 +00002518/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2519/// expression is cheap enough and side-effect-free enough to evaluate
2520/// unconditionally instead of conditionally. This is used to convert control
2521/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002522static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2523 CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002524 E = E->IgnoreParens();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002525
Chris Lattnerc6bea672011-04-16 23:15:35 +00002526 // Anything that is an integer or floating point constant is fine.
2527 if (E->isConstantInitializer(CGF.getContext(), false))
Chris Lattner9802a512008-11-12 08:55:54 +00002528 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002529
Chris Lattner9802a512008-11-12 08:55:54 +00002530 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2531 // X and Y are local variables.
2532 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2533 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002534 if (VD->hasLocalStorage() && !(CGF.getContext()
2535 .getCanonicalType(VD->getType())
2536 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002537 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002538
Chris Lattner9802a512008-11-12 08:55:54 +00002539 return false;
2540}
2541
2542
Chris Lattner7f02f722007-08-24 05:35:26 +00002543Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00002544VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002545 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00002546
2547 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +00002548 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCall56ca35d2011-02-17 10:25:35 +00002549
2550 Expr *condExpr = E->getCond();
2551 Expr *lhsExpr = E->getTrueExpr();
2552 Expr *rhsExpr = E->getFalseExpr();
2553
Chris Lattner31a09842008-11-12 08:04:58 +00002554 // If the condition constant folds and can be elided, try to avoid emitting
2555 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002556 bool CondExprBool;
2557 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00002558 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00002559 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002560
Eli Friedmanc8645e32011-10-15 02:10:40 +00002561 // If the dead side doesn't have labels we need, just emit the Live part.
2562 if (!CGF.ContainsLabel(dead)) {
2563 Value *Result = Visit(live);
2564
2565 // If the live part is a throw expression, it acts like it has a void
2566 // type, so evaluating it returns a null Value*. However, a conditional
2567 // with non-void type must return a non-null Value*.
2568 if (!Result && !E->getType()->isVoidType())
2569 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
2570
2571 return Result;
2572 }
Chris Lattnerc657e922008-11-11 18:56:45 +00002573 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002574
Nate Begeman6155d732010-09-20 22:41:17 +00002575 // OpenCL: If the condition is a vector, we can treat this condition like
2576 // the select function.
2577 if (CGF.getContext().getLangOptions().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00002578 && condExpr->getType()->isVectorType()) {
2579 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2580 llvm::Value *LHS = Visit(lhsExpr);
2581 llvm::Value *RHS = Visit(rhsExpr);
Nate Begeman6155d732010-09-20 22:41:17 +00002582
Chris Lattner2acc6e32011-07-18 04:24:23 +00002583 llvm::Type *condType = ConvertType(condExpr->getType());
2584 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Nate Begeman6155d732010-09-20 22:41:17 +00002585
2586 unsigned numElem = vecTy->getNumElements();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002587 llvm::Type *elemType = vecTy->getElementType();
Nate Begeman6155d732010-09-20 22:41:17 +00002588
Chris Lattner2ce88422012-01-25 05:34:41 +00002589 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begeman6155d732010-09-20 22:41:17 +00002590 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2591 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2592 llvm::VectorType::get(elemType,
2593 numElem),
2594 "sext");
2595 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2596
2597 // Cast float to int to perform ANDs if necessary.
2598 llvm::Value *RHSTmp = RHS;
2599 llvm::Value *LHSTmp = LHS;
2600 bool wasCast = false;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002601 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Nate Begeman6155d732010-09-20 22:41:17 +00002602 if (rhsVTy->getElementType()->isFloatTy()) {
2603 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2604 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2605 wasCast = true;
2606 }
2607
2608 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2609 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2610 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2611 if (wasCast)
2612 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2613
2614 return tmp5;
2615 }
2616
Chris Lattner9802a512008-11-12 08:55:54 +00002617 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2618 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002619 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00002620 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2621 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2622 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2623 llvm::Value *LHS = Visit(lhsExpr);
2624 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman1e4f68c2011-12-08 22:01:56 +00002625 if (!LHS) {
2626 // If the conditional has void type, make sure we return a null Value*.
2627 assert(!RHS && "LHS and RHS types must match");
2628 return 0;
2629 }
Chris Lattner9802a512008-11-12 08:55:54 +00002630 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2631 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002632
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002633 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2634 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002635 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002636
2637 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002638 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002639
Chris Lattner7f02f722007-08-24 05:35:26 +00002640 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002641 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002642 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002643 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002644
Chris Lattner7f02f722007-08-24 05:35:26 +00002645 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002646 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002647
Chris Lattner7f02f722007-08-24 05:35:26 +00002648 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002649 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002650 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002651 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002652
John McCall150b4622011-01-26 04:00:11 +00002653 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002654 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002655
Eli Friedman48daf592009-12-07 20:25:53 +00002656 // If the LHS or RHS is a throw expression, it will be legitimately null.
2657 if (!LHS)
2658 return RHS;
2659 if (!RHS)
2660 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002661
Chris Lattner7f02f722007-08-24 05:35:26 +00002662 // Create a PHI node for the real part.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002663 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner7f02f722007-08-24 05:35:26 +00002664 PN->addIncoming(LHS, LHSBlock);
2665 PN->addIncoming(RHS, RHSBlock);
2666 return PN;
2667}
2668
2669Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002670 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002671}
2672
Chris Lattner2202bce2007-11-30 17:56:23 +00002673Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002674 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002675 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2676
2677 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002678 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002679 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2680
Mike Stump7f79f9b2009-05-29 15:46:01 +00002681 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002682 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002683}
2684
John McCall6b5a61b2011-02-07 10:33:21 +00002685Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2686 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002687}
2688
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002689Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2690 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2acc6e32011-07-18 04:24:23 +00002691 llvm::Type *DstTy = ConvertType(E->getType());
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002692
2693 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2694 // a shuffle vector instead of a bitcast.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002695 llvm::Type *SrcTy = Src->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002696 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2697 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2698 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2699 if ((numElementsDst == 3 && numElementsSrc == 4)
2700 || (numElementsDst == 4 && numElementsSrc == 3)) {
2701
2702
2703 // In the case of going from int4->float3, a bitcast is needed before
2704 // doing a shuffle.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002705 llvm::Type *srcElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002706 cast<llvm::VectorType>(SrcTy)->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002707 llvm::Type *dstElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002708 cast<llvm::VectorType>(DstTy)->getElementType();
2709
2710 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2711 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2712 // Create a float type of the same size as the source or destination.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002713 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002714 numElementsSrc);
2715
2716 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2717 }
2718
2719 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2720
Chris Lattner5f9e2722011-07-23 10:55:15 +00002721 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002722 Args.push_back(Builder.getInt32(0));
2723 Args.push_back(Builder.getInt32(1));
2724 Args.push_back(Builder.getInt32(2));
2725
2726 if (numElementsDst == 4)
Chris Lattner8b418682012-02-07 00:39:47 +00002727 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002728
2729 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2730
2731 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2732 }
2733 }
2734
2735 return Builder.CreateBitCast(Src, DstTy, "astype");
2736}
2737
Eli Friedman276b0612011-10-11 02:20:01 +00002738Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
2739 return CGF.EmitAtomicExpr(E).getScalarVal();
2740}
2741
Chris Lattner7f02f722007-08-24 05:35:26 +00002742//===----------------------------------------------------------------------===//
2743// Entry Point into this File
2744//===----------------------------------------------------------------------===//
2745
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002746/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2747/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002748Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002749 assert(E && !hasAggregateLLVMType(E->getType()) &&
2750 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002751
Devang Patel5de7a0e2011-03-07 18:29:53 +00002752 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002753 disableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002754 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stump7f79f9b2009-05-29 15:46:01 +00002755 .Visit(const_cast<Expr*>(E));
Devang Patel5de7a0e2011-03-07 18:29:53 +00002756 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002757 enableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002758 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +00002759}
Chris Lattner3707b252007-08-26 06:48:56 +00002760
2761/// EmitScalarConversion - Emit a conversion from the specified type to the
2762/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002763Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2764 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002765 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2766 "Invalid scalar expression to emit");
2767 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2768}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002769
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002770/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2771/// type to the specified destination type, where the destination type is an
2772/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002773Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2774 QualType SrcTy,
2775 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002776 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002777 "Invalid complex -> scalar conversion");
2778 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2779 DstTy);
2780}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002781
Chris Lattner8c11a652010-06-26 22:09:34 +00002782
2783llvm::Value *CodeGenFunction::
2784EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2785 bool isInc, bool isPre) {
2786 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2787}
2788
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002789LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2790 llvm::Value *V;
2791 // object->isa or (*object).isa
2792 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002793 // build Class* type
Chris Lattner2acc6e32011-07-18 04:24:23 +00002794 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002795
2796 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00002797 if (BaseExpr->isRValue()) {
Eli Friedmand71f4422011-12-19 23:03:09 +00002798 V = CreateMemTemp(E->getType(), "resval");
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002799 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2800 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002801 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
Eli Friedmand71f4422011-12-19 23:03:09 +00002802 MakeNaturalAlignAddrLValue(V, E->getType()));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002803 } else {
2804 if (E->isArrow())
2805 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2806 else
2807 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002808 }
2809
2810 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002811 ClassPtrTy = ClassPtrTy->getPointerTo();
2812 V = Builder.CreateBitCast(V, ClassPtrTy);
Eli Friedmand71f4422011-12-19 23:03:09 +00002813 return MakeNaturalAlignAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002814}
2815
Douglas Gregor6a03e342010-04-23 04:16:32 +00002816
John McCall2a416372010-12-05 02:00:02 +00002817LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00002818 const CompoundAssignOperator *E) {
2819 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002820 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002821 switch (E->getOpcode()) {
2822#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002823 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002824 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002825 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002826 COMPOUND_OP(Mul);
2827 COMPOUND_OP(Div);
2828 COMPOUND_OP(Rem);
2829 COMPOUND_OP(Add);
2830 COMPOUND_OP(Sub);
2831 COMPOUND_OP(Shl);
2832 COMPOUND_OP(Shr);
2833 COMPOUND_OP(And);
2834 COMPOUND_OP(Xor);
2835 COMPOUND_OP(Or);
2836#undef COMPOUND_OP
2837
John McCall2de56d12010-08-25 11:45:40 +00002838 case BO_PtrMemD:
2839 case BO_PtrMemI:
2840 case BO_Mul:
2841 case BO_Div:
2842 case BO_Rem:
2843 case BO_Add:
2844 case BO_Sub:
2845 case BO_Shl:
2846 case BO_Shr:
2847 case BO_LT:
2848 case BO_GT:
2849 case BO_LE:
2850 case BO_GE:
2851 case BO_EQ:
2852 case BO_NE:
2853 case BO_And:
2854 case BO_Xor:
2855 case BO_Or:
2856 case BO_LAnd:
2857 case BO_LOr:
2858 case BO_Assign:
2859 case BO_Comma:
David Blaikieb219cfc2011-09-23 05:06:16 +00002860 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor6a03e342010-04-23 04:16:32 +00002861 }
2862
2863 llvm_unreachable("Unhandled compound assignment operator");
2864}