blob: 9d9562014848f70402ac2e616f0d988e1d207f81 [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 }
Nate Begemane7579b52007-11-15 05:40:03 +0000180 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000181 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000182 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000183 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000184 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000185 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000186 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000187 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000188 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000189 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000190 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000191 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000192 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
193 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000194 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000195
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000196 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000197 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000198 }
John McCalle996ffd2011-02-16 08:02:54 +0000199
200 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000201 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +0000202 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
John McCalle996ffd2011-02-16 08:02:54 +0000203
204 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000205 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000206 }
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000207
Chris Lattner7f02f722007-08-24 05:35:26 +0000208 // l-values.
209 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman28665272009-11-26 03:22:21 +0000210 Expr::EvalResult Result;
John McCall189d6ef2010-10-09 01:34:31 +0000211 if (!E->Evaluate(Result, CGF.getContext()))
212 return EmitLoadOfLValue(E);
213
214 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
215
216 llvm::Constant *C;
Chris Lattner48431f92011-04-19 22:55:03 +0000217 if (Result.Val.isInt())
218 C = Builder.getInt(Result.Val.getInt());
219 else if (Result.Val.isFloat())
John McCall189d6ef2010-10-09 01:34:31 +0000220 C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
Chris Lattner48431f92011-04-19 22:55:03 +0000221 else
John McCall189d6ef2010-10-09 01:34:31 +0000222 return EmitLoadOfLValue(E);
John McCall189d6ef2010-10-09 01:34:31 +0000223
224 // Make sure we emit a debug reference to the global variable.
225 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
226 if (!CGF.getContext().DeclMustBeEmitted(VD))
227 CGF.EmitDeclRefExprDbgValue(E, C);
228 } else if (isa<EnumConstantDecl>(E->getDecl())) {
229 CGF.EmitDeclRefExprDbgValue(E, C);
230 }
231
232 return C;
Chris Lattner7f02f722007-08-24 05:35:26 +0000233 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000234 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
235 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000236 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000237 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
238 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000239 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000240 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000241 return EmitLoadOfLValue(E);
242 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000243 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
John McCallf6a16482010-12-04 03:47:34 +0000244 assert(E->getObjectKind() == OK_Ordinary &&
245 "reached property reference without lvalue-to-rvalue");
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000246 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000247 }
248 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000249 if (E->getMethodDecl() &&
250 E->getMethodDecl()->getResultType()->isReferenceType())
251 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000252 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000253 }
254
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000255 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000256 LValue LV = CGF.EmitObjCIsaExpr(E);
John McCall545d9962011-06-25 02:11:03 +0000257 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000258 return V;
259 }
260
Chris Lattner7f02f722007-08-24 05:35:26 +0000261 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000262 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000263 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000264 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000265 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
266 return EmitLoadOfLValue(E);
267 }
Devang Patel35634f52007-10-24 17:18:43 +0000268
Nate Begeman0533b302009-10-18 20:10:40 +0000269 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000270
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000271 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000272 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000273 }
John McCallbc8d40d2011-06-24 21:55:10 +0000274 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000275 if (E->getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000276 CGF.EmitVariablyModifiedType(E->getType());
277 return VisitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000278 }
John McCallbc8d40d2011-06-24 21:55:10 +0000279 Value *VisitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000280
281 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000282 if (E->getCallReturnType()->isReferenceType())
283 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000284
Chris Lattner9b655512007-08-31 22:49:20 +0000285 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000286 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000287
Chris Lattner33793202007-08-31 22:09:40 +0000288 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000289
Mike Stumpa99038c2009-02-28 09:07:16 +0000290 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000291
Chris Lattner7f02f722007-08-24 05:35:26 +0000292 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000293 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000294 LValue LV = EmitLValue(E->getSubExpr());
295 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000296 }
297 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000298 LValue LV = EmitLValue(E->getSubExpr());
299 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000300 }
301 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000302 LValue LV = EmitLValue(E->getSubExpr());
303 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000304 }
305 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000306 LValue LV = EmitLValue(E->getSubExpr());
307 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000308 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000309
Anton Yartsev683564a2011-02-07 02:17:30 +0000310 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
311 llvm::Value *InVal,
312 llvm::Value *NextVal,
313 bool IsInc);
314
Chris Lattner8c11a652010-06-26 22:09:34 +0000315 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
316 bool isInc, bool isPre);
317
318
Chris Lattner7f02f722007-08-24 05:35:26 +0000319 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000320 if (isa<MemberPointerType>(E->getType())) // never sugared
321 return CGF.CGM.getMemberPointerConstant(E);
322
Chris Lattner7f02f722007-08-24 05:35:26 +0000323 return EmitLValue(E->getSubExpr()).getAddress();
324 }
John McCallfd569002010-12-04 12:43:24 +0000325 Value *VisitUnaryDeref(const UnaryOperator *E) {
326 if (E->getType()->isVoidType())
327 return Visit(E->getSubExpr()); // the actual value should be unused
328 return EmitLoadOfLValue(E);
329 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000330 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000331 // This differs from gcc, though, most likely due to a bug in gcc.
332 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000333 return Visit(E->getSubExpr());
334 }
335 Value *VisitUnaryMinus (const UnaryOperator *E);
336 Value *VisitUnaryNot (const UnaryOperator *E);
337 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000338 Value *VisitUnaryReal (const UnaryOperator *E);
339 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000340 Value *VisitUnaryExtension(const UnaryOperator *E) {
341 return Visit(E->getSubExpr());
342 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000343
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000344 // C++
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000345 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedmanec24b0e2011-08-14 04:50:34 +0000346 return EmitLoadOfLValue(E);
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000347 }
348
Chris Lattner04421082008-04-08 04:40:51 +0000349 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
350 return Visit(DAE->getExpr());
351 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000352 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
353 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000354 }
355
John McCall4765fa02010-12-06 08:20:24 +0000356 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
357 return CGF.EmitExprWithCleanups(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000358 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000359 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
360 return CGF.EmitCXXNewExpr(E);
361 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000362 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
363 CGF.EmitCXXDeleteExpr(E);
364 return 0;
365 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000366 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000367 return Builder.getInt1(E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000368 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000369
Francois Pichet6ad6f282010-12-07 00:08:36 +0000370 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000371 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000372 }
373
John Wiegley21ff2e52011-04-28 00:16:57 +0000374 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
375 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
376 }
377
John Wiegley55262202011-04-25 06:54:41 +0000378 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
379 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
380 }
381
Douglas Gregora71d8192009-09-04 17:36:40 +0000382 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
383 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000384 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000385 // operator (), and the result of such a call has type void. The only
386 // effect is the evaluation of the postfix-expression before the dot or
387 // arrow.
388 CGF.EmitScalarExpr(E->getBase());
389 return 0;
390 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000391
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000392 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000393 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000394 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000395
396 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
397 CGF.EmitCXXThrowExpr(E);
398 return 0;
399 }
400
Sebastian Redl98294de2010-09-10 21:04:00 +0000401 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000402 return Builder.getInt1(E->getValue());
Sebastian Redl98294de2010-09-10 21:04:00 +0000403 }
404
Chris Lattner7f02f722007-08-24 05:35:26 +0000405 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000406 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000407 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000408 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
409 case LangOptions::SOB_Undefined:
410 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
411 case LangOptions::SOB_Defined:
412 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
413 case LangOptions::SOB_Trapping:
414 return EmitOverflowCheckedBinOp(Ops);
415 }
416 }
417
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000418 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000419 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000420 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
421 }
Chris Lattner80230302010-09-11 21:47:09 +0000422 bool isTrapvOverflowBehavior() {
423 return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
424 == LangOptions::SOB_Trapping;
425 }
Mike Stump2add4732009-04-01 20:28:16 +0000426 /// Create a binary op that checks for overflow.
427 /// Currently only supports +, - and *.
428 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner80230302010-09-11 21:47:09 +0000429 // Emit the overflow BB when -ftrapv option is activated.
430 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
431 Builder.SetInsertPoint(overflowBB);
432 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
433 Builder.CreateCall(Trap);
434 Builder.CreateUnreachable();
435 }
436 // Check for undefined division and modulus behaviors.
437 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
438 llvm::Value *Zero,bool isDiv);
Chris Lattner7f02f722007-08-24 05:35:26 +0000439 Value *EmitDiv(const BinOpInfo &Ops);
440 Value *EmitRem(const BinOpInfo &Ops);
441 Value *EmitAdd(const BinOpInfo &Ops);
442 Value *EmitSub(const BinOpInfo &Ops);
443 Value *EmitShl(const BinOpInfo &Ops);
444 Value *EmitShr(const BinOpInfo &Ops);
445 Value *EmitAnd(const BinOpInfo &Ops) {
446 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
447 }
448 Value *EmitXor(const BinOpInfo &Ops) {
449 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
450 }
451 Value *EmitOr (const BinOpInfo &Ops) {
452 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
453 }
454
Chris Lattner1f1ded92007-08-24 21:00:35 +0000455 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000456 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
457 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000458 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000459
Chris Lattner3ccf7742007-08-26 21:41:21 +0000460 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000461 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
462
463 // Binary operators and binary compound assignment operators.
464#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000465 Value *VisitBin ## OP(const BinaryOperator *E) { \
466 return Emit ## OP(EmitBinOps(E)); \
467 } \
468 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
469 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000470 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000471 HANDLEBINOP(Mul)
472 HANDLEBINOP(Div)
473 HANDLEBINOP(Rem)
474 HANDLEBINOP(Add)
475 HANDLEBINOP(Sub)
476 HANDLEBINOP(Shl)
477 HANDLEBINOP(Shr)
478 HANDLEBINOP(And)
479 HANDLEBINOP(Xor)
480 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000481#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000482
Chris Lattner7f02f722007-08-24 05:35:26 +0000483 // Comparisons.
484 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
485 unsigned SICmpOpc, unsigned FCmpOpc);
486#define VISITCOMP(CODE, UI, SI, FP) \
487 Value *VisitBin##CODE(const BinaryOperator *E) { \
488 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
489 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000490 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
491 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
492 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
493 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
494 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
495 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000496#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000497
Chris Lattner7f02f722007-08-24 05:35:26 +0000498 Value *VisitBinAssign (const BinaryOperator *E);
499
500 Value *VisitBinLAnd (const BinaryOperator *E);
501 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000502 Value *VisitBinComma (const BinaryOperator *E);
503
Eli Friedman25b825d2009-11-18 09:41:26 +0000504 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
505 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
506
Chris Lattner7f02f722007-08-24 05:35:26 +0000507 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000508 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000509 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000510 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000511 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000512 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
513 return CGF.EmitObjCStringLiteral(E);
514 }
Tanya Lattner61eee0c2011-06-04 00:47:47 +0000515 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000516};
517} // end anonymous namespace.
518
519//===----------------------------------------------------------------------===//
520// Utilities
521//===----------------------------------------------------------------------===//
522
Chris Lattner9abc84e2007-08-26 16:42:57 +0000523/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000524/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000525Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000526 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000527
John McCalldaa8e4e2010-11-15 09:13:47 +0000528 if (SrcType->isRealFloatingType())
529 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000530
John McCall0bab0cd2010-08-23 01:21:21 +0000531 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
532 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000533
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000534 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000535 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000536
John McCalldaa8e4e2010-11-15 09:13:47 +0000537 if (isa<llvm::IntegerType>(Src->getType()))
538 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000539
John McCalldaa8e4e2010-11-15 09:13:47 +0000540 assert(isa<llvm::PointerType>(Src->getType()));
541 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000542}
543
Chris Lattner3707b252007-08-26 06:48:56 +0000544/// EmitScalarConversion - Emit a conversion from the specified type to the
545/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000546Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
547 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000548 SrcType = CGF.getContext().getCanonicalType(SrcType);
549 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000550 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000551
Chris Lattnercf289082007-08-26 07:21:11 +0000552 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000553
Chris Lattner3707b252007-08-26 06:48:56 +0000554 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000555 if (DstType->isBooleanType())
556 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000557
Chris Lattner2acc6e32011-07-18 04:24:23 +0000558 llvm::Type *DstTy = ConvertType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000559
560 // Ignore conversions like int -> uint.
561 if (Src->getType() == DstTy)
562 return Src;
563
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000564 // Handle pointer conversions next: pointers can only be converted to/from
565 // other pointers and integers. Check for pointer types in terms of LLVM, as
566 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000567 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000568 // The source value may be an integer, or a pointer.
Anders Carlsson191dfe92009-09-12 04:57:16 +0000569 if (isa<llvm::PointerType>(Src->getType()))
Chris Lattner3707b252007-08-26 06:48:56 +0000570 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000571
Chris Lattner3707b252007-08-26 06:48:56 +0000572 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000573 // First, convert to the correct width so that we control the kind of
574 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000575 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000576 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman25615422009-03-04 04:02:35 +0000577 llvm::Value* IntResult =
578 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
579 // Then, cast to pointer.
580 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000581 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000582
Daniel Dunbar270cc662008-08-25 09:51:32 +0000583 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000584 // Must be an ptr to int cast.
585 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000586 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000587 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000588
Nate Begeman213541a2008-04-18 23:10:10 +0000589 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000590 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000591 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000592 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000593 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
594
595 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000596 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +0000597 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +0000598 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000599
600 // Splat the element across to all elements
Chris Lattner5f9e2722011-07-23 10:55:15 +0000601 SmallVector<llvm::Constant*, 16> Args;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000602 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattnerfb018d12011-02-15 00:14:06 +0000603 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner48431f92011-04-19 22:55:03 +0000604 Args.push_back(Builder.getInt32(0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000605
Chris Lattnerfb018d12011-02-15 00:14:06 +0000606 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000607 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
608 return Yay;
609 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000610
Chris Lattner3b1ae002008-02-02 04:51:41 +0000611 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000612 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000613 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000614 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000615
Chris Lattner3707b252007-08-26 06:48:56 +0000616 // Finally, we have the arithmetic types: real int/float.
617 if (isa<llvm::IntegerType>(Src->getType())) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000618 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000619 if (isa<llvm::IntegerType>(DstTy))
620 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
621 else if (InputSigned)
622 return Builder.CreateSIToFP(Src, DstTy, "conv");
623 else
624 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000625 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000626
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000627 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
Chris Lattner3707b252007-08-26 06:48:56 +0000628 if (isa<llvm::IntegerType>(DstTy)) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000629 if (DstType->isSignedIntegerOrEnumerationType())
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000630 return Builder.CreateFPToSI(Src, DstTy, "conv");
631 else
632 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000633 }
634
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000635 assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000636 if (DstTy->getTypeID() < Src->getType()->getTypeID())
637 return Builder.CreateFPTrunc(Src, DstTy, "conv");
638 else
639 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000640}
641
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000642/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
643/// type to the specified destination type, where the destination type is an
644/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000645Value *ScalarExprEmitter::
646EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
647 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000648 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000649 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000650
Chris Lattnered70f0a2007-08-26 16:52:28 +0000651 // Handle conversions to bool first, they are special: comparisons against 0.
652 if (DstTy->isBooleanType()) {
653 // Complex != 0 -> (Real != 0) | (Imag != 0)
654 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
655 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
656 return Builder.CreateOr(Src.first, Src.second, "tobool");
657 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000658
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000659 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
660 // the imaginary part of the complex value is discarded and the value of the
661 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000662 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000663 return EmitScalarConversion(Src.first, SrcTy, DstTy);
664}
665
Anders Carlssona40a9f32010-05-22 17:45:10 +0000666Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000667 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
668 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
669
670 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000671}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000672
Chris Lattner7f02f722007-08-24 05:35:26 +0000673//===----------------------------------------------------------------------===//
674// Visitor Methods
675//===----------------------------------------------------------------------===//
676
677Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000678 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000679 if (E->getType()->isVoidType())
680 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000681 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000682}
683
Eli Friedmand38617c2008-05-14 19:38:39 +0000684Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000685 // Vector Mask Case
686 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000687 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000688 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
689 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
690 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000691
Chris Lattner2acc6e32011-07-18 04:24:23 +0000692 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000693 unsigned LHSElts = LTy->getNumElements();
694
695 if (E->getNumSubExprs() == 3) {
696 Mask = CGF.EmitScalarExpr(E->getExpr(2));
697
698 // Shuffle LHS & RHS into one input vector.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000699 SmallVector<llvm::Constant*, 32> concat;
Nate Begeman37b6a572010-06-08 00:16:34 +0000700 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000701 concat.push_back(Builder.getInt32(2*i));
702 concat.push_back(Builder.getInt32(2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000703 }
704
Chris Lattnerfb018d12011-02-15 00:14:06 +0000705 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000706 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
707 LHSElts *= 2;
708 } else {
709 Mask = RHS;
710 }
711
Chris Lattner2acc6e32011-07-18 04:24:23 +0000712 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000713 llvm::Constant* EltMask;
714
715 // Treat vec3 like vec4.
716 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
717 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
718 (1 << llvm::Log2_32(LHSElts+2))-1);
719 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
720 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
721 (1 << llvm::Log2_32(LHSElts+1))-1);
722 else
723 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
724 (1 << llvm::Log2_32(LHSElts))-1);
725
726 // Mask off the high bits of each shuffle index.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000727 SmallVector<llvm::Constant *, 32> MaskV;
Nate Begeman37b6a572010-06-08 00:16:34 +0000728 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
729 MaskV.push_back(EltMask);
730
Chris Lattnerfb018d12011-02-15 00:14:06 +0000731 Value* MaskBits = llvm::ConstantVector::get(MaskV);
Nate Begeman37b6a572010-06-08 00:16:34 +0000732 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
733
734 // newv = undef
735 // mask = mask & maskbits
736 // for each elt
737 // n = extract mask i
738 // x = extract val n
739 // newv = insert newv, x, i
Chris Lattner2acc6e32011-07-18 04:24:23 +0000740 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000741 MTy->getNumElements());
742 Value* NewV = llvm::UndefValue::get(RTy);
743 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000744 Value *Indx = Builder.getInt32(i);
Nate Begeman37b6a572010-06-08 00:16:34 +0000745 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000746 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000747
748 // Handle vec3 special since the index will be off by one for the RHS.
749 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
750 Value *cmpIndx, *newIndx;
Chris Lattner48431f92011-04-19 22:55:03 +0000751 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000752 "cmp_shuf_idx");
Chris Lattner48431f92011-04-19 22:55:03 +0000753 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
Nate Begeman37b6a572010-06-08 00:16:34 +0000754 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
755 }
756 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
757 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
758 }
759 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000760 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000761
Eli Friedmand38617c2008-05-14 19:38:39 +0000762 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
763 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000764
765 // Handle vec3 special since the index will be off by one for the RHS.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000766 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000767 SmallVector<llvm::Constant*, 32> indices;
Nate Begeman37b6a572010-06-08 00:16:34 +0000768 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
Eli Friedman0eb47fc2011-05-19 00:37:32 +0000769 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
770 if (VTy->getNumElements() == 3 && Idx > 3)
771 Idx -= 1;
772 indices.push_back(Builder.getInt32(Idx));
Nate Begeman37b6a572010-06-08 00:16:34 +0000773 }
774
Chris Lattnerfb018d12011-02-15 00:14:06 +0000775 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000776 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
777}
Eli Friedman28665272009-11-26 03:22:21 +0000778Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
779 Expr::EvalResult Result;
780 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
781 if (E->isArrow())
782 CGF.EmitScalarExpr(E->getBase());
783 else
784 EmitLValue(E->getBase());
Chris Lattner48431f92011-04-19 22:55:03 +0000785 return Builder.getInt(Result.Val.getInt());
Eli Friedman28665272009-11-26 03:22:21 +0000786 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000787
788 // Emit debug info for aggregate now, if it was delayed to reduce
789 // debug info size.
790 CGDebugInfo *DI = CGF.getDebugInfo();
791 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
792 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
793 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000794 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Devang Patel78ba3d42010-10-04 21:46:04 +0000795 DI->getOrCreateRecordType(PTy->getPointeeType(),
796 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000797 }
Eli Friedman28665272009-11-26 03:22:21 +0000798 return EmitLoadOfLValue(E);
799}
Eli Friedmand38617c2008-05-14 19:38:39 +0000800
Chris Lattner7f02f722007-08-24 05:35:26 +0000801Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000802 TestAndClearIgnoreResultAssign();
803
Chris Lattner7f02f722007-08-24 05:35:26 +0000804 // Emit subscript expressions in rvalue context's. For most cases, this just
805 // loads the lvalue formed by the subscript expr. However, we have to be
806 // careful, because the base of a vector subscript is occasionally an rvalue,
807 // so we can't get it as an lvalue.
808 if (!E->getBase()->getType()->isVectorType())
809 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000810
Chris Lattner7f02f722007-08-24 05:35:26 +0000811 // Handle the vector case. The base must be a vector, the index must be an
812 // integer value.
813 Value *Base = Visit(E->getBase());
814 Value *Idx = Visit(E->getIdx());
Douglas Gregor575a1c92011-05-20 16:38:50 +0000815 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000816 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000817 return Builder.CreateExtractElement(Base, Idx, "vecext");
818}
819
Nate Begeman0533b302009-10-18 20:10:40 +0000820static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000821 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman0533b302009-10-18 20:10:40 +0000822 int MV = SVI->getMaskValue(Idx);
823 if (MV == -1)
824 return llvm::UndefValue::get(I32Ty);
825 return llvm::ConstantInt::get(I32Ty, Off+MV);
826}
827
828Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
829 bool Ignore = TestAndClearIgnoreResultAssign();
830 (void)Ignore;
831 assert (Ignore == false && "init list ignored");
832 unsigned NumInitElements = E->getNumInits();
833
834 if (E->hadArrayRangeDesignator())
835 CGF.ErrorUnsupported(E, "GNU array range designator extension");
836
Chris Lattner2acc6e32011-07-18 04:24:23 +0000837 llvm::VectorType *VType =
Nate Begeman0533b302009-10-18 20:10:40 +0000838 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
839
Sebastian Redlcea8d962011-09-24 17:48:14 +0000840 if (!VType) {
841 if (NumInitElements == 0) {
842 // C++11 value-initialization for the scalar.
843 return EmitNullValue(E->getType());
844 }
845 // We have a scalar in braces. Just use the first element.
Nate Begeman0533b302009-10-18 20:10:40 +0000846 return Visit(E->getInit(0));
Sebastian Redlcea8d962011-09-24 17:48:14 +0000847 }
Nate Begeman0533b302009-10-18 20:10:40 +0000848
849 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000850
851 // Loop over initializers collecting the Value for each, and remembering
852 // whether the source was swizzle (ExtVectorElementExpr). This will allow
853 // us to fold the shuffle for the swizzle into the shuffle for the vector
854 // initializer, since LLVM optimizers generally do not want to touch
855 // shuffles.
856 unsigned CurIdx = 0;
857 bool VIsUndefShuffle = false;
858 llvm::Value *V = llvm::UndefValue::get(VType);
859 for (unsigned i = 0; i != NumInitElements; ++i) {
860 Expr *IE = E->getInit(i);
861 Value *Init = Visit(IE);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000862 SmallVector<llvm::Constant*, 16> Args;
Nate Begeman0533b302009-10-18 20:10:40 +0000863
Chris Lattner2acc6e32011-07-18 04:24:23 +0000864 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000865
866 // Handle scalar elements. If the scalar initializer is actually one
867 // element of a different vector of the same width, use shuffle instead of
868 // extract+insert.
869 if (!VVT) {
870 if (isa<ExtVectorElementExpr>(IE)) {
871 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
872
873 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
874 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
875 Value *LHS = 0, *RHS = 0;
876 if (CurIdx == 0) {
877 // insert into undef -> shuffle (src, undef)
878 Args.push_back(C);
879 for (unsigned j = 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000880 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000881
882 LHS = EI->getVectorOperand();
883 RHS = V;
884 VIsUndefShuffle = true;
885 } else if (VIsUndefShuffle) {
886 // insert into undefshuffle && size match -> shuffle (v, src)
887 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
888 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000889 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner48431f92011-04-19 22:55:03 +0000890 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Nate Begeman0533b302009-10-18 20:10:40 +0000891 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000892 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000893
894 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
895 RHS = EI->getVectorOperand();
896 VIsUndefShuffle = false;
897 }
898 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +0000899 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000900 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
901 ++CurIdx;
902 continue;
903 }
904 }
905 }
Chris Lattner48431f92011-04-19 22:55:03 +0000906 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
907 "vecinit");
Nate Begeman0533b302009-10-18 20:10:40 +0000908 VIsUndefShuffle = false;
909 ++CurIdx;
910 continue;
911 }
912
913 unsigned InitElts = VVT->getNumElements();
914
915 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
916 // input is the same width as the vector being constructed, generate an
917 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000918 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000919 if (isa<ExtVectorElementExpr>(IE)) {
920 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
921 Value *SVOp = SVI->getOperand(0);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000922 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000923
924 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000925 for (unsigned j = 0; j != CurIdx; ++j) {
926 // If the current vector initializer is a shuffle with undef, merge
927 // this shuffle directly into it.
928 if (VIsUndefShuffle) {
929 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000930 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000931 } else {
Chris Lattner48431f92011-04-19 22:55:03 +0000932 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000933 }
934 }
935 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000936 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000937 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000938 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000939
940 if (VIsUndefShuffle)
941 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
942
943 Init = SVOp;
944 }
945 }
946
947 // Extend init to result vector length, and then shuffle its contribution
948 // to the vector initializer into V.
949 if (Args.empty()) {
950 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000951 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000952 for (unsigned j = InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000953 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +0000954 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000955 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000956 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000957
958 Args.clear();
959 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000960 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000961 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000962 Args.push_back(Builder.getInt32(j+Offset));
Nate Begeman0533b302009-10-18 20:10:40 +0000963 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000964 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000965 }
966
967 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
968 // merging subsequent shuffles into this one.
969 if (CurIdx == 0)
970 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +0000971 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000972 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
973 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
974 CurIdx += InitElts;
975 }
976
977 // FIXME: evaluate codegen vs. shuffling against constant null vector.
978 // Emit remaining default initializers.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000979 llvm::Type *EltTy = VType->getElementType();
Nate Begeman0533b302009-10-18 20:10:40 +0000980
981 // Emit remaining default initializers
982 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner48431f92011-04-19 22:55:03 +0000983 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000984 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
985 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
986 }
987 return V;
988}
989
Anders Carlssona3697c92009-11-23 17:57:54 +0000990static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
991 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +0000992
John McCall2de56d12010-08-25 11:45:40 +0000993 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +0000994 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +0000995
996 if (isa<CXXThisExpr>(E)) {
997 // We always assume that 'this' is never null.
998 return false;
999 }
1000
1001 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00001002 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +00001003 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +00001004 return false;
1005 }
1006
1007 return true;
1008}
1009
Chris Lattner7f02f722007-08-24 05:35:26 +00001010// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1011// have to handle a more broad range of conversions than explicit casts, as they
1012// handle things like function to ptr-to-function decay etc.
John McCallbc8d40d2011-06-24 21:55:10 +00001013Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmand8889622009-11-27 04:41:50 +00001014 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001015 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001016 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001017
Mike Stump7f79f9b2009-05-29 15:46:01 +00001018 if (!DestTy->isVoidType())
1019 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001020
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001021 // Since almost all cast kinds apply to scalars, this switch doesn't have
1022 // a default case, so the compiler will warn on a missing case. The cases
1023 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001024 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001025 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1026
John McCall2de56d12010-08-25 11:45:40 +00001027 case CK_LValueBitCast:
1028 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001029 Value *V = EmitLValue(E).getAddress();
1030 V = Builder.CreateBitCast(V,
1031 ConvertType(CGF.getContext().getPointerType(DestTy)));
John McCall545d9962011-06-25 02:11:03 +00001032 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy));
Douglas Gregore39a3892010-07-13 23:17:26 +00001033 }
John McCalldc05b112011-09-10 01:16:55 +00001034
John McCall1d9b3b22011-09-09 05:25:32 +00001035 case CK_CPointerToObjCPointerCast:
1036 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001037 case CK_AnyPointerToBlockPointerCast:
1038 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001039 Value *Src = Visit(const_cast<Expr*>(E));
1040 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1041 }
John McCall2de56d12010-08-25 11:45:40 +00001042 case CK_NoOp:
1043 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001044 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001045
John McCall2de56d12010-08-25 11:45:40 +00001046 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +00001047 const CXXRecordDecl *DerivedClassDecl =
1048 DestTy->getCXXRecordDeclForPointerType();
1049
Anders Carlssona04efdf2010-04-24 21:23:59 +00001050 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001051 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001052 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001053 }
John McCall2de56d12010-08-25 11:45:40 +00001054 case CK_UncheckedDerivedToBase:
1055 case CK_DerivedToBase: {
Anders Carlsson191dfe92009-09-12 04:57:16 +00001056 const RecordType *DerivedClassTy =
1057 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1058 CXXRecordDecl *DerivedClassDecl =
1059 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1060
Anders Carlsson34a2d382010-04-24 21:06:20 +00001061 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001062 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001063 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001064 }
Anders Carlsson575b3742011-04-11 02:03:26 +00001065 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001066 Value *V = Visit(const_cast<Expr*>(E));
1067 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1068 return CGF.EmitDynamicCast(V, DCE);
1069 }
Eli Friedmand8889622009-11-27 04:41:50 +00001070
John McCall2de56d12010-08-25 11:45:40 +00001071 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001072 assert(E->getType()->isArrayType() &&
1073 "Array to pointer decay must have array source type!");
1074
1075 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1076
1077 // Note that VLA pointers are always decayed, so we don't need to do
1078 // anything here.
1079 if (!E->getType()->isVariableArrayType()) {
1080 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1081 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1082 ->getElementType()) &&
1083 "Expected pointer to array");
1084 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1085 }
1086
Chris Lattner410b12e2011-07-20 04:31:01 +00001087 // Make sure the array decay ends up being the right type. This matters if
1088 // the array type was of an incomplete type.
Chris Lattnercb8095f2011-07-20 04:59:57 +00001089 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
Eli Friedmanad35a832009-11-16 21:33:53 +00001090 }
John McCall2de56d12010-08-25 11:45:40 +00001091 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001092 return EmitLValue(E).getAddress();
1093
John McCall404cd162010-11-13 01:35:44 +00001094 case CK_NullToPointer:
1095 if (MustVisitNullValue(E))
1096 (void) Visit(E);
1097
1098 return llvm::ConstantPointerNull::get(
1099 cast<llvm::PointerType>(ConvertType(DestTy)));
1100
John McCall2de56d12010-08-25 11:45:40 +00001101 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001102 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001103 (void) Visit(E);
1104
John McCall0bab0cd2010-08-23 01:21:21 +00001105 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1106 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1107 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001108
John McCall2de56d12010-08-25 11:45:40 +00001109 case CK_BaseToDerivedMemberPointer:
1110 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001111 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001112
1113 // Note that the AST doesn't distinguish between checked and
1114 // unchecked member pointer conversions, so we always have to
1115 // implement checked conversions here. This is inefficient when
1116 // actual control flow may be required in order to perform the
1117 // check, which it is for data member pointers (but not member
1118 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001119 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001120 }
John McCallf85e1932011-06-15 23:02:42 +00001121
John McCall33e56f32011-09-10 06:18:15 +00001122 case CK_ARCProduceObject:
John McCallf85e1932011-06-15 23:02:42 +00001123 return CGF.EmitARCRetainScalarExpr(E);
John McCall33e56f32011-09-10 06:18:15 +00001124 case CK_ARCConsumeObject:
John McCallf85e1932011-06-15 23:02:42 +00001125 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall33e56f32011-09-10 06:18:15 +00001126 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00001127 llvm::Value *value = Visit(E);
1128 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1129 return CGF.EmitObjCConsumeObject(E->getType(), value);
1130 }
John McCall348f16f2011-10-04 06:23:45 +00001131 case CK_ARCExtendBlockObject:
1132 return CGF.EmitARCExtendBlockObject(E);
John McCallf85e1932011-06-15 23:02:42 +00001133
John McCall2bb5d002010-11-13 09:02:35 +00001134 case CK_FloatingRealToComplex:
1135 case CK_FloatingComplexCast:
1136 case CK_IntegralRealToComplex:
1137 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001138 case CK_IntegralComplexToFloatingComplex:
1139 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001140 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001141 case CK_ToUnion:
1142 llvm_unreachable("scalar cast to non-scalar value");
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001143 break;
John McCallf6a16482010-12-04 03:47:34 +00001144
1145 case CK_GetObjCProperty: {
1146 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
Douglas Gregorda29e092011-01-22 02:44:21 +00001147 assert(E->isGLValue() && E->getObjectKind() == OK_ObjCProperty &&
John McCallf6a16482010-12-04 03:47:34 +00001148 "CK_GetObjCProperty for non-lvalue or non-ObjCProperty");
John McCall545d9962011-06-25 02:11:03 +00001149 RValue RV = CGF.EmitLoadOfLValue(CGF.EmitLValue(E));
John McCallf6a16482010-12-04 03:47:34 +00001150 return RV.getScalarVal();
1151 }
John McCall1de4d4e2011-04-07 08:22:57 +00001152
John McCall0ae287a2010-12-01 04:43:34 +00001153 case CK_LValueToRValue:
1154 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001155 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001156 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001157
John McCall2de56d12010-08-25 11:45:40 +00001158 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001159 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001160
Anders Carlsson82debc72009-10-18 18:12:03 +00001161 // First, convert to the correct width so that we control the kind of
1162 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001163 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +00001164 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson82debc72009-10-18 18:12:03 +00001165 llvm::Value* IntResult =
1166 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001167
Anders Carlsson82debc72009-10-18 18:12:03 +00001168 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001169 }
Eli Friedman65949422011-06-25 02:58:47 +00001170 case CK_PointerToIntegral:
1171 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1172 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001173
John McCall2de56d12010-08-25 11:45:40 +00001174 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001175 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001176 return 0;
1177 }
John McCall2de56d12010-08-25 11:45:40 +00001178 case CK_VectorSplat: {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001179 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001180 Value *Elt = Visit(const_cast<Expr*>(E));
1181
1182 // Insert the element in element zero of an undef vector
1183 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +00001184 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +00001185 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Eli Friedmanad35a832009-11-16 21:33:53 +00001186
1187 // Splat the element across to all elements
Chris Lattner5f9e2722011-07-23 10:55:15 +00001188 SmallVector<llvm::Constant*, 16> Args;
Eli Friedmanad35a832009-11-16 21:33:53 +00001189 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner48431f92011-04-19 22:55:03 +00001190 llvm::Constant *Zero = Builder.getInt32(0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001191 for (unsigned i = 0; i < NumElements; i++)
John McCalldaa8e4e2010-11-15 09:13:47 +00001192 Args.push_back(Zero);
Eli Friedmanad35a832009-11-16 21:33:53 +00001193
Chris Lattnerfb018d12011-02-15 00:14:06 +00001194 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Eli Friedmanad35a832009-11-16 21:33:53 +00001195 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1196 return Yay;
1197 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001198
John McCall2de56d12010-08-25 11:45:40 +00001199 case CK_IntegralCast:
1200 case CK_IntegralToFloating:
1201 case CK_FloatingToIntegral:
1202 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001203 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001204
John McCalldaa8e4e2010-11-15 09:13:47 +00001205 case CK_IntegralToBoolean:
1206 return EmitIntToBoolConversion(Visit(E));
1207 case CK_PointerToBoolean:
1208 return EmitPointerToBoolConversion(Visit(E));
1209 case CK_FloatingToBoolean:
1210 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001211 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001212 llvm::Value *MemPtr = Visit(E);
1213 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1214 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001215 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001216
1217 case CK_FloatingComplexToReal:
1218 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001219 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001220
1221 case CK_FloatingComplexToBoolean:
1222 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001223 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001224
1225 // TODO: kill this function off, inline appropriate case here
1226 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1227 }
1228
John McCall0bab0cd2010-08-23 01:21:21 +00001229 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001230
John McCall61ad0e62010-11-16 06:21:14 +00001231 llvm_unreachable("unknown scalar cast");
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001232 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +00001233}
1234
Chris Lattner33793202007-08-31 22:09:40 +00001235Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001236 CodeGenFunction::StmtExprEvaluation eval(CGF);
1237 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1238 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001239}
1240
Mike Stumpa99038c2009-02-28 09:07:16 +00001241Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
John McCalla5bcb8f2011-03-16 02:53:38 +00001242 LValue LV = CGF.EmitBlockDeclRefLValue(E);
John McCall545d9962011-06-25 02:11:03 +00001243 return CGF.EmitLoadOfLValue(LV).getScalarVal();
Mike Stump4e7a1f72009-02-21 20:00:35 +00001244}
Chris Lattner33793202007-08-31 22:09:40 +00001245
Chris Lattner7f02f722007-08-24 05:35:26 +00001246//===----------------------------------------------------------------------===//
1247// Unary Operators
1248//===----------------------------------------------------------------------===//
1249
Chris Lattner8c11a652010-06-26 22:09:34 +00001250llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001251EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1252 llvm::Value *InVal,
1253 llvm::Value *NextVal, bool IsInc) {
1254 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1255 case LangOptions::SOB_Undefined:
1256 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1257 break;
1258 case LangOptions::SOB_Defined:
1259 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1260 break;
1261 case LangOptions::SOB_Trapping:
1262 BinOpInfo BinOp;
1263 BinOp.LHS = InVal;
1264 BinOp.RHS = NextVal;
1265 BinOp.Ty = E->getType();
1266 BinOp.Opcode = BO_Add;
1267 BinOp.E = E;
1268 return EmitOverflowCheckedBinOp(BinOp);
Anton Yartsev683564a2011-02-07 02:17:30 +00001269 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001270 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev683564a2011-02-07 02:17:30 +00001271}
1272
John McCall5936e332011-02-15 09:22:45 +00001273llvm::Value *
1274ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1275 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001276
John McCall5936e332011-02-15 09:22:45 +00001277 QualType type = E->getSubExpr()->getType();
John McCall545d9962011-06-25 02:11:03 +00001278 llvm::Value *value = EmitLoadOfLValue(LV);
John McCall5936e332011-02-15 09:22:45 +00001279 llvm::Value *input = value;
Anton Yartsev683564a2011-02-07 02:17:30 +00001280
John McCall5936e332011-02-15 09:22:45 +00001281 int amount = (isInc ? 1 : -1);
1282
1283 // Special case of integer increment that we have to check first: bool++.
1284 // Due to promotion rules, we get:
1285 // bool++ -> bool = bool + 1
1286 // -> bool = (int)bool + 1
1287 // -> bool = ((int)bool + 1 != 0)
1288 // An interesting aspect of this is that increment is always true.
1289 // Decrement does not have this property.
1290 if (isInc && type->isBooleanType()) {
1291 value = Builder.getTrue();
1292
1293 // Most common case by far: integer increment.
1294 } else if (type->isIntegerType()) {
1295
1296 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1297
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001298 // Note that signed integer inc/dec with width less than int can't
1299 // overflow because of promotion rules; we're just eliding a few steps here.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001300 if (type->isSignedIntegerOrEnumerationType() &&
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001301 value->getType()->getPrimitiveSizeInBits() >=
John McCall913dab22011-06-25 01:32:37 +00001302 CGF.IntTy->getBitWidth())
John McCall5936e332011-02-15 09:22:45 +00001303 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
John McCall5936e332011-02-15 09:22:45 +00001304 else
1305 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1306
1307 // Next most common: pointer increment.
1308 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1309 QualType type = ptr->getPointeeType();
1310
1311 // VLA types don't have constant size.
John McCall913dab22011-06-25 01:32:37 +00001312 if (const VariableArrayType *vla
1313 = CGF.getContext().getAsVariableArrayType(type)) {
1314 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCallbc8d40d2011-06-24 21:55:10 +00001315 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Chris Lattner2cb42222011-03-01 00:03:48 +00001316 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
John McCallbc8d40d2011-06-24 21:55:10 +00001317 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2cb42222011-03-01 00:03:48 +00001318 else
John McCallbc8d40d2011-06-24 21:55:10 +00001319 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
John McCall5936e332011-02-15 09:22:45 +00001320
1321 // Arithmetic on function pointers (!) is just +-1.
1322 } else if (type->isFunctionType()) {
Chris Lattner48431f92011-04-19 22:55:03 +00001323 llvm::Value *amt = Builder.getInt32(amount);
John McCall5936e332011-02-15 09:22:45 +00001324
1325 value = CGF.EmitCastToVoidPtr(value);
Chris Lattner2cb42222011-03-01 00:03:48 +00001326 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1327 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1328 else
1329 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001330 value = Builder.CreateBitCast(value, input->getType());
1331
1332 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001333 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001334 llvm::Value *amt = Builder.getInt32(amount);
Chris Lattner2cb42222011-03-01 00:03:48 +00001335 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1336 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1337 else
1338 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001339 }
1340
1341 // Vector increment/decrement.
1342 } else if (type->isVectorType()) {
1343 if (type->hasIntegerRepresentation()) {
1344 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1345
Eli Friedmand4b9ee32011-05-06 18:04:18 +00001346 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCall5936e332011-02-15 09:22:45 +00001347 } else {
1348 value = Builder.CreateFAdd(
1349 value,
1350 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001351 isInc ? "inc" : "dec");
1352 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001353
John McCall5936e332011-02-15 09:22:45 +00001354 // Floating point.
1355 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001356 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001357 llvm::Value *amt;
1358 if (value->getType()->isFloatTy())
1359 amt = llvm::ConstantFP::get(VMContext,
1360 llvm::APFloat(static_cast<float>(amount)));
1361 else if (value->getType()->isDoubleTy())
1362 amt = llvm::ConstantFP::get(VMContext,
1363 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001364 else {
John McCall5936e332011-02-15 09:22:45 +00001365 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001366 bool ignored;
1367 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1368 &ignored);
John McCall5936e332011-02-15 09:22:45 +00001369 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001370 }
John McCall5936e332011-02-15 09:22:45 +00001371 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1372
1373 // Objective-C pointer types.
1374 } else {
1375 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1376 value = CGF.EmitCastToVoidPtr(value);
1377
1378 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1379 if (!isInc) size = -size;
1380 llvm::Value *sizeValue =
1381 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1382
Chris Lattner2cb42222011-03-01 00:03:48 +00001383 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1384 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1385 else
1386 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001387 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001388 }
1389
1390 // Store the updated result through the lvalue.
1391 if (LV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001392 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001393 else
John McCall545d9962011-06-25 02:11:03 +00001394 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Chris Lattner8c11a652010-06-26 22:09:34 +00001395
1396 // If this is a postinc, return the value read from memory, otherwise use the
1397 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001398 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001399}
1400
1401
1402
Chris Lattner7f02f722007-08-24 05:35:26 +00001403Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001404 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001405 // Emit unary minus with EmitSub so we handle overflow cases etc.
1406 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001407 BinOp.RHS = Visit(E->getSubExpr());
1408
1409 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1410 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1411 else
1412 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001413 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001414 BinOp.Opcode = BO_Sub;
Chris Lattner9a207232010-06-26 21:48:21 +00001415 BinOp.E = E;
1416 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001417}
1418
1419Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001420 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001421 Value *Op = Visit(E->getSubExpr());
1422 return Builder.CreateNot(Op, "neg");
1423}
1424
1425Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1426 // Compare operand to zero.
1427 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001428
Chris Lattner7f02f722007-08-24 05:35:26 +00001429 // Invert value.
1430 // TODO: Could dynamically modify easy computations here. For example, if
1431 // the operand is an icmp ne, turn into icmp eq.
1432 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001433
Anders Carlsson9f84d882009-05-19 18:44:53 +00001434 // ZExt result to the expr type.
1435 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001436}
1437
Eli Friedman0027d2b2010-08-05 09:58:49 +00001438Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1439 // Try folding the offsetof to a constant.
1440 Expr::EvalResult EvalResult;
1441 if (E->Evaluate(EvalResult, CGF.getContext()))
Chris Lattner48431f92011-04-19 22:55:03 +00001442 return Builder.getInt(EvalResult.Val.getInt());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001443
1444 // Loop over the components of the offsetof to compute the value.
1445 unsigned n = E->getNumComponents();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001446 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001447 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1448 QualType CurrentType = E->getTypeSourceInfo()->getType();
1449 for (unsigned i = 0; i != n; ++i) {
1450 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001451 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001452 switch (ON.getKind()) {
1453 case OffsetOfExpr::OffsetOfNode::Array: {
1454 // Compute the index
1455 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1456 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001457 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedman0027d2b2010-08-05 09:58:49 +00001458 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1459
1460 // Save the element type
1461 CurrentType =
1462 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1463
1464 // Compute the element size
1465 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1466 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1467
1468 // Multiply out to compute the result
1469 Offset = Builder.CreateMul(Idx, ElemSize);
1470 break;
1471 }
1472
1473 case OffsetOfExpr::OffsetOfNode::Field: {
1474 FieldDecl *MemberDecl = ON.getField();
1475 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1476 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1477
1478 // Compute the index of the field in its parent.
1479 unsigned i = 0;
1480 // FIXME: It would be nice if we didn't have to loop here!
1481 for (RecordDecl::field_iterator Field = RD->field_begin(),
1482 FieldEnd = RD->field_end();
1483 Field != FieldEnd; (void)++Field, ++i) {
1484 if (*Field == MemberDecl)
1485 break;
1486 }
1487 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1488
1489 // Compute the offset to the field
1490 int64_t OffsetInt = RL.getFieldOffset(i) /
1491 CGF.getContext().getCharWidth();
1492 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1493
1494 // Save the element type.
1495 CurrentType = MemberDecl->getType();
1496 break;
1497 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001498
Eli Friedman0027d2b2010-08-05 09:58:49 +00001499 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001500 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001501
Eli Friedman0027d2b2010-08-05 09:58:49 +00001502 case OffsetOfExpr::OffsetOfNode::Base: {
1503 if (ON.getBase()->isVirtual()) {
1504 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1505 continue;
1506 }
1507
1508 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1509 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1510
1511 // Save the element type.
1512 CurrentType = ON.getBase()->getType();
1513
1514 // Compute the offset to the base.
1515 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1516 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Anders Carlssona14f5972010-10-31 23:22:37 +00001517 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
Eli Friedman0027d2b2010-08-05 09:58:49 +00001518 CGF.getContext().getCharWidth();
1519 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1520 break;
1521 }
1522 }
1523 Result = Builder.CreateAdd(Result, Offset);
1524 }
1525 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001526}
1527
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001528/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001529/// argument of the sizeof expression as an integer.
1530Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001531ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1532 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001533 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001534 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001535 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001536 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1537 if (E->isArgumentType()) {
1538 // sizeof(type) - make sure to emit the VLA size.
John McCallbc8d40d2011-06-24 21:55:10 +00001539 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001540 } else {
1541 // C99 6.5.3.4p2: If the argument is an expression of type
1542 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001543 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001544 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001545
John McCallbc8d40d2011-06-24 21:55:10 +00001546 QualType eltType;
1547 llvm::Value *numElts;
1548 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1549
1550 llvm::Value *size = numElts;
1551
1552 // Scale the number of non-VLA elements by the non-VLA element size.
1553 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1554 if (!eltSize.isOne())
1555 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1556
1557 return size;
Anders Carlssonb50525b2008-12-21 03:33:21 +00001558 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001559 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001560
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001561 // If this isn't sizeof(vla), the result must be constant; use the constant
1562 // folding logic so we don't have to duplicate it here.
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001563 Expr::EvalResult Result;
1564 E->Evaluate(Result, CGF.getContext());
Chris Lattner48431f92011-04-19 22:55:03 +00001565 return Builder.getInt(Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +00001566}
1567
Chris Lattner46f93d02007-08-24 21:20:17 +00001568Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1569 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001570 if (Op->getType()->isAnyComplexType()) {
1571 // If it's an l-value, load through the appropriate subobject l-value.
1572 // Note that we have to ask E because Op might be an l-value that
1573 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001574 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001575 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001576
1577 // Otherwise, calculate and project.
1578 return CGF.EmitComplexExpr(Op, false, true).first;
1579 }
1580
Chris Lattner46f93d02007-08-24 21:20:17 +00001581 return Visit(Op);
1582}
John McCallb418d742010-11-16 10:08:07 +00001583
Chris Lattner46f93d02007-08-24 21:20:17 +00001584Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1585 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001586 if (Op->getType()->isAnyComplexType()) {
1587 // If it's an l-value, load through the appropriate subobject l-value.
1588 // Note that we have to ask E because Op might be an l-value that
1589 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001590 if (Op->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001591 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001592
1593 // Otherwise, calculate and project.
1594 return CGF.EmitComplexExpr(Op, true, false).second;
1595 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001596
Mike Stump7f79f9b2009-05-29 15:46:01 +00001597 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1598 // effects are evaluated, but not the actual value.
John McCallb418d742010-11-16 10:08:07 +00001599 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001600 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001601}
1602
Chris Lattner7f02f722007-08-24 05:35:26 +00001603//===----------------------------------------------------------------------===//
1604// Binary Operators
1605//===----------------------------------------------------------------------===//
1606
1607BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001608 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001609 BinOpInfo Result;
1610 Result.LHS = Visit(E->getLHS());
1611 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001612 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001613 Result.Opcode = E->getOpcode();
Chris Lattner7f02f722007-08-24 05:35:26 +00001614 Result.E = E;
1615 return Result;
1616}
1617
Douglas Gregor6a03e342010-04-23 04:16:32 +00001618LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1619 const CompoundAssignOperator *E,
1620 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001621 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001622 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001623 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001624
Eli Friedmanab3a8522009-03-28 01:22:36 +00001625 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001626 // This needs to go through the complex expression emitter, but it's a tad
1627 // complicated to do that... I'm leaving it out for now. (Note that we do
1628 // actually need the imaginary part of the RHS for multiplication and
1629 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001630 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001631 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001632 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001633 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001634
Mike Stumpcc0442f2009-05-22 19:07:20 +00001635 // Emit the RHS first. __block variables need to have the rhs evaluated
1636 // first, plus this should improve codegen a little.
1637 OpInfo.RHS = Visit(E->getRHS());
1638 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001639 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001640 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001641 // Load/convert the LHS.
Mike Stumpb14e62d2009-12-16 02:57:00 +00001642 LValue LHSLV = EmitCheckedLValue(E->getLHS());
John McCall545d9962011-06-25 02:11:03 +00001643 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
Eli Friedmanab3a8522009-03-28 01:22:36 +00001644 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1645 E->getComputationLHSType());
Douglas Gregor6a03e342010-04-23 04:16:32 +00001646
Chris Lattner1f1ded92007-08-24 21:00:35 +00001647 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001648 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001649
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001650 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001651 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001652
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001653 // Store the result value into the LHS lvalue. Bit-fields are handled
1654 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1655 // 'An assignment expression has the value of the left operand after the
1656 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001657 if (LHSLV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001658 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001659 else
John McCall545d9962011-06-25 02:11:03 +00001660 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001661
Douglas Gregor6a03e342010-04-23 04:16:32 +00001662 return LHSLV;
1663}
1664
1665Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1666 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1667 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001668 Value *RHS;
1669 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1670
1671 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001672 if (Ignore)
1673 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001674
John McCallb418d742010-11-16 10:08:07 +00001675 // The result of an assignment in C is the assigned r-value.
1676 if (!CGF.getContext().getLangOptions().CPlusPlus)
1677 return RHS;
1678
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001679 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00001680 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001681 return RHS;
1682
1683 // If the lvalue is non-volatile, return the computed value of the assignment.
1684 if (!LHS.isVolatileQualified())
1685 return RHS;
1686
1687 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00001688 return EmitLoadOfLValue(LHS);
Chris Lattner1f1ded92007-08-24 21:00:35 +00001689}
1690
Chris Lattner80230302010-09-11 21:47:09 +00001691void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1692 const BinOpInfo &Ops,
1693 llvm::Value *Zero, bool isDiv) {
Bill Wendling14ef3192011-07-07 21:13:10 +00001694 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
Chris Lattner80230302010-09-11 21:47:09 +00001695 llvm::BasicBlock *contBB =
Bill Wendling14ef3192011-07-07 21:13:10 +00001696 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn,
1697 llvm::next(insertPt));
1698 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Chris Lattner80230302010-09-11 21:47:09 +00001699
Chris Lattner2acc6e32011-07-18 04:24:23 +00001700 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
Chris Lattner80230302010-09-11 21:47:09 +00001701
1702 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1703 llvm::Value *IntMin =
Chris Lattner48431f92011-04-19 22:55:03 +00001704 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner80230302010-09-11 21:47:09 +00001705 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1706
1707 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1708 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1709 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1710 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1711 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1712 overflowBB, contBB);
1713 } else {
1714 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1715 overflowBB, contBB);
1716 }
1717 EmitOverflowBB(overflowBB);
1718 Builder.SetInsertPoint(contBB);
1719}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001720
Chris Lattner7f02f722007-08-24 05:35:26 +00001721Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Chris Lattner80230302010-09-11 21:47:09 +00001722 if (isTrapvOverflowBehavior()) {
1723 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1724
1725 if (Ops.Ty->isIntegerType())
1726 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1727 else if (Ops.Ty->isRealFloatingType()) {
Bill Wendling14ef3192011-07-07 21:13:10 +00001728 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
1729 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn,
1730 llvm::next(insertPt));
Chris Lattner80230302010-09-11 21:47:09 +00001731 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1732 CGF.CurFn);
Chris Lattner80230302010-09-11 21:47:09 +00001733 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1734 overflowBB, DivCont);
1735 EmitOverflowBB(overflowBB);
1736 Builder.SetInsertPoint(DivCont);
1737 }
1738 }
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001739 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner7f02f722007-08-24 05:35:26 +00001740 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Douglas Gregorf6094622010-07-23 15:58:24 +00001741 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001742 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1743 else
1744 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1745}
1746
1747Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1748 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner80230302010-09-11 21:47:09 +00001749 if (isTrapvOverflowBehavior()) {
1750 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1751
1752 if (Ops.Ty->isIntegerType())
1753 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1754 }
1755
Eli Friedman52d68742011-04-10 04:44:11 +00001756 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001757 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1758 else
1759 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1760}
1761
Mike Stump2add4732009-04-01 20:28:16 +00001762Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1763 unsigned IID;
1764 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001765
Chris Lattner9a207232010-06-26 21:48:21 +00001766 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001767 case BO_Add:
1768 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001769 OpID = 1;
1770 IID = llvm::Intrinsic::sadd_with_overflow;
1771 break;
John McCall2de56d12010-08-25 11:45:40 +00001772 case BO_Sub:
1773 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001774 OpID = 2;
1775 IID = llvm::Intrinsic::ssub_with_overflow;
1776 break;
John McCall2de56d12010-08-25 11:45:40 +00001777 case BO_Mul:
1778 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001779 OpID = 3;
1780 IID = llvm::Intrinsic::smul_with_overflow;
1781 break;
1782 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001783 llvm_unreachable("Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +00001784 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +00001785 }
Mike Stump035cf892009-04-02 18:15:54 +00001786 OpID <<= 1;
1787 OpID |= 1;
1788
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001789 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump2add4732009-04-01 20:28:16 +00001790
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00001791 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump2add4732009-04-01 20:28:16 +00001792
1793 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1794 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1795 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1796
1797 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00001798 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendling14ef3192011-07-07 21:13:10 +00001799 llvm::Function::iterator insertPt = initialBB;
1800 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
1801 llvm::next(insertPt));
Chris Lattner93a00352010-08-07 00:20:46 +00001802 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001803
1804 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1805
Chris Lattner93a00352010-08-07 00:20:46 +00001806 // Handle overflow with llvm.trap.
David Chisnall7f18e672010-09-17 18:29:54 +00001807 const std::string *handlerName =
1808 &CGF.getContext().getLangOptions().OverflowHandler;
1809 if (handlerName->empty()) {
1810 EmitOverflowBB(overflowBB);
1811 Builder.SetInsertPoint(continueBB);
1812 return result;
1813 }
1814
1815 // If an overflow handler is set, then we want to call it and then use its
1816 // result, if it returns.
1817 Builder.SetInsertPoint(overflowBB);
1818
1819 // Get the overflow handler.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001820 llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext);
1821 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnall7f18e672010-09-17 18:29:54 +00001822 llvm::FunctionType *handlerTy =
1823 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1824 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1825
1826 // Sign extend the args to 64-bit, so that we can use the same handler for
1827 // all types of overflow.
1828 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1829 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1830
1831 // Call the handler with the two arguments, the operation, and the size of
1832 // the result.
1833 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1834 Builder.getInt8(OpID),
1835 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1836
1837 // Truncate the result back to the desired size.
1838 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1839 Builder.CreateBr(continueBB);
1840
Mike Stump2add4732009-04-01 20:28:16 +00001841 Builder.SetInsertPoint(continueBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001842 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnall7f18e672010-09-17 18:29:54 +00001843 phi->addIncoming(result, initialBB);
1844 phi->addIncoming(handlerResult, overflowBB);
1845
1846 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00001847}
Chris Lattner7f02f722007-08-24 05:35:26 +00001848
John McCall913dab22011-06-25 01:32:37 +00001849/// Emit pointer + index arithmetic.
1850static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1851 const BinOpInfo &op,
1852 bool isSubtraction) {
1853 // Must have binary (not unary) expr here. Unary pointer
1854 // increment/decrement doesn't use this path.
1855 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1856
1857 Value *pointer = op.LHS;
1858 Expr *pointerOperand = expr->getLHS();
1859 Value *index = op.RHS;
1860 Expr *indexOperand = expr->getRHS();
1861
1862 // In a subtraction, the LHS is always the pointer.
1863 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1864 std::swap(pointer, index);
1865 std::swap(pointerOperand, indexOperand);
1866 }
1867
1868 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1869 if (width != CGF.PointerWidthInBits) {
1870 // Zero-extend or sign-extend the pointer value according to
1871 // whether the index is signed or not.
1872 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1873 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1874 "idx.ext");
1875 }
1876
1877 // If this is subtraction, negate the index.
1878 if (isSubtraction)
1879 index = CGF.Builder.CreateNeg(index, "idx.neg");
1880
1881 const PointerType *pointerType
1882 = pointerOperand->getType()->getAs<PointerType>();
1883 if (!pointerType) {
1884 QualType objectType = pointerOperand->getType()
1885 ->castAs<ObjCObjectPointerType>()
1886 ->getPointeeType();
1887 llvm::Value *objectSize
1888 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1889
1890 index = CGF.Builder.CreateMul(index, objectSize);
1891
1892 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1893 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1894 return CGF.Builder.CreateBitCast(result, pointer->getType());
1895 }
1896
1897 QualType elementType = pointerType->getPointeeType();
1898 if (const VariableArrayType *vla
1899 = CGF.getContext().getAsVariableArrayType(elementType)) {
1900 // The element count here is the total number of non-VLA elements.
1901 llvm::Value *numElements = CGF.getVLASize(vla).first;
1902
1903 // Effectively, the multiply by the VLA size is part of the GEP.
1904 // GEP indexes are signed, and scaling an index isn't permitted to
1905 // signed-overflow, so we use the same semantics for our explicit
1906 // multiply. We suppress this if overflow is not undefined behavior.
1907 if (CGF.getLangOptions().isSignedOverflowDefined()) {
1908 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
1909 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1910 } else {
1911 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
1912 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattnera4d71452010-06-26 21:25:03 +00001913 }
John McCall913dab22011-06-25 01:32:37 +00001914 return pointer;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001915 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001916
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001917 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1918 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1919 // future proof.
John McCall913dab22011-06-25 01:32:37 +00001920 if (elementType->isVoidType() || elementType->isFunctionType()) {
1921 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1922 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1923 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001924 }
1925
John McCall913dab22011-06-25 01:32:37 +00001926 if (CGF.getLangOptions().isSignedOverflowDefined())
1927 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1928
1929 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001930}
1931
John McCall913dab22011-06-25 01:32:37 +00001932Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
1933 if (op.LHS->getType()->isPointerTy() ||
1934 op.RHS->getType()->isPointerTy())
1935 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
1936
1937 if (op.Ty->isSignedIntegerOrEnumerationType()) {
1938 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1939 case LangOptions::SOB_Undefined:
1940 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
1941 case LangOptions::SOB_Defined:
1942 return Builder.CreateAdd(op.LHS, op.RHS, "add");
1943 case LangOptions::SOB_Trapping:
1944 return EmitOverflowCheckedBinOp(op);
1945 }
1946 }
1947
1948 if (op.LHS->getType()->isFPOrFPVectorTy())
1949 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
1950
1951 return Builder.CreateAdd(op.LHS, op.RHS, "add");
1952}
1953
1954Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
1955 // The LHS is always a pointer if either side is.
1956 if (!op.LHS->getType()->isPointerTy()) {
1957 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001958 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1959 case LangOptions::SOB_Undefined:
John McCall913dab22011-06-25 01:32:37 +00001960 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
Chris Lattnera4d71452010-06-26 21:25:03 +00001961 case LangOptions::SOB_Defined:
John McCall913dab22011-06-25 01:32:37 +00001962 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Chris Lattnera4d71452010-06-26 21:25:03 +00001963 case LangOptions::SOB_Trapping:
John McCall913dab22011-06-25 01:32:37 +00001964 return EmitOverflowCheckedBinOp(op);
Chris Lattnera4d71452010-06-26 21:25:03 +00001965 }
1966 }
1967
John McCall913dab22011-06-25 01:32:37 +00001968 if (op.LHS->getType()->isFPOrFPVectorTy())
1969 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Chris Lattner2eb91e42010-03-29 17:28:16 +00001970
John McCall913dab22011-06-25 01:32:37 +00001971 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001972 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001973
John McCall913dab22011-06-25 01:32:37 +00001974 // If the RHS is not a pointer, then we have normal pointer
1975 // arithmetic.
1976 if (!op.RHS->getType()->isPointerTy())
1977 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmandaa24a22009-03-28 02:45:41 +00001978
John McCall913dab22011-06-25 01:32:37 +00001979 // Otherwise, this is a pointer subtraction.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001980
John McCall913dab22011-06-25 01:32:37 +00001981 // Do the raw subtraction part.
1982 llvm::Value *LHS
1983 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
1984 llvm::Value *RHS
1985 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
1986 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar2a866252009-04-25 05:08:32 +00001987
John McCall913dab22011-06-25 01:32:37 +00001988 // Okay, figure out the element size.
1989 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1990 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001991
John McCall913dab22011-06-25 01:32:37 +00001992 llvm::Value *divisor = 0;
1993
1994 // For a variable-length array, this is going to be non-constant.
1995 if (const VariableArrayType *vla
1996 = CGF.getContext().getAsVariableArrayType(elementType)) {
1997 llvm::Value *numElements;
1998 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
1999
2000 divisor = numElements;
2001
2002 // Scale the number of non-VLA elements by the non-VLA element size.
2003 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2004 if (!eltSize.isOne())
2005 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2006
2007 // For everything elese, we can just compute it, safe in the
2008 // assumption that Sema won't let anything through that we can't
2009 // safely compute the size of.
2010 } else {
2011 CharUnits elementSize;
2012 // Handle GCC extension for pointer arithmetic on void* and
2013 // function pointer types.
2014 if (elementType->isVoidType() || elementType->isFunctionType())
2015 elementSize = CharUnits::One();
2016 else
2017 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2018
2019 // Don't even emit the divide for element size of 1.
2020 if (elementSize.isOne())
2021 return diffInChars;
2022
2023 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner7f02f722007-08-24 05:35:26 +00002024 }
Chris Lattner2cb42222011-03-01 00:03:48 +00002025
Chris Lattner2cb42222011-03-01 00:03:48 +00002026 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2027 // pointer difference in C is only defined in the case where both operands
2028 // are pointing to elements of an array.
John McCall913dab22011-06-25 01:32:37 +00002029 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002030}
2031
2032Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2033 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2034 // RHS to the same size as the LHS.
2035 Value *RHS = Ops.RHS;
2036 if (Ops.LHS->getType() != RHS->getType())
2037 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002038
Mike Stumpbe07f602009-12-14 21:58:14 +00002039 if (CGF.CatchUndefined
2040 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2041 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2042 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2043 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2044 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002045 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002046 CGF.EmitBlock(Cont);
2047 }
2048
Chris Lattner7f02f722007-08-24 05:35:26 +00002049 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2050}
2051
2052Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2053 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2054 // RHS to the same size as the LHS.
2055 Value *RHS = Ops.RHS;
2056 if (Ops.LHS->getType() != RHS->getType())
2057 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002058
Mike Stumpbe07f602009-12-14 21:58:14 +00002059 if (CGF.CatchUndefined
2060 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2061 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2062 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2063 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2064 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002065 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002066 CGF.EmitBlock(Cont);
2067 }
2068
Douglas Gregorf6094622010-07-23 15:58:24 +00002069 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002070 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2071 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2072}
2073
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002074enum IntrinsicType { VCMPEQ, VCMPGT };
2075// return corresponding comparison intrinsic for given vector type
2076static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2077 BuiltinType::Kind ElemKind) {
2078 switch (ElemKind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002079 default: llvm_unreachable("unexpected element type");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002080 case BuiltinType::Char_U:
2081 case BuiltinType::UChar:
2082 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2083 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2084 break;
2085 case BuiltinType::Char_S:
2086 case BuiltinType::SChar:
2087 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2088 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2089 break;
2090 case BuiltinType::UShort:
2091 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2092 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2093 break;
2094 case BuiltinType::Short:
2095 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2096 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2097 break;
2098 case BuiltinType::UInt:
2099 case BuiltinType::ULong:
2100 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2101 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2102 break;
2103 case BuiltinType::Int:
2104 case BuiltinType::Long:
2105 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2106 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2107 break;
2108 case BuiltinType::Float:
2109 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2110 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2111 break;
2112 }
2113 return llvm::Intrinsic::not_intrinsic;
2114}
2115
Chris Lattner7f02f722007-08-24 05:35:26 +00002116Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2117 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002118 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002119 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002120 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002121 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002122 assert(E->getOpcode() == BO_EQ ||
2123 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002124 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2125 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002126 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002127 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002128 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002129 Value *LHS = Visit(E->getLHS());
2130 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002131
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002132 // If AltiVec, the comparison results in a numeric type, so we use
2133 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002134 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002135 // constants for mapping CR6 register bits to predicate result
2136 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2137
2138 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2139
2140 // in several cases vector arguments order will be reversed
2141 Value *FirstVecArg = LHS,
2142 *SecondVecArg = RHS;
2143
2144 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002145 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002146 BuiltinType::Kind ElementKind = BTy->getKind();
2147
2148 switch(E->getOpcode()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002149 default: llvm_unreachable("is not a comparison operation");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002150 case BO_EQ:
2151 CR6 = CR6_LT;
2152 ID = GetIntrinsic(VCMPEQ, ElementKind);
2153 break;
2154 case BO_NE:
2155 CR6 = CR6_EQ;
2156 ID = GetIntrinsic(VCMPEQ, ElementKind);
2157 break;
2158 case BO_LT:
2159 CR6 = CR6_LT;
2160 ID = GetIntrinsic(VCMPGT, ElementKind);
2161 std::swap(FirstVecArg, SecondVecArg);
2162 break;
2163 case BO_GT:
2164 CR6 = CR6_LT;
2165 ID = GetIntrinsic(VCMPGT, ElementKind);
2166 break;
2167 case BO_LE:
2168 if (ElementKind == BuiltinType::Float) {
2169 CR6 = CR6_LT;
2170 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2171 std::swap(FirstVecArg, SecondVecArg);
2172 }
2173 else {
2174 CR6 = CR6_EQ;
2175 ID = GetIntrinsic(VCMPGT, ElementKind);
2176 }
2177 break;
2178 case BO_GE:
2179 if (ElementKind == BuiltinType::Float) {
2180 CR6 = CR6_LT;
2181 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2182 }
2183 else {
2184 CR6 = CR6_EQ;
2185 ID = GetIntrinsic(VCMPGT, ElementKind);
2186 std::swap(FirstVecArg, SecondVecArg);
2187 }
2188 break;
2189 }
2190
Chris Lattner48431f92011-04-19 22:55:03 +00002191 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002192 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2193 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2194 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2195 }
2196
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002197 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002198 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002199 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002200 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002201 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002202 LHS, RHS, "cmp");
2203 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002204 // Unsigned integers and pointers.
2205 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002206 LHS, RHS, "cmp");
2207 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002208
2209 // If this is a vector comparison, sign extend the result to the appropriate
2210 // vector integer type and return it (don't convert to bool).
2211 if (LHSTy->isVectorType())
2212 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002213
Chris Lattner7f02f722007-08-24 05:35:26 +00002214 } else {
2215 // Complex Comparison: can only be an equality comparison.
2216 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2217 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002218
John McCall183700f2009-09-21 23:43:11 +00002219 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002220
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002221 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002222 if (CETy->isRealFloatingType()) {
2223 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2224 LHS.first, RHS.first, "cmp.r");
2225 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2226 LHS.second, RHS.second, "cmp.i");
2227 } else {
2228 // Complex comparisons can only be equality comparisons. As such, signed
2229 // and unsigned opcodes are the same.
2230 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2231 LHS.first, RHS.first, "cmp.r");
2232 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2233 LHS.second, RHS.second, "cmp.i");
2234 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002235
John McCall2de56d12010-08-25 11:45:40 +00002236 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002237 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2238 } else {
John McCall2de56d12010-08-25 11:45:40 +00002239 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002240 "Complex comparison other than == or != ?");
2241 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2242 }
2243 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002244
2245 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002246}
2247
2248Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002249 bool Ignore = TestAndClearIgnoreResultAssign();
2250
John McCallf85e1932011-06-15 23:02:42 +00002251 Value *RHS;
2252 LValue LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002253
John McCallf85e1932011-06-15 23:02:42 +00002254 switch (E->getLHS()->getType().getObjCLifetime()) {
2255 case Qualifiers::OCL_Strong:
2256 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2257 break;
2258
2259 case Qualifiers::OCL_Autoreleasing:
2260 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2261 break;
2262
2263 case Qualifiers::OCL_Weak:
2264 RHS = Visit(E->getRHS());
2265 LHS = EmitCheckedLValue(E->getLHS());
2266 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2267 break;
2268
2269 // No reason to do any of these differently.
2270 case Qualifiers::OCL_None:
2271 case Qualifiers::OCL_ExplicitNone:
2272 // __block variables need to have the rhs evaluated first, plus
2273 // this should improve codegen just a little.
2274 RHS = Visit(E->getRHS());
2275 LHS = EmitCheckedLValue(E->getLHS());
2276
2277 // Store the value into the LHS. Bit-fields are handled specially
2278 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2279 // 'An assignment expression has the value of the left operand after
2280 // the assignment...'.
2281 if (LHS.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002282 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCallf85e1932011-06-15 23:02:42 +00002283 else
John McCall545d9962011-06-25 02:11:03 +00002284 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCallf85e1932011-06-15 23:02:42 +00002285 }
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002286
2287 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002288 if (Ignore)
2289 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002290
John McCallb418d742010-11-16 10:08:07 +00002291 // The result of an assignment in C is the assigned r-value.
2292 if (!CGF.getContext().getLangOptions().CPlusPlus)
2293 return RHS;
2294
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002295 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00002296 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002297 return RHS;
2298
2299 // If the lvalue is non-volatile, return the computed value of the assignment.
2300 if (!LHS.isVolatileQualified())
2301 return RHS;
2302
2303 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00002304 return EmitLoadOfLValue(LHS);
Chris Lattner7f02f722007-08-24 05:35:26 +00002305}
2306
2307Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002308 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002309
Chris Lattner20eb09d2008-11-12 08:26:50 +00002310 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2311 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002312 bool LHSCondVal;
2313 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2314 if (LHSCondVal) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002315 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002316 // ZExt result to int or bool.
2317 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002318 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002319
Chris Lattner7804bcb2009-10-17 04:24:20 +00002320 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002321 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002322 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002323 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002324
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002325 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2326 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002327
John McCall150b4622011-01-26 04:00:11 +00002328 CodeGenFunction::ConditionalEvaluation eval(CGF);
2329
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002330 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2331 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2332
2333 // Any edges into the ContBlock are now from an (indeterminate number of)
2334 // edges from this first condition. All of these values will be false. Start
2335 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002336 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002337 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002338 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2339 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002340 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002341
John McCall150b4622011-01-26 04:00:11 +00002342 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002343 CGF.EmitBlock(RHSBlock);
2344 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002345 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002346
Chris Lattner7f02f722007-08-24 05:35:26 +00002347 // Reaquire the RHS block, as there may be subblocks inserted.
2348 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002349
2350 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2351 // into the phi node for the edge with the value of RHSCond.
Devang Patelacd72362011-03-30 00:08:31 +00002352 if (CGF.getDebugInfo())
2353 // There is no need to emit line number for unconditional branch.
2354 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Chris Lattner7f02f722007-08-24 05:35:26 +00002355 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002356 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002357
Chris Lattner7f02f722007-08-24 05:35:26 +00002358 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002359 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002360}
2361
2362Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002363 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002364
Chris Lattner20eb09d2008-11-12 08:26:50 +00002365 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2366 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002367 bool LHSCondVal;
2368 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2369 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002370 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002371 // ZExt result to int or bool.
2372 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002373 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002374
Chris Lattner7804bcb2009-10-17 04:24:20 +00002375 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002376 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002377 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002378 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002379
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002380 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2381 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002382
John McCall150b4622011-01-26 04:00:11 +00002383 CodeGenFunction::ConditionalEvaluation eval(CGF);
2384
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002385 // Branch on the LHS first. If it is true, go to the success (cont) block.
2386 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2387
2388 // Any edges into the ContBlock are now from an (indeterminate number of)
2389 // edges from this first condition. All of these values will be true. Start
2390 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002391 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002392 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002393 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2394 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002395 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002396
John McCall150b4622011-01-26 04:00:11 +00002397 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002398
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002399 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002400 CGF.EmitBlock(RHSBlock);
2401 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002402
John McCall150b4622011-01-26 04:00:11 +00002403 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002404
Chris Lattner7f02f722007-08-24 05:35:26 +00002405 // Reaquire the RHS block, as there may be subblocks inserted.
2406 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002407
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002408 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2409 // into the phi node for the edge with the value of RHSCond.
2410 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002411 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002412
Chris Lattner7f02f722007-08-24 05:35:26 +00002413 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002414 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002415}
2416
2417Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002418 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002419 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002420 return Visit(E->getRHS());
2421}
2422
2423//===----------------------------------------------------------------------===//
2424// Other Operators
2425//===----------------------------------------------------------------------===//
2426
Chris Lattner9802a512008-11-12 08:55:54 +00002427/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2428/// expression is cheap enough and side-effect-free enough to evaluate
2429/// unconditionally instead of conditionally. This is used to convert control
2430/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002431static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2432 CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002433 E = E->IgnoreParens();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002434
Chris Lattnerc6bea672011-04-16 23:15:35 +00002435 // Anything that is an integer or floating point constant is fine.
2436 if (E->isConstantInitializer(CGF.getContext(), false))
Chris Lattner9802a512008-11-12 08:55:54 +00002437 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002438
Chris Lattner9802a512008-11-12 08:55:54 +00002439 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2440 // X and Y are local variables.
2441 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2442 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002443 if (VD->hasLocalStorage() && !(CGF.getContext()
2444 .getCanonicalType(VD->getType())
2445 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002446 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002447
Chris Lattner9802a512008-11-12 08:55:54 +00002448 return false;
2449}
2450
2451
Chris Lattner7f02f722007-08-24 05:35:26 +00002452Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00002453VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002454 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00002455
2456 // Bind the common expression if necessary.
2457 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2458
2459 Expr *condExpr = E->getCond();
2460 Expr *lhsExpr = E->getTrueExpr();
2461 Expr *rhsExpr = E->getFalseExpr();
2462
Chris Lattner31a09842008-11-12 08:04:58 +00002463 // If the condition constant folds and can be elided, try to avoid emitting
2464 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002465 bool CondExprBool;
2466 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00002467 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00002468 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002469
Chris Lattner31a09842008-11-12 08:04:58 +00002470 // If the dead side doesn't have labels we need, and if the Live side isn't
2471 // the gnu missing ?: extension (which we could handle, but don't bother
2472 // to), just emit the Live part.
John McCall56ca35d2011-02-17 10:25:35 +00002473 if (!CGF.ContainsLabel(dead))
2474 return Visit(live);
Chris Lattnerc657e922008-11-11 18:56:45 +00002475 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002476
Nate Begeman6155d732010-09-20 22:41:17 +00002477 // OpenCL: If the condition is a vector, we can treat this condition like
2478 // the select function.
2479 if (CGF.getContext().getLangOptions().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00002480 && condExpr->getType()->isVectorType()) {
2481 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2482 llvm::Value *LHS = Visit(lhsExpr);
2483 llvm::Value *RHS = Visit(rhsExpr);
Nate Begeman6155d732010-09-20 22:41:17 +00002484
Chris Lattner2acc6e32011-07-18 04:24:23 +00002485 llvm::Type *condType = ConvertType(condExpr->getType());
2486 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Nate Begeman6155d732010-09-20 22:41:17 +00002487
2488 unsigned numElem = vecTy->getNumElements();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002489 llvm::Type *elemType = vecTy->getElementType();
Nate Begeman6155d732010-09-20 22:41:17 +00002490
2491 std::vector<llvm::Constant*> Zvals;
2492 for (unsigned i = 0; i < numElem; ++i)
Chris Lattner48431f92011-04-19 22:55:03 +00002493 Zvals.push_back(llvm::ConstantInt::get(elemType, 0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002494
Nate Begeman6155d732010-09-20 22:41:17 +00002495 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals);
2496 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2497 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2498 llvm::VectorType::get(elemType,
2499 numElem),
2500 "sext");
2501 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2502
2503 // Cast float to int to perform ANDs if necessary.
2504 llvm::Value *RHSTmp = RHS;
2505 llvm::Value *LHSTmp = LHS;
2506 bool wasCast = false;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002507 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Nate Begeman6155d732010-09-20 22:41:17 +00002508 if (rhsVTy->getElementType()->isFloatTy()) {
2509 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2510 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2511 wasCast = true;
2512 }
2513
2514 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2515 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2516 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2517 if (wasCast)
2518 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2519
2520 return tmp5;
2521 }
2522
Chris Lattner9802a512008-11-12 08:55:54 +00002523 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2524 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002525 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00002526 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2527 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2528 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2529 llvm::Value *LHS = Visit(lhsExpr);
2530 llvm::Value *RHS = Visit(rhsExpr);
Chris Lattner9802a512008-11-12 08:55:54 +00002531 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2532 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002533
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002534 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2535 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002536 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002537
2538 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002539 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002540
Chris Lattner7f02f722007-08-24 05:35:26 +00002541 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002542 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002543 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002544 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002545
Chris Lattner7f02f722007-08-24 05:35:26 +00002546 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002547 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002548
Chris Lattner7f02f722007-08-24 05:35:26 +00002549 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002550 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002551 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002552 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002553
John McCall150b4622011-01-26 04:00:11 +00002554 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002555 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002556
Eli Friedman48daf592009-12-07 20:25:53 +00002557 // If the LHS or RHS is a throw expression, it will be legitimately null.
2558 if (!LHS)
2559 return RHS;
2560 if (!RHS)
2561 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002562
Chris Lattner7f02f722007-08-24 05:35:26 +00002563 // Create a PHI node for the real part.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002564 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner7f02f722007-08-24 05:35:26 +00002565 PN->addIncoming(LHS, LHSBlock);
2566 PN->addIncoming(RHS, RHSBlock);
2567 return PN;
2568}
2569
2570Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002571 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002572}
2573
Chris Lattner2202bce2007-11-30 17:56:23 +00002574Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002575 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002576 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2577
2578 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002579 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002580 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2581
Mike Stump7f79f9b2009-05-29 15:46:01 +00002582 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002583 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002584}
2585
John McCall6b5a61b2011-02-07 10:33:21 +00002586Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2587 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002588}
2589
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002590Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2591 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2acc6e32011-07-18 04:24:23 +00002592 llvm::Type *DstTy = ConvertType(E->getType());
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002593
2594 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2595 // a shuffle vector instead of a bitcast.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002596 llvm::Type *SrcTy = Src->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002597 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2598 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2599 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2600 if ((numElementsDst == 3 && numElementsSrc == 4)
2601 || (numElementsDst == 4 && numElementsSrc == 3)) {
2602
2603
2604 // In the case of going from int4->float3, a bitcast is needed before
2605 // doing a shuffle.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002606 llvm::Type *srcElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002607 cast<llvm::VectorType>(SrcTy)->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002608 llvm::Type *dstElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002609 cast<llvm::VectorType>(DstTy)->getElementType();
2610
2611 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2612 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2613 // Create a float type of the same size as the source or destination.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002614 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002615 numElementsSrc);
2616
2617 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2618 }
2619
2620 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2621
Chris Lattner5f9e2722011-07-23 10:55:15 +00002622 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002623 Args.push_back(Builder.getInt32(0));
2624 Args.push_back(Builder.getInt32(1));
2625 Args.push_back(Builder.getInt32(2));
2626
2627 if (numElementsDst == 4)
2628 Args.push_back(llvm::UndefValue::get(
2629 llvm::Type::getInt32Ty(CGF.getLLVMContext())));
2630
2631 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2632
2633 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2634 }
2635 }
2636
2637 return Builder.CreateBitCast(Src, DstTy, "astype");
2638}
2639
Chris Lattner7f02f722007-08-24 05:35:26 +00002640//===----------------------------------------------------------------------===//
2641// Entry Point into this File
2642//===----------------------------------------------------------------------===//
2643
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002644/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2645/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002646Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002647 assert(E && !hasAggregateLLVMType(E->getType()) &&
2648 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002649
Devang Patel5de7a0e2011-03-07 18:29:53 +00002650 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002651 disableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002652 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stump7f79f9b2009-05-29 15:46:01 +00002653 .Visit(const_cast<Expr*>(E));
Devang Patel5de7a0e2011-03-07 18:29:53 +00002654 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002655 enableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002656 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +00002657}
Chris Lattner3707b252007-08-26 06:48:56 +00002658
2659/// EmitScalarConversion - Emit a conversion from the specified type to the
2660/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002661Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2662 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002663 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2664 "Invalid scalar expression to emit");
2665 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2666}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002667
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002668/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2669/// type to the specified destination type, where the destination type is an
2670/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002671Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2672 QualType SrcTy,
2673 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002674 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002675 "Invalid complex -> scalar conversion");
2676 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2677 DstTy);
2678}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002679
Chris Lattner8c11a652010-06-26 22:09:34 +00002680
2681llvm::Value *CodeGenFunction::
2682EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2683 bool isInc, bool isPre) {
2684 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2685}
2686
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002687LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2688 llvm::Value *V;
2689 // object->isa or (*object).isa
2690 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002691 // build Class* type
Chris Lattner2acc6e32011-07-18 04:24:23 +00002692 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002693
2694 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00002695 if (BaseExpr->isRValue()) {
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002696 V = CreateTempAlloca(ClassPtrTy, "resval");
2697 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2698 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002699 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
John McCall545d9962011-06-25 02:11:03 +00002700 MakeAddrLValue(V, E->getType()));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002701 } else {
2702 if (E->isArrow())
2703 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2704 else
2705 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002706 }
2707
2708 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002709 ClassPtrTy = ClassPtrTy->getPointerTo();
2710 V = Builder.CreateBitCast(V, ClassPtrTy);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002711 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002712}
2713
Douglas Gregor6a03e342010-04-23 04:16:32 +00002714
John McCall2a416372010-12-05 02:00:02 +00002715LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00002716 const CompoundAssignOperator *E) {
2717 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002718 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002719 switch (E->getOpcode()) {
2720#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002721 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002722 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002723 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002724 COMPOUND_OP(Mul);
2725 COMPOUND_OP(Div);
2726 COMPOUND_OP(Rem);
2727 COMPOUND_OP(Add);
2728 COMPOUND_OP(Sub);
2729 COMPOUND_OP(Shl);
2730 COMPOUND_OP(Shr);
2731 COMPOUND_OP(And);
2732 COMPOUND_OP(Xor);
2733 COMPOUND_OP(Or);
2734#undef COMPOUND_OP
2735
John McCall2de56d12010-08-25 11:45:40 +00002736 case BO_PtrMemD:
2737 case BO_PtrMemI:
2738 case BO_Mul:
2739 case BO_Div:
2740 case BO_Rem:
2741 case BO_Add:
2742 case BO_Sub:
2743 case BO_Shl:
2744 case BO_Shr:
2745 case BO_LT:
2746 case BO_GT:
2747 case BO_LE:
2748 case BO_GE:
2749 case BO_EQ:
2750 case BO_NE:
2751 case BO_And:
2752 case BO_Xor:
2753 case BO_Or:
2754 case BO_LAnd:
2755 case BO_LOr:
2756 case BO_Assign:
2757 case BO_Comma:
David Blaikieb219cfc2011-09-23 05:06:16 +00002758 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor6a03e342010-04-23 04:16:32 +00002759 }
2760
2761 llvm_unreachable("Unhandled compound assignment operator");
2762}