blob: ad373095dedd9c408498f3c29ed06ead5e5cda27 [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); }
Richard Smith7ac9ef12012-09-08 02:08:36 +000083 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
84 return CGF.EmitCheckedLValue(E, TCK);
Richard Smith2c9f87c2012-08-24 00:54:33 +000085 }
Chris Lattner7f02f722007-08-24 05:35:26 +000086
John McCall545d9962011-06-25 02:11:03 +000087 Value *EmitLoadOfLValue(LValue LV) {
88 return CGF.EmitLoadOfLValue(LV).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000089 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000090
Chris Lattner7f02f722007-08-24 05:35:26 +000091 /// EmitLoadOfLValue - Given an expression with complex type that represents a
92 /// value l-value, this method emits the address of the l-value, then loads
93 /// and returns the result.
94 Value *EmitLoadOfLValue(const Expr *E) {
Richard Smith7ac9ef12012-09-08 02:08:36 +000095 return EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load));
Chris Lattner7f02f722007-08-24 05:35:26 +000096 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000097
Chris Lattner9abc84e2007-08-26 16:42:57 +000098 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000099 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000100 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000101
Chris Lattner3707b252007-08-26 06:48:56 +0000102 /// EmitScalarConversion - Emit a conversion from the specified type to the
103 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000104 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
105
106 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000107 /// complex type to the specified destination type, where the destination type
108 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000109 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
110 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000111
Anders Carlssona40a9f32010-05-22 17:45:10 +0000112 /// EmitNullValue - Emit a value that corresponds to null for the given type.
113 Value *EmitNullValue(QualType Ty);
114
John McCalldaa8e4e2010-11-15 09:13:47 +0000115 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
116 Value *EmitFloatToBoolConversion(Value *V) {
117 // Compare against 0.0 for fp scalars.
118 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
119 return Builder.CreateFCmpUNE(V, Zero, "tobool");
120 }
121
122 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
123 Value *EmitPointerToBoolConversion(Value *V) {
124 Value *Zero = llvm::ConstantPointerNull::get(
125 cast<llvm::PointerType>(V->getType()));
126 return Builder.CreateICmpNE(V, Zero, "tobool");
127 }
128
129 Value *EmitIntToBoolConversion(Value *V) {
130 // Because of the type rules of C, we often end up computing a
131 // logical value, then zero extending it to int, then wanting it
132 // as a logical value again. Optimize this common case.
133 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
134 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
135 Value *Result = ZI->getOperand(0);
136 // If there aren't any more uses, zap the instruction to save space.
137 // Note that there can be more uses, for example if this
138 // is the result of an assignment.
139 if (ZI->use_empty())
140 ZI->eraseFromParent();
141 return Result;
142 }
143 }
144
Chris Lattner48431f92011-04-19 22:55:03 +0000145 return Builder.CreateIsNotNull(V, "tobool");
John McCalldaa8e4e2010-11-15 09:13:47 +0000146 }
147
Chris Lattner7f02f722007-08-24 05:35:26 +0000148 //===--------------------------------------------------------------------===//
149 // Visitor Methods
150 //===--------------------------------------------------------------------===//
151
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000152 Value *Visit(Expr *E) {
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000153 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
154 }
155
Chris Lattner7f02f722007-08-24 05:35:26 +0000156 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000157 S->dump(CGF.getContext().getSourceManager());
David Blaikieb219cfc2011-09-23 05:06:16 +0000158 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner7f02f722007-08-24 05:35:26 +0000159 }
160 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000161
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000162 Value *VisitParenExpr(ParenExpr *PE) {
163 return Visit(PE->getSubExpr());
164 }
John McCall91a57552011-07-15 05:09:51 +0000165 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
166 return Visit(E->getReplacement());
167 }
Peter Collingbournef111d932011-04-15 00:35:48 +0000168 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
169 return Visit(GE->getResultExpr());
170 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000171
172 // Leaves.
173 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000174 return Builder.getInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000175 }
176 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000177 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000178 }
179 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000180 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000181 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000182 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
183 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
184 }
Nate Begemane7579b52007-11-15 05:40:03 +0000185 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000186 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000187 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000188 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000189 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000190 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000191 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000192 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000193 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000194 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000195 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000196 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000197 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
198 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000199 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000200
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000201 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000202 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000203 }
John McCalle996ffd2011-02-16 08:02:54 +0000204
John McCall4b9c2d22011-11-06 09:01:30 +0000205 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
206 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
207 }
208
John McCalle996ffd2011-02-16 08:02:54 +0000209 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000210 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +0000211 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
John McCalle996ffd2011-02-16 08:02:54 +0000212
213 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000214 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000215 }
John McCalldd2ecee2012-03-10 03:05:10 +0000216
Chris Lattner7f02f722007-08-24 05:35:26 +0000217 // l-values.
John McCallf4b88a42012-03-10 09:33:50 +0000218 Value *VisitDeclRefExpr(DeclRefExpr *E) {
219 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
John McCalldd2ecee2012-03-10 03:05:10 +0000220 if (result.isReference())
John McCallf4b88a42012-03-10 09:33:50 +0000221 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
John McCalldd2ecee2012-03-10 03:05:10 +0000222 return result.getValue();
Richard Smitha3ca41f2012-03-02 23:27:11 +0000223 }
John McCallf4b88a42012-03-10 09:33:50 +0000224 return EmitLoadOfLValue(E);
John McCalldd2ecee2012-03-10 03:05:10 +0000225 }
226
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000227 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
228 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000229 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000230 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
231 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000232 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000233 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000234 return EmitLoadOfLValue(E);
235 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000236 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000237 if (E->getMethodDecl() &&
238 E->getMethodDecl()->getResultType()->isReferenceType())
239 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000240 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000241 }
242
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000243 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000244 LValue LV = CGF.EmitObjCIsaExpr(E);
John McCall545d9962011-06-25 02:11:03 +0000245 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000246 return V;
247 }
248
Chris Lattner7f02f722007-08-24 05:35:26 +0000249 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000250 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000251 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000252 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000253 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
254 return EmitLoadOfLValue(E);
255 }
Devang Patel35634f52007-10-24 17:18:43 +0000256
Nate Begeman0533b302009-10-18 20:10:40 +0000257 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000258
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000259 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000260 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000261 }
John McCallbc8d40d2011-06-24 21:55:10 +0000262 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000263 if (E->getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000264 CGF.EmitVariablyModifiedType(E->getType());
265 return VisitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000266 }
John McCallbc8d40d2011-06-24 21:55:10 +0000267 Value *VisitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000268
269 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000270 if (E->getCallReturnType()->isReferenceType())
271 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000272
Chris Lattner9b655512007-08-31 22:49:20 +0000273 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000274 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000275
Chris Lattner33793202007-08-31 22:09:40 +0000276 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000277
Chris Lattner7f02f722007-08-24 05:35:26 +0000278 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000279 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000280 LValue LV = EmitLValue(E->getSubExpr());
281 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000282 }
283 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000284 LValue LV = EmitLValue(E->getSubExpr());
285 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000286 }
287 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000288 LValue LV = EmitLValue(E->getSubExpr());
289 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000290 }
291 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000292 LValue LV = EmitLValue(E->getSubExpr());
293 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000294 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000295
Anton Yartsev683564a2011-02-07 02:17:30 +0000296 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
297 llvm::Value *InVal,
298 llvm::Value *NextVal,
299 bool IsInc);
300
Chris Lattner8c11a652010-06-26 22:09:34 +0000301 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
302 bool isInc, bool isPre);
303
304
Chris Lattner7f02f722007-08-24 05:35:26 +0000305 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000306 if (isa<MemberPointerType>(E->getType())) // never sugared
307 return CGF.CGM.getMemberPointerConstant(E);
308
Chris Lattner7f02f722007-08-24 05:35:26 +0000309 return EmitLValue(E->getSubExpr()).getAddress();
310 }
John McCallfd569002010-12-04 12:43:24 +0000311 Value *VisitUnaryDeref(const UnaryOperator *E) {
312 if (E->getType()->isVoidType())
313 return Visit(E->getSubExpr()); // the actual value should be unused
314 return EmitLoadOfLValue(E);
315 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000316 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000317 // This differs from gcc, though, most likely due to a bug in gcc.
318 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000319 return Visit(E->getSubExpr());
320 }
321 Value *VisitUnaryMinus (const UnaryOperator *E);
322 Value *VisitUnaryNot (const UnaryOperator *E);
323 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000324 Value *VisitUnaryReal (const UnaryOperator *E);
325 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000326 Value *VisitUnaryExtension(const UnaryOperator *E) {
327 return Visit(E->getSubExpr());
328 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000329
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000330 // C++
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000331 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedmanec24b0e2011-08-14 04:50:34 +0000332 return EmitLoadOfLValue(E);
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000333 }
334
Chris Lattner04421082008-04-08 04:40:51 +0000335 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
336 return Visit(DAE->getExpr());
337 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000338 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
339 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000340 }
341
John McCall4765fa02010-12-06 08:20:24 +0000342 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +0000343 CGF.enterFullExpression(E);
344 CodeGenFunction::RunCleanupsScope Scope(CGF);
345 return Visit(E->getSubExpr());
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000346 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000347 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
348 return CGF.EmitCXXNewExpr(E);
349 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000350 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
351 CGF.EmitCXXDeleteExpr(E);
352 return 0;
353 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000354 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000355 return Builder.getInt1(E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000356 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000357
Francois Pichet6ad6f282010-12-07 00:08:36 +0000358 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000359 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000360 }
361
John Wiegley21ff2e52011-04-28 00:16:57 +0000362 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
363 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
364 }
365
John Wiegley55262202011-04-25 06:54:41 +0000366 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
367 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
368 }
369
Douglas Gregora71d8192009-09-04 17:36:40 +0000370 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
371 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000372 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000373 // operator (), and the result of such a call has type void. The only
374 // effect is the evaluation of the postfix-expression before the dot or
375 // arrow.
376 CGF.EmitScalarExpr(E->getBase());
377 return 0;
378 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000379
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000380 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000381 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000382 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000383
384 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
385 CGF.EmitCXXThrowExpr(E);
386 return 0;
387 }
388
Sebastian Redl98294de2010-09-10 21:04:00 +0000389 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000390 return Builder.getInt1(E->getValue());
Sebastian Redl98294de2010-09-10 21:04:00 +0000391 }
392
Chris Lattner7f02f722007-08-24 05:35:26 +0000393 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000394 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000395 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000396 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000397 case LangOptions::SOB_Defined:
398 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith9d3e2262012-08-25 00:32:28 +0000399 case LangOptions::SOB_Undefined:
400 if (!CGF.CatchUndefined)
401 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
402 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +0000403 case LangOptions::SOB_Trapping:
404 return EmitOverflowCheckedBinOp(Ops);
405 }
406 }
407
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000408 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000409 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000410 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
411 }
Chris Lattner80230302010-09-11 21:47:09 +0000412 bool isTrapvOverflowBehavior() {
Richard Smith9d3e2262012-08-25 00:32:28 +0000413 return CGF.getContext().getLangOpts().getSignedOverflowBehavior()
414 == LangOptions::SOB_Trapping || CGF.CatchUndefined;
Chris Lattner80230302010-09-11 21:47:09 +0000415 }
Mike Stump2add4732009-04-01 20:28:16 +0000416 /// Create a binary op that checks for overflow.
417 /// Currently only supports +, - and *.
418 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith7ac9ef12012-09-08 02:08:36 +0000419
Chris Lattner80230302010-09-11 21:47:09 +0000420 // Check for undefined division and modulus behaviors.
421 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
422 llvm::Value *Zero,bool isDiv);
Chris Lattner7f02f722007-08-24 05:35:26 +0000423 Value *EmitDiv(const BinOpInfo &Ops);
424 Value *EmitRem(const BinOpInfo &Ops);
425 Value *EmitAdd(const BinOpInfo &Ops);
426 Value *EmitSub(const BinOpInfo &Ops);
427 Value *EmitShl(const BinOpInfo &Ops);
428 Value *EmitShr(const BinOpInfo &Ops);
429 Value *EmitAnd(const BinOpInfo &Ops) {
430 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
431 }
432 Value *EmitXor(const BinOpInfo &Ops) {
433 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
434 }
435 Value *EmitOr (const BinOpInfo &Ops) {
436 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
437 }
438
Chris Lattner1f1ded92007-08-24 21:00:35 +0000439 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000440 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
441 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000442 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000443
Chris Lattner3ccf7742007-08-26 21:41:21 +0000444 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000445 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
446
447 // Binary operators and binary compound assignment operators.
448#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000449 Value *VisitBin ## OP(const BinaryOperator *E) { \
450 return Emit ## OP(EmitBinOps(E)); \
451 } \
452 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
453 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000454 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000455 HANDLEBINOP(Mul)
456 HANDLEBINOP(Div)
457 HANDLEBINOP(Rem)
458 HANDLEBINOP(Add)
459 HANDLEBINOP(Sub)
460 HANDLEBINOP(Shl)
461 HANDLEBINOP(Shr)
462 HANDLEBINOP(And)
463 HANDLEBINOP(Xor)
464 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000465#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000466
Chris Lattner7f02f722007-08-24 05:35:26 +0000467 // Comparisons.
468 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
469 unsigned SICmpOpc, unsigned FCmpOpc);
470#define VISITCOMP(CODE, UI, SI, FP) \
471 Value *VisitBin##CODE(const BinaryOperator *E) { \
472 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
473 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000474 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
475 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
476 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
477 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
478 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
479 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000480#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000481
Chris Lattner7f02f722007-08-24 05:35:26 +0000482 Value *VisitBinAssign (const BinaryOperator *E);
483
484 Value *VisitBinLAnd (const BinaryOperator *E);
485 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000486 Value *VisitBinComma (const BinaryOperator *E);
487
Eli Friedman25b825d2009-11-18 09:41:26 +0000488 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
489 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
490
Chris Lattner7f02f722007-08-24 05:35:26 +0000491 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000492 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000493 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000494 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000495 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000496 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
497 return CGF.EmitObjCStringLiteral(E);
498 }
Patrick Beardeb382ec2012-04-19 00:25:12 +0000499 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
500 return CGF.EmitObjCBoxedExpr(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000501 }
502 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
503 return CGF.EmitObjCArrayLiteral(E);
504 }
505 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
506 return CGF.EmitObjCDictionaryLiteral(E);
507 }
Tanya Lattner61eee0c2011-06-04 00:47:47 +0000508 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedman276b0612011-10-11 02:20:01 +0000509 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000510};
511} // end anonymous namespace.
512
513//===----------------------------------------------------------------------===//
514// Utilities
515//===----------------------------------------------------------------------===//
516
Chris Lattner9abc84e2007-08-26 16:42:57 +0000517/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000518/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000519Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000520 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000521
John McCalldaa8e4e2010-11-15 09:13:47 +0000522 if (SrcType->isRealFloatingType())
523 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000524
John McCall0bab0cd2010-08-23 01:21:21 +0000525 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
526 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000527
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000528 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000529 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000530
John McCalldaa8e4e2010-11-15 09:13:47 +0000531 if (isa<llvm::IntegerType>(Src->getType()))
532 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000533
John McCalldaa8e4e2010-11-15 09:13:47 +0000534 assert(isa<llvm::PointerType>(Src->getType()));
535 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000536}
537
Chris Lattner3707b252007-08-26 06:48:56 +0000538/// EmitScalarConversion - Emit a conversion from the specified type to the
539/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000540Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
541 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000542 SrcType = CGF.getContext().getCanonicalType(SrcType);
543 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000544 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000545
Chris Lattnercf289082007-08-26 07:21:11 +0000546 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000547
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000548 llvm::Type *SrcTy = Src->getType();
549
550 // Floating casts might be a bit special: if we're doing casts to / from half
551 // FP, we should go via special intrinsics.
552 if (SrcType->isHalfType()) {
553 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
554 SrcType = CGF.getContext().FloatTy;
Chris Lattner8b418682012-02-07 00:39:47 +0000555 SrcTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000556 }
557
Chris Lattner3707b252007-08-26 06:48:56 +0000558 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000559 if (DstType->isBooleanType())
560 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000561
Chris Lattner2acc6e32011-07-18 04:24:23 +0000562 llvm::Type *DstTy = ConvertType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000563
564 // Ignore conversions like int -> uint.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000565 if (SrcTy == DstTy)
Chris Lattner3707b252007-08-26 06:48:56 +0000566 return Src;
567
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000568 // Handle pointer conversions next: pointers can only be converted to/from
569 // other pointers and integers. Check for pointer types in terms of LLVM, as
570 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000571 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000572 // The source value may be an integer, or a pointer.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000573 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3707b252007-08-26 06:48:56 +0000574 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000575
Chris Lattner3707b252007-08-26 06:48:56 +0000576 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000577 // First, convert to the correct width so that we control the kind of
578 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000579 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000580 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman25615422009-03-04 04:02:35 +0000581 llvm::Value* IntResult =
582 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
583 // Then, cast to pointer.
584 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000585 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000586
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000587 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000588 // Must be an ptr to int cast.
589 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000590 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000591 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000592
Nate Begeman213541a2008-04-18 23:10:10 +0000593 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000594 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000595 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000596 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000597 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
598
599 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000600 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +0000601 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +0000602 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000603
604 // Splat the element across to all elements
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000605 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner2ce88422012-01-25 05:34:41 +0000606 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements,
607 Builder.getInt32(0));
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000608 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
609 return Yay;
610 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000611
Chris Lattner3b1ae002008-02-02 04:51:41 +0000612 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000613 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000614 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000615 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000616
Chris Lattner3707b252007-08-26 06:48:56 +0000617 // Finally, we have the arithmetic types: real int/float.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000618 Value *Res = NULL;
619 llvm::Type *ResTy = DstTy;
620
621 // Cast to half via float
622 if (DstType->isHalfType())
Chris Lattner8b418682012-02-07 00:39:47 +0000623 DstTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000624
625 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000626 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000627 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000628 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000629 else if (InputSigned)
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000630 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000631 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000632 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
633 } else if (isa<llvm::IntegerType>(DstTy)) {
634 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor575a1c92011-05-20 16:38:50 +0000635 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000636 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000637 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000638 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
639 } else {
640 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
641 "Unknown real conversion");
642 if (DstTy->getTypeID() < SrcTy->getTypeID())
643 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
644 else
645 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000646 }
647
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000648 if (DstTy != ResTy) {
649 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
650 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
651 }
652
653 return Res;
Chris Lattner3707b252007-08-26 06:48:56 +0000654}
655
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000656/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
657/// type to the specified destination type, where the destination type is an
658/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000659Value *ScalarExprEmitter::
660EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
661 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000662 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000663 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000664
Chris Lattnered70f0a2007-08-26 16:52:28 +0000665 // Handle conversions to bool first, they are special: comparisons against 0.
666 if (DstTy->isBooleanType()) {
667 // Complex != 0 -> (Real != 0) | (Imag != 0)
668 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
669 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
670 return Builder.CreateOr(Src.first, Src.second, "tobool");
671 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000672
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000673 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
674 // the imaginary part of the complex value is discarded and the value of the
675 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000676 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000677 return EmitScalarConversion(Src.first, SrcTy, DstTy);
678}
679
Anders Carlssona40a9f32010-05-22 17:45:10 +0000680Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000681 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
682 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
683
684 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000685}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000686
Chris Lattner7f02f722007-08-24 05:35:26 +0000687//===----------------------------------------------------------------------===//
688// Visitor Methods
689//===----------------------------------------------------------------------===//
690
691Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000692 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000693 if (E->getType()->isVoidType())
694 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000695 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000696}
697
Eli Friedmand38617c2008-05-14 19:38:39 +0000698Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000699 // Vector Mask Case
700 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000701 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000702 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
703 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
704 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000705
Chris Lattner2acc6e32011-07-18 04:24:23 +0000706 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000707 unsigned LHSElts = LTy->getNumElements();
708
709 if (E->getNumSubExprs() == 3) {
710 Mask = CGF.EmitScalarExpr(E->getExpr(2));
711
712 // Shuffle LHS & RHS into one input vector.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000713 SmallVector<llvm::Constant*, 32> concat;
Nate Begeman37b6a572010-06-08 00:16:34 +0000714 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000715 concat.push_back(Builder.getInt32(2*i));
716 concat.push_back(Builder.getInt32(2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000717 }
718
Chris Lattnerfb018d12011-02-15 00:14:06 +0000719 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000720 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
721 LHSElts *= 2;
722 } else {
723 Mask = RHS;
724 }
725
Chris Lattner2acc6e32011-07-18 04:24:23 +0000726 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000727 llvm::Constant* EltMask;
728
729 // Treat vec3 like vec4.
730 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
731 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
732 (1 << llvm::Log2_32(LHSElts+2))-1);
733 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
734 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
735 (1 << llvm::Log2_32(LHSElts+1))-1);
736 else
737 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
738 (1 << llvm::Log2_32(LHSElts))-1);
739
740 // Mask off the high bits of each shuffle index.
Chris Lattner2ce88422012-01-25 05:34:41 +0000741 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
742 EltMask);
Nate Begeman37b6a572010-06-08 00:16:34 +0000743 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
744
745 // newv = undef
746 // mask = mask & maskbits
747 // for each elt
748 // n = extract mask i
749 // x = extract val n
750 // newv = insert newv, x, i
Chris Lattner2acc6e32011-07-18 04:24:23 +0000751 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000752 MTy->getNumElements());
753 Value* NewV = llvm::UndefValue::get(RTy);
754 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Eli Friedman87b9c032012-04-05 21:48:40 +0000755 Value *IIndx = Builder.getInt32(i);
756 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000757 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000758
759 // Handle vec3 special since the index will be off by one for the RHS.
760 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
761 Value *cmpIndx, *newIndx;
Chris Lattner48431f92011-04-19 22:55:03 +0000762 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000763 "cmp_shuf_idx");
Chris Lattner48431f92011-04-19 22:55:03 +0000764 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
Nate Begeman37b6a572010-06-08 00:16:34 +0000765 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
766 }
767 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman87b9c032012-04-05 21:48:40 +0000768 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begeman37b6a572010-06-08 00:16:34 +0000769 }
770 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000771 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000772
Eli Friedmand38617c2008-05-14 19:38:39 +0000773 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
774 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000775
776 // Handle vec3 special since the index will be off by one for the RHS.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000777 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000778 SmallVector<llvm::Constant*, 32> indices;
Nate Begeman37b6a572010-06-08 00:16:34 +0000779 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
Eli Friedman0eb47fc2011-05-19 00:37:32 +0000780 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
781 if (VTy->getNumElements() == 3 && Idx > 3)
782 Idx -= 1;
783 indices.push_back(Builder.getInt32(Idx));
Nate Begeman37b6a572010-06-08 00:16:34 +0000784 }
785
Chris Lattnerfb018d12011-02-15 00:14:06 +0000786 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000787 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
788}
Eli Friedman28665272009-11-26 03:22:21 +0000789Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Richard Smith80d4b552011-12-28 19:48:30 +0000790 llvm::APSInt Value;
791 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
Eli Friedman28665272009-11-26 03:22:21 +0000792 if (E->isArrow())
793 CGF.EmitScalarExpr(E->getBase());
794 else
795 EmitLValue(E->getBase());
Richard Smith80d4b552011-12-28 19:48:30 +0000796 return Builder.getInt(Value);
Eli Friedman28665272009-11-26 03:22:21 +0000797 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000798
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000799 // Emit debug info for aggregate now, if it was delayed to reduce
Devang Patel78ba3d42010-10-04 21:46:04 +0000800 // debug info size.
801 CGDebugInfo *DI = CGF.getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000802 if (DI &&
803 CGF.CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo) {
Devang Patel78ba3d42010-10-04 21:46:04 +0000804 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
805 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000806 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000807 DI->getOrCreateRecordType(PTy->getPointeeType(),
Devang Patel78ba3d42010-10-04 21:46:04 +0000808 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000809 }
Eli Friedman28665272009-11-26 03:22:21 +0000810 return EmitLoadOfLValue(E);
811}
Eli Friedmand38617c2008-05-14 19:38:39 +0000812
Chris Lattner7f02f722007-08-24 05:35:26 +0000813Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000814 TestAndClearIgnoreResultAssign();
815
Chris Lattner7f02f722007-08-24 05:35:26 +0000816 // Emit subscript expressions in rvalue context's. For most cases, this just
817 // loads the lvalue formed by the subscript expr. However, we have to be
818 // careful, because the base of a vector subscript is occasionally an rvalue,
819 // so we can't get it as an lvalue.
820 if (!E->getBase()->getType()->isVectorType())
821 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000822
Chris Lattner7f02f722007-08-24 05:35:26 +0000823 // Handle the vector case. The base must be a vector, the index must be an
824 // integer value.
825 Value *Base = Visit(E->getBase());
826 Value *Idx = Visit(E->getIdx());
Douglas Gregor575a1c92011-05-20 16:38:50 +0000827 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000828 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000829 return Builder.CreateExtractElement(Base, Idx, "vecext");
830}
831
Nate Begeman0533b302009-10-18 20:10:40 +0000832static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000833 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman0533b302009-10-18 20:10:40 +0000834 int MV = SVI->getMaskValue(Idx);
835 if (MV == -1)
836 return llvm::UndefValue::get(I32Ty);
837 return llvm::ConstantInt::get(I32Ty, Off+MV);
838}
839
840Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
841 bool Ignore = TestAndClearIgnoreResultAssign();
842 (void)Ignore;
843 assert (Ignore == false && "init list ignored");
844 unsigned NumInitElements = E->getNumInits();
845
846 if (E->hadArrayRangeDesignator())
847 CGF.ErrorUnsupported(E, "GNU array range designator extension");
848
Chris Lattner2acc6e32011-07-18 04:24:23 +0000849 llvm::VectorType *VType =
Nate Begeman0533b302009-10-18 20:10:40 +0000850 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
851
Sebastian Redlcea8d962011-09-24 17:48:14 +0000852 if (!VType) {
853 if (NumInitElements == 0) {
854 // C++11 value-initialization for the scalar.
855 return EmitNullValue(E->getType());
856 }
857 // We have a scalar in braces. Just use the first element.
Nate Begeman0533b302009-10-18 20:10:40 +0000858 return Visit(E->getInit(0));
Sebastian Redlcea8d962011-09-24 17:48:14 +0000859 }
Nate Begeman0533b302009-10-18 20:10:40 +0000860
861 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000862
863 // Loop over initializers collecting the Value for each, and remembering
864 // whether the source was swizzle (ExtVectorElementExpr). This will allow
865 // us to fold the shuffle for the swizzle into the shuffle for the vector
866 // initializer, since LLVM optimizers generally do not want to touch
867 // shuffles.
868 unsigned CurIdx = 0;
869 bool VIsUndefShuffle = false;
870 llvm::Value *V = llvm::UndefValue::get(VType);
871 for (unsigned i = 0; i != NumInitElements; ++i) {
872 Expr *IE = E->getInit(i);
873 Value *Init = Visit(IE);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000874 SmallVector<llvm::Constant*, 16> Args;
Nate Begeman0533b302009-10-18 20:10:40 +0000875
Chris Lattner2acc6e32011-07-18 04:24:23 +0000876 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000877
878 // Handle scalar elements. If the scalar initializer is actually one
879 // element of a different vector of the same width, use shuffle instead of
880 // extract+insert.
881 if (!VVT) {
882 if (isa<ExtVectorElementExpr>(IE)) {
883 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
884
885 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
886 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
887 Value *LHS = 0, *RHS = 0;
888 if (CurIdx == 0) {
889 // insert into undef -> shuffle (src, undef)
890 Args.push_back(C);
Benjamin Kramer14c59822012-02-14 12:06:21 +0000891 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000892
893 LHS = EI->getVectorOperand();
894 RHS = V;
895 VIsUndefShuffle = true;
896 } else if (VIsUndefShuffle) {
897 // insert into undefshuffle && size match -> shuffle (v, src)
898 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
899 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000900 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner48431f92011-04-19 22:55:03 +0000901 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000902 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
903
Nate Begeman0533b302009-10-18 20:10:40 +0000904 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
905 RHS = EI->getVectorOperand();
906 VIsUndefShuffle = false;
907 }
908 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +0000909 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000910 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
911 ++CurIdx;
912 continue;
913 }
914 }
915 }
Chris Lattner48431f92011-04-19 22:55:03 +0000916 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
917 "vecinit");
Nate Begeman0533b302009-10-18 20:10:40 +0000918 VIsUndefShuffle = false;
919 ++CurIdx;
920 continue;
921 }
922
923 unsigned InitElts = VVT->getNumElements();
924
925 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
926 // input is the same width as the vector being constructed, generate an
927 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000928 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000929 if (isa<ExtVectorElementExpr>(IE)) {
930 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
931 Value *SVOp = SVI->getOperand(0);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000932 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000933
934 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000935 for (unsigned j = 0; j != CurIdx; ++j) {
936 // If the current vector initializer is a shuffle with undef, merge
937 // this shuffle directly into it.
938 if (VIsUndefShuffle) {
939 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000940 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000941 } else {
Chris Lattner48431f92011-04-19 22:55:03 +0000942 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000943 }
944 }
945 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000946 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000947 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000948
949 if (VIsUndefShuffle)
950 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
951
952 Init = SVOp;
953 }
954 }
955
956 // Extend init to result vector length, and then shuffle its contribution
957 // to the vector initializer into V.
958 if (Args.empty()) {
959 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000960 Args.push_back(Builder.getInt32(j));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000961 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +0000962 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000963 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000964 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000965
966 Args.clear();
967 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000968 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000969 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000970 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000971 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000972 }
973
974 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
975 // merging subsequent shuffles into this one.
976 if (CurIdx == 0)
977 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +0000978 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000979 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
980 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
981 CurIdx += InitElts;
982 }
983
984 // FIXME: evaluate codegen vs. shuffling against constant null vector.
985 // Emit remaining default initializers.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000986 llvm::Type *EltTy = VType->getElementType();
Nate Begeman0533b302009-10-18 20:10:40 +0000987
988 // Emit remaining default initializers
989 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner48431f92011-04-19 22:55:03 +0000990 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000991 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
992 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
993 }
994 return V;
995}
996
Anders Carlssona3697c92009-11-23 17:57:54 +0000997static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
998 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +0000999
John McCall2de56d12010-08-25 11:45:40 +00001000 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +00001001 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +00001002
1003 if (isa<CXXThisExpr>(E)) {
1004 // We always assume that 'this' is never null.
1005 return false;
1006 }
1007
1008 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00001009 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +00001010 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +00001011 return false;
1012 }
1013
1014 return true;
1015}
1016
Chris Lattner7f02f722007-08-24 05:35:26 +00001017// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1018// have to handle a more broad range of conversions than explicit casts, as they
1019// handle things like function to ptr-to-function decay etc.
John McCallbc8d40d2011-06-24 21:55:10 +00001020Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmand8889622009-11-27 04:41:50 +00001021 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001022 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001023 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001024
Mike Stump7f79f9b2009-05-29 15:46:01 +00001025 if (!DestTy->isVoidType())
1026 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001027
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001028 // Since almost all cast kinds apply to scalars, this switch doesn't have
1029 // a default case, so the compiler will warn on a missing case. The cases
1030 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001031 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001032 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001033 case CK_BuiltinFnToFnPtr:
1034 llvm_unreachable("builtin functions are handled elsewhere");
1035
John McCall2de56d12010-08-25 11:45:40 +00001036 case CK_LValueBitCast:
1037 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001038 Value *V = EmitLValue(E).getAddress();
1039 V = Builder.CreateBitCast(V,
1040 ConvertType(CGF.getContext().getPointerType(DestTy)));
Eli Friedmand71f4422011-12-19 23:03:09 +00001041 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
Douglas Gregore39a3892010-07-13 23:17:26 +00001042 }
John McCalldc05b112011-09-10 01:16:55 +00001043
John McCall1d9b3b22011-09-09 05:25:32 +00001044 case CK_CPointerToObjCPointerCast:
1045 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001046 case CK_AnyPointerToBlockPointerCast:
1047 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001048 Value *Src = Visit(const_cast<Expr*>(E));
1049 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1050 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001051 case CK_AtomicToNonAtomic:
1052 case CK_NonAtomicToAtomic:
John McCall2de56d12010-08-25 11:45:40 +00001053 case CK_NoOp:
1054 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001055 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001056
John McCall2de56d12010-08-25 11:45:40 +00001057 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +00001058 const CXXRecordDecl *DerivedClassDecl =
1059 DestTy->getCXXRecordDeclForPointerType();
1060
Anders Carlssona04efdf2010-04-24 21:23:59 +00001061 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001062 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001063 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001064 }
John McCall2de56d12010-08-25 11:45:40 +00001065 case CK_UncheckedDerivedToBase:
1066 case CK_DerivedToBase: {
Anders Carlsson191dfe92009-09-12 04:57:16 +00001067 const RecordType *DerivedClassTy =
1068 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1069 CXXRecordDecl *DerivedClassDecl =
1070 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1071
Anders Carlsson34a2d382010-04-24 21:06:20 +00001072 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001073 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001074 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001075 }
Anders Carlsson575b3742011-04-11 02:03:26 +00001076 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001077 Value *V = Visit(const_cast<Expr*>(E));
1078 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1079 return CGF.EmitDynamicCast(V, DCE);
1080 }
Eli Friedmand8889622009-11-27 04:41:50 +00001081
John McCall2de56d12010-08-25 11:45:40 +00001082 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001083 assert(E->getType()->isArrayType() &&
1084 "Array to pointer decay must have array source type!");
1085
1086 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1087
1088 // Note that VLA pointers are always decayed, so we don't need to do
1089 // anything here.
1090 if (!E->getType()->isVariableArrayType()) {
1091 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1092 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1093 ->getElementType()) &&
1094 "Expected pointer to array");
1095 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1096 }
1097
Chris Lattner410b12e2011-07-20 04:31:01 +00001098 // Make sure the array decay ends up being the right type. This matters if
1099 // the array type was of an incomplete type.
Chris Lattnercb8095f2011-07-20 04:59:57 +00001100 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
Eli Friedmanad35a832009-11-16 21:33:53 +00001101 }
John McCall2de56d12010-08-25 11:45:40 +00001102 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001103 return EmitLValue(E).getAddress();
1104
John McCall404cd162010-11-13 01:35:44 +00001105 case CK_NullToPointer:
1106 if (MustVisitNullValue(E))
1107 (void) Visit(E);
1108
1109 return llvm::ConstantPointerNull::get(
1110 cast<llvm::PointerType>(ConvertType(DestTy)));
1111
John McCall2de56d12010-08-25 11:45:40 +00001112 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001113 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001114 (void) Visit(E);
1115
John McCall0bab0cd2010-08-23 01:21:21 +00001116 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1117 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1118 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001119
John McCall4d4e5c12012-02-15 01:22:51 +00001120 case CK_ReinterpretMemberPointer:
John McCall2de56d12010-08-25 11:45:40 +00001121 case CK_BaseToDerivedMemberPointer:
1122 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001123 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001124
1125 // Note that the AST doesn't distinguish between checked and
1126 // unchecked member pointer conversions, so we always have to
1127 // implement checked conversions here. This is inefficient when
1128 // actual control flow may be required in order to perform the
1129 // check, which it is for data member pointers (but not member
1130 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001131 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001132 }
John McCallf85e1932011-06-15 23:02:42 +00001133
John McCall33e56f32011-09-10 06:18:15 +00001134 case CK_ARCProduceObject:
John McCallf85e1932011-06-15 23:02:42 +00001135 return CGF.EmitARCRetainScalarExpr(E);
John McCall33e56f32011-09-10 06:18:15 +00001136 case CK_ARCConsumeObject:
John McCallf85e1932011-06-15 23:02:42 +00001137 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall33e56f32011-09-10 06:18:15 +00001138 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00001139 llvm::Value *value = Visit(E);
1140 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1141 return CGF.EmitObjCConsumeObject(E->getType(), value);
1142 }
John McCall348f16f2011-10-04 06:23:45 +00001143 case CK_ARCExtendBlockObject:
1144 return CGF.EmitARCExtendBlockObject(E);
John McCallf85e1932011-06-15 23:02:42 +00001145
Douglas Gregorac1303e2012-02-22 05:02:47 +00001146 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmancae40c42012-02-28 01:08:45 +00001147 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Douglas Gregorac1303e2012-02-22 05:02:47 +00001148
John McCall2bb5d002010-11-13 09:02:35 +00001149 case CK_FloatingRealToComplex:
1150 case CK_FloatingComplexCast:
1151 case CK_IntegralRealToComplex:
1152 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001153 case CK_IntegralComplexToFloatingComplex:
1154 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001155 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001156 case CK_ToUnion:
1157 llvm_unreachable("scalar cast to non-scalar value");
John McCallf6a16482010-12-04 03:47:34 +00001158
John McCall0ae287a2010-12-01 04:43:34 +00001159 case CK_LValueToRValue:
1160 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001161 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001162 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001163
John McCall2de56d12010-08-25 11:45:40 +00001164 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001165 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001166
Anders Carlsson82debc72009-10-18 18:12:03 +00001167 // First, convert to the correct width so that we control the kind of
1168 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001169 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +00001170 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson82debc72009-10-18 18:12:03 +00001171 llvm::Value* IntResult =
1172 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001173
Anders Carlsson82debc72009-10-18 18:12:03 +00001174 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001175 }
Eli Friedman65949422011-06-25 02:58:47 +00001176 case CK_PointerToIntegral:
1177 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1178 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001179
John McCall2de56d12010-08-25 11:45:40 +00001180 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001181 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001182 return 0;
1183 }
John McCall2de56d12010-08-25 11:45:40 +00001184 case CK_VectorSplat: {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001185 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001186 Value *Elt = Visit(const_cast<Expr*>(E));
Craig Topper5fa56082012-02-06 05:05:50 +00001187 Elt = EmitScalarConversion(Elt, E->getType(),
1188 DestTy->getAs<VectorType>()->getElementType());
Eli Friedmanad35a832009-11-16 21:33:53 +00001189
1190 // Insert the element in element zero of an undef vector
1191 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +00001192 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +00001193 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Eli Friedmanad35a832009-11-16 21:33:53 +00001194
1195 // Splat the element across to all elements
Eli Friedmanad35a832009-11-16 21:33:53 +00001196 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner48431f92011-04-19 22:55:03 +00001197 llvm::Constant *Zero = Builder.getInt32(0);
Chris Lattner2ce88422012-01-25 05:34:41 +00001198 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero);
Eli Friedmanad35a832009-11-16 21:33:53 +00001199 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1200 return Yay;
1201 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001202
John McCall2de56d12010-08-25 11:45:40 +00001203 case CK_IntegralCast:
1204 case CK_IntegralToFloating:
1205 case CK_FloatingToIntegral:
1206 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001207 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
John McCalldaa8e4e2010-11-15 09:13:47 +00001208 case CK_IntegralToBoolean:
1209 return EmitIntToBoolConversion(Visit(E));
1210 case CK_PointerToBoolean:
1211 return EmitPointerToBoolConversion(Visit(E));
1212 case CK_FloatingToBoolean:
1213 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001214 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001215 llvm::Value *MemPtr = Visit(E);
1216 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1217 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001218 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001219
1220 case CK_FloatingComplexToReal:
1221 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001222 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001223
1224 case CK_FloatingComplexToBoolean:
1225 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001226 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001227
1228 // TODO: kill this function off, inline appropriate case here
1229 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1230 }
1231
John McCall0bab0cd2010-08-23 01:21:21 +00001232 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001233
John McCall61ad0e62010-11-16 06:21:14 +00001234 llvm_unreachable("unknown scalar cast");
Chris Lattner7f02f722007-08-24 05:35:26 +00001235}
1236
Chris Lattner33793202007-08-31 22:09:40 +00001237Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001238 CodeGenFunction::StmtExprEvaluation eval(CGF);
1239 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1240 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001241}
1242
Chris Lattner7f02f722007-08-24 05:35:26 +00001243//===----------------------------------------------------------------------===//
1244// Unary Operators
1245//===----------------------------------------------------------------------===//
1246
Chris Lattner8c11a652010-06-26 22:09:34 +00001247llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001248EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1249 llvm::Value *InVal,
1250 llvm::Value *NextVal, bool IsInc) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001251 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00001252 case LangOptions::SOB_Defined:
1253 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
Richard Smith9d3e2262012-08-25 00:32:28 +00001254 case LangOptions::SOB_Undefined:
1255 if (!CGF.CatchUndefined)
1256 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1257 // Fall through.
Anton Yartsev683564a2011-02-07 02:17:30 +00001258 case LangOptions::SOB_Trapping:
1259 BinOpInfo BinOp;
1260 BinOp.LHS = InVal;
1261 BinOp.RHS = NextVal;
1262 BinOp.Ty = E->getType();
1263 BinOp.Opcode = BO_Add;
1264 BinOp.E = E;
1265 return EmitOverflowCheckedBinOp(BinOp);
Anton Yartsev683564a2011-02-07 02:17:30 +00001266 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001267 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev683564a2011-02-07 02:17:30 +00001268}
1269
John McCall5936e332011-02-15 09:22:45 +00001270llvm::Value *
1271ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1272 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001273
John McCall5936e332011-02-15 09:22:45 +00001274 QualType type = E->getSubExpr()->getType();
John McCall545d9962011-06-25 02:11:03 +00001275 llvm::Value *value = EmitLoadOfLValue(LV);
John McCall5936e332011-02-15 09:22:45 +00001276 llvm::Value *input = value;
David Chisnall7a7ee302012-01-16 17:27:18 +00001277 llvm::PHINode *atomicPHI = 0;
Anton Yartsev683564a2011-02-07 02:17:30 +00001278
John McCall5936e332011-02-15 09:22:45 +00001279 int amount = (isInc ? 1 : -1);
1280
David Chisnall7a7ee302012-01-16 17:27:18 +00001281 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1282 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1283 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1284 Builder.CreateBr(opBB);
1285 Builder.SetInsertPoint(opBB);
1286 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1287 atomicPHI->addIncoming(value, startBB);
1288 type = atomicTy->getValueType();
1289 value = atomicPHI;
1290 }
1291
John McCall5936e332011-02-15 09:22:45 +00001292 // Special case of integer increment that we have to check first: bool++.
1293 // Due to promotion rules, we get:
1294 // bool++ -> bool = bool + 1
1295 // -> bool = (int)bool + 1
1296 // -> bool = ((int)bool + 1 != 0)
1297 // An interesting aspect of this is that increment is always true.
1298 // Decrement does not have this property.
1299 if (isInc && type->isBooleanType()) {
1300 value = Builder.getTrue();
1301
1302 // Most common case by far: integer increment.
1303 } else if (type->isIntegerType()) {
1304
Michael Liao36d5cea2012-08-28 16:55:13 +00001305 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCall5936e332011-02-15 09:22:45 +00001306
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001307 // Note that signed integer inc/dec with width less than int can't
1308 // overflow because of promotion rules; we're just eliding a few steps here.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001309 if (type->isSignedIntegerOrEnumerationType() &&
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001310 value->getType()->getPrimitiveSizeInBits() >=
John McCall913dab22011-06-25 01:32:37 +00001311 CGF.IntTy->getBitWidth())
John McCall5936e332011-02-15 09:22:45 +00001312 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
John McCall5936e332011-02-15 09:22:45 +00001313 else
1314 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1315
1316 // Next most common: pointer increment.
1317 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1318 QualType type = ptr->getPointeeType();
1319
1320 // VLA types don't have constant size.
John McCall913dab22011-06-25 01:32:37 +00001321 if (const VariableArrayType *vla
1322 = CGF.getContext().getAsVariableArrayType(type)) {
1323 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCallbc8d40d2011-06-24 21:55:10 +00001324 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
David Blaikie4e4d0842012-03-11 07:00:24 +00001325 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
John McCallbc8d40d2011-06-24 21:55:10 +00001326 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2cb42222011-03-01 00:03:48 +00001327 else
John McCallbc8d40d2011-06-24 21:55:10 +00001328 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
John McCall5936e332011-02-15 09:22:45 +00001329
1330 // Arithmetic on function pointers (!) is just +-1.
1331 } else if (type->isFunctionType()) {
Chris Lattner48431f92011-04-19 22:55:03 +00001332 llvm::Value *amt = Builder.getInt32(amount);
John McCall5936e332011-02-15 09:22:45 +00001333
1334 value = CGF.EmitCastToVoidPtr(value);
David Blaikie4e4d0842012-03-11 07:00:24 +00001335 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001336 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1337 else
1338 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001339 value = Builder.CreateBitCast(value, input->getType());
1340
1341 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001342 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001343 llvm::Value *amt = Builder.getInt32(amount);
David Blaikie4e4d0842012-03-11 07:00:24 +00001344 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001345 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1346 else
1347 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001348 }
1349
1350 // Vector increment/decrement.
1351 } else if (type->isVectorType()) {
1352 if (type->hasIntegerRepresentation()) {
1353 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1354
Eli Friedmand4b9ee32011-05-06 18:04:18 +00001355 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCall5936e332011-02-15 09:22:45 +00001356 } else {
1357 value = Builder.CreateFAdd(
1358 value,
1359 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001360 isInc ? "inc" : "dec");
1361 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001362
John McCall5936e332011-02-15 09:22:45 +00001363 // Floating point.
1364 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001365 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001366 llvm::Value *amt;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001367
1368 if (type->isHalfType()) {
1369 // Another special case: half FP increment should be done via float
1370 value =
1371 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1372 input);
1373 }
1374
John McCall5936e332011-02-15 09:22:45 +00001375 if (value->getType()->isFloatTy())
1376 amt = llvm::ConstantFP::get(VMContext,
1377 llvm::APFloat(static_cast<float>(amount)));
1378 else if (value->getType()->isDoubleTy())
1379 amt = llvm::ConstantFP::get(VMContext,
1380 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001381 else {
John McCall5936e332011-02-15 09:22:45 +00001382 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001383 bool ignored;
1384 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1385 &ignored);
John McCall5936e332011-02-15 09:22:45 +00001386 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001387 }
John McCall5936e332011-02-15 09:22:45 +00001388 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1389
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001390 if (type->isHalfType())
1391 value =
1392 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1393 value);
1394
John McCall5936e332011-02-15 09:22:45 +00001395 // Objective-C pointer types.
1396 } else {
1397 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1398 value = CGF.EmitCastToVoidPtr(value);
1399
1400 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1401 if (!isInc) size = -size;
1402 llvm::Value *sizeValue =
1403 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1404
David Blaikie4e4d0842012-03-11 07:00:24 +00001405 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001406 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1407 else
1408 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001409 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001410 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001411
1412 if (atomicPHI) {
1413 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1414 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1415 llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
1416 value, llvm::SequentiallyConsistent);
1417 atomicPHI->addIncoming(old, opBB);
1418 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1419 Builder.CreateCondBr(success, contBB, opBB);
1420 Builder.SetInsertPoint(contBB);
1421 return isPre ? value : input;
1422 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001423
Chris Lattner8c11a652010-06-26 22:09:34 +00001424 // Store the updated result through the lvalue.
1425 if (LV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001426 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001427 else
John McCall545d9962011-06-25 02:11:03 +00001428 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001429
Chris Lattner8c11a652010-06-26 22:09:34 +00001430 // If this is a postinc, return the value read from memory, otherwise use the
1431 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001432 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001433}
1434
1435
1436
Chris Lattner7f02f722007-08-24 05:35:26 +00001437Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001438 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001439 // Emit unary minus with EmitSub so we handle overflow cases etc.
1440 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001441 BinOp.RHS = Visit(E->getSubExpr());
1442
1443 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1444 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1445 else
1446 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001447 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001448 BinOp.Opcode = BO_Sub;
Chris Lattner9a207232010-06-26 21:48:21 +00001449 BinOp.E = E;
1450 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001451}
1452
1453Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001454 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001455 Value *Op = Visit(E->getSubExpr());
1456 return Builder.CreateNot(Op, "neg");
1457}
1458
1459Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00001460
1461 // Perform vector logical not on comparison with zero vector.
1462 if (E->getType()->isExtVectorType()) {
1463 Value *Oper = Visit(E->getSubExpr());
1464 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1465 Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1466 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1467 }
1468
Chris Lattner7f02f722007-08-24 05:35:26 +00001469 // Compare operand to zero.
1470 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001471
Chris Lattner7f02f722007-08-24 05:35:26 +00001472 // Invert value.
1473 // TODO: Could dynamically modify easy computations here. For example, if
1474 // the operand is an icmp ne, turn into icmp eq.
1475 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001476
Anders Carlsson9f84d882009-05-19 18:44:53 +00001477 // ZExt result to the expr type.
1478 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001479}
1480
Eli Friedman0027d2b2010-08-05 09:58:49 +00001481Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1482 // Try folding the offsetof to a constant.
Richard Smith80d4b552011-12-28 19:48:30 +00001483 llvm::APSInt Value;
1484 if (E->EvaluateAsInt(Value, CGF.getContext()))
1485 return Builder.getInt(Value);
Eli Friedman0027d2b2010-08-05 09:58:49 +00001486
1487 // Loop over the components of the offsetof to compute the value.
1488 unsigned n = E->getNumComponents();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001489 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001490 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1491 QualType CurrentType = E->getTypeSourceInfo()->getType();
1492 for (unsigned i = 0; i != n; ++i) {
1493 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001494 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001495 switch (ON.getKind()) {
1496 case OffsetOfExpr::OffsetOfNode::Array: {
1497 // Compute the index
1498 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1499 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001500 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedman0027d2b2010-08-05 09:58:49 +00001501 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1502
1503 // Save the element type
1504 CurrentType =
1505 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1506
1507 // Compute the element size
1508 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1509 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1510
1511 // Multiply out to compute the result
1512 Offset = Builder.CreateMul(Idx, ElemSize);
1513 break;
1514 }
1515
1516 case OffsetOfExpr::OffsetOfNode::Field: {
1517 FieldDecl *MemberDecl = ON.getField();
1518 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1519 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1520
1521 // Compute the index of the field in its parent.
1522 unsigned i = 0;
1523 // FIXME: It would be nice if we didn't have to loop here!
1524 for (RecordDecl::field_iterator Field = RD->field_begin(),
1525 FieldEnd = RD->field_end();
David Blaikie262bc182012-04-30 02:36:29 +00001526 Field != FieldEnd; ++Field, ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00001527 if (*Field == MemberDecl)
Eli Friedman0027d2b2010-08-05 09:58:49 +00001528 break;
1529 }
1530 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1531
1532 // Compute the offset to the field
1533 int64_t OffsetInt = RL.getFieldOffset(i) /
1534 CGF.getContext().getCharWidth();
1535 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1536
1537 // Save the element type.
1538 CurrentType = MemberDecl->getType();
1539 break;
1540 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001541
Eli Friedman0027d2b2010-08-05 09:58:49 +00001542 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001543 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001544
Eli Friedman0027d2b2010-08-05 09:58:49 +00001545 case OffsetOfExpr::OffsetOfNode::Base: {
1546 if (ON.getBase()->isVirtual()) {
1547 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1548 continue;
1549 }
1550
1551 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1552 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1553
1554 // Save the element type.
1555 CurrentType = ON.getBase()->getType();
1556
1557 // Compute the offset to the base.
1558 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1559 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001560 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1561 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001562 break;
1563 }
1564 }
1565 Result = Builder.CreateAdd(Result, Offset);
1566 }
1567 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001568}
1569
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001570/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001571/// argument of the sizeof expression as an integer.
1572Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001573ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1574 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001575 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001576 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001577 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001578 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1579 if (E->isArgumentType()) {
1580 // sizeof(type) - make sure to emit the VLA size.
John McCallbc8d40d2011-06-24 21:55:10 +00001581 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001582 } else {
1583 // C99 6.5.3.4p2: If the argument is an expression of type
1584 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001585 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001586 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001587
John McCallbc8d40d2011-06-24 21:55:10 +00001588 QualType eltType;
1589 llvm::Value *numElts;
1590 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1591
1592 llvm::Value *size = numElts;
1593
1594 // Scale the number of non-VLA elements by the non-VLA element size.
1595 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1596 if (!eltSize.isOne())
1597 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1598
1599 return size;
Anders Carlssonb50525b2008-12-21 03:33:21 +00001600 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001601 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001602
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001603 // If this isn't sizeof(vla), the result must be constant; use the constant
1604 // folding logic so we don't have to duplicate it here.
Richard Smith80d4b552011-12-28 19:48:30 +00001605 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001606}
1607
Chris Lattner46f93d02007-08-24 21:20:17 +00001608Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1609 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001610 if (Op->getType()->isAnyComplexType()) {
1611 // If it's an l-value, load through the appropriate subobject l-value.
1612 // Note that we have to ask E because Op might be an l-value that
1613 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001614 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001615 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001616
1617 // Otherwise, calculate and project.
1618 return CGF.EmitComplexExpr(Op, false, true).first;
1619 }
1620
Chris Lattner46f93d02007-08-24 21:20:17 +00001621 return Visit(Op);
1622}
John McCallb418d742010-11-16 10:08:07 +00001623
Chris Lattner46f93d02007-08-24 21:20:17 +00001624Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1625 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001626 if (Op->getType()->isAnyComplexType()) {
1627 // If it's an l-value, load through the appropriate subobject l-value.
1628 // Note that we have to ask E because Op might be an l-value that
1629 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001630 if (Op->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001631 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001632
1633 // Otherwise, calculate and project.
1634 return CGF.EmitComplexExpr(Op, true, false).second;
1635 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001636
Mike Stump7f79f9b2009-05-29 15:46:01 +00001637 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1638 // effects are evaluated, but not the actual value.
Richard Smithdfb80de2012-02-18 20:53:32 +00001639 if (Op->isGLValue())
1640 CGF.EmitLValue(Op);
1641 else
1642 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001643 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001644}
1645
Chris Lattner7f02f722007-08-24 05:35:26 +00001646//===----------------------------------------------------------------------===//
1647// Binary Operators
1648//===----------------------------------------------------------------------===//
1649
1650BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001651 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001652 BinOpInfo Result;
1653 Result.LHS = Visit(E->getLHS());
1654 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001655 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001656 Result.Opcode = E->getOpcode();
Chris Lattner7f02f722007-08-24 05:35:26 +00001657 Result.E = E;
1658 return Result;
1659}
1660
Douglas Gregor6a03e342010-04-23 04:16:32 +00001661LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1662 const CompoundAssignOperator *E,
1663 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001664 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001665 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001666 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001667
Eli Friedmanab3a8522009-03-28 01:22:36 +00001668 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001669 // This needs to go through the complex expression emitter, but it's a tad
1670 // complicated to do that... I'm leaving it out for now. (Note that we do
1671 // actually need the imaginary part of the RHS for multiplication and
1672 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001673 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001674 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001675 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001676 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001677
Mike Stumpcc0442f2009-05-22 19:07:20 +00001678 // Emit the RHS first. __block variables need to have the rhs evaluated
1679 // first, plus this should improve codegen a little.
1680 OpInfo.RHS = Visit(E->getRHS());
1681 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001682 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001683 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001684 // Load/convert the LHS.
Richard Smith7ac9ef12012-09-08 02:08:36 +00001685 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall545d9962011-06-25 02:11:03 +00001686 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
David Chisnall7a7ee302012-01-16 17:27:18 +00001687
1688 llvm::PHINode *atomicPHI = 0;
Eli Friedman860a3192012-06-16 02:19:17 +00001689 if (LHSTy->isAtomicType()) {
David Chisnall7a7ee302012-01-16 17:27:18 +00001690 // FIXME: For floating point types, we should be saving and restoring the
1691 // floating point environment in the loop.
1692 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1693 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1694 Builder.CreateBr(opBB);
1695 Builder.SetInsertPoint(opBB);
1696 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
1697 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00001698 OpInfo.LHS = atomicPHI;
1699 }
Eli Friedman860a3192012-06-16 02:19:17 +00001700
1701 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1702 E->getComputationLHSType());
1703
Chris Lattner1f1ded92007-08-24 21:00:35 +00001704 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001705 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001706
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001707 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001708 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
David Chisnall7a7ee302012-01-16 17:27:18 +00001709
1710 if (atomicPHI) {
1711 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1712 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1713 llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
1714 Result, llvm::SequentiallyConsistent);
1715 atomicPHI->addIncoming(old, opBB);
1716 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1717 Builder.CreateCondBr(success, contBB, opBB);
1718 Builder.SetInsertPoint(contBB);
1719 return LHSLV;
1720 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001721
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001722 // Store the result value into the LHS lvalue. Bit-fields are handled
1723 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1724 // 'An assignment expression has the value of the left operand after the
1725 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001726 if (LHSLV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001727 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001728 else
John McCall545d9962011-06-25 02:11:03 +00001729 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001730
Douglas Gregor6a03e342010-04-23 04:16:32 +00001731 return LHSLV;
1732}
1733
1734Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1735 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1736 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001737 Value *RHS;
1738 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1739
1740 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001741 if (Ignore)
1742 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001743
John McCallb418d742010-11-16 10:08:07 +00001744 // The result of an assignment in C is the assigned r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00001745 if (!CGF.getContext().getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00001746 return RHS;
1747
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001748 // If the lvalue is non-volatile, return the computed value of the assignment.
1749 if (!LHS.isVolatileQualified())
1750 return RHS;
1751
1752 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00001753 return EmitLoadOfLValue(LHS);
Chris Lattner1f1ded92007-08-24 21:00:35 +00001754}
1755
Chris Lattner80230302010-09-11 21:47:09 +00001756void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith7ac9ef12012-09-08 02:08:36 +00001757 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001758 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
Chris Lattner80230302010-09-11 21:47:09 +00001759
1760 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1761 llvm::Value *IntMin =
Chris Lattner48431f92011-04-19 22:55:03 +00001762 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner80230302010-09-11 21:47:09 +00001763 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1764
Richard Smith7ac9ef12012-09-08 02:08:36 +00001765 llvm::Value *Cond1 = Builder.CreateICmpNE(Ops.RHS, Zero);
1766 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
1767 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
1768 llvm::Value *Cond2 = Builder.CreateOr(LHSCmp, RHSCmp, "or");
1769 CGF.EmitCheck(Builder.CreateAnd(Cond1, Cond2, "and"));
Chris Lattner80230302010-09-11 21:47:09 +00001770 } else {
Richard Smith7ac9ef12012-09-08 02:08:36 +00001771 CGF.EmitCheck(Builder.CreateICmpNE(Ops.RHS, Zero));
Chris Lattner80230302010-09-11 21:47:09 +00001772 }
Chris Lattner80230302010-09-11 21:47:09 +00001773}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001774
Chris Lattner7f02f722007-08-24 05:35:26 +00001775Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Richard Smith7ac9ef12012-09-08 02:08:36 +00001776 if (isTrapvOverflowBehavior()) {
Chris Lattner80230302010-09-11 21:47:09 +00001777 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1778
1779 if (Ops.Ty->isIntegerType())
1780 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
Richard Smith7ac9ef12012-09-08 02:08:36 +00001781 else if (Ops.Ty->isRealFloatingType())
1782 CGF.EmitCheck(Builder.CreateFCmpUNE(Ops.RHS, Zero));
Chris Lattner80230302010-09-11 21:47:09 +00001783 }
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001784 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
1785 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
David Blaikie4e4d0842012-03-11 07:00:24 +00001786 if (CGF.getContext().getLangOpts().OpenCL) {
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001787 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
1788 llvm::Type *ValTy = Val->getType();
1789 if (ValTy->isFloatTy() ||
1790 (isa<llvm::VectorType>(ValTy) &&
1791 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sands82500162012-04-10 08:23:07 +00001792 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001793 }
1794 return Val;
1795 }
Douglas Gregorf6094622010-07-23 15:58:24 +00001796 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001797 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1798 else
1799 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1800}
1801
1802Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1803 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner80230302010-09-11 21:47:09 +00001804 if (isTrapvOverflowBehavior()) {
1805 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1806
1807 if (Ops.Ty->isIntegerType())
1808 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1809 }
1810
Eli Friedman52d68742011-04-10 04:44:11 +00001811 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001812 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1813 else
1814 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1815}
1816
Mike Stump2add4732009-04-01 20:28:16 +00001817Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1818 unsigned IID;
1819 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001820
Chris Lattner9a207232010-06-26 21:48:21 +00001821 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001822 case BO_Add:
1823 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001824 OpID = 1;
1825 IID = llvm::Intrinsic::sadd_with_overflow;
1826 break;
John McCall2de56d12010-08-25 11:45:40 +00001827 case BO_Sub:
1828 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001829 OpID = 2;
1830 IID = llvm::Intrinsic::ssub_with_overflow;
1831 break;
John McCall2de56d12010-08-25 11:45:40 +00001832 case BO_Mul:
1833 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001834 OpID = 3;
1835 IID = llvm::Intrinsic::smul_with_overflow;
1836 break;
1837 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001838 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump2add4732009-04-01 20:28:16 +00001839 }
Mike Stump035cf892009-04-02 18:15:54 +00001840 OpID <<= 1;
1841 OpID |= 1;
1842
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001843 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump2add4732009-04-01 20:28:16 +00001844
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00001845 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump2add4732009-04-01 20:28:16 +00001846
1847 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1848 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1849 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1850
Richard Smith7ac9ef12012-09-08 02:08:36 +00001851 // Handle overflow with llvm.trap if no custom handler has been specified.
1852 const std::string *handlerName =
1853 &CGF.getContext().getLangOpts().OverflowHandler;
1854 if (handlerName->empty()) {
1855 CGF.EmitCheck(Builder.CreateNot(overflow));
1856 return result;
1857 }
1858
Mike Stump2add4732009-04-01 20:28:16 +00001859 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00001860 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendling14ef3192011-07-07 21:13:10 +00001861 llvm::Function::iterator insertPt = initialBB;
1862 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
1863 llvm::next(insertPt));
Chris Lattner93a00352010-08-07 00:20:46 +00001864 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001865
1866 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1867
David Chisnall7f18e672010-09-17 18:29:54 +00001868 // If an overflow handler is set, then we want to call it and then use its
1869 // result, if it returns.
1870 Builder.SetInsertPoint(overflowBB);
1871
1872 // Get the overflow handler.
Chris Lattner8b418682012-02-07 00:39:47 +00001873 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001874 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnall7f18e672010-09-17 18:29:54 +00001875 llvm::FunctionType *handlerTy =
1876 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1877 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1878
1879 // Sign extend the args to 64-bit, so that we can use the same handler for
1880 // all types of overflow.
1881 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1882 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1883
1884 // Call the handler with the two arguments, the operation, and the size of
1885 // the result.
1886 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1887 Builder.getInt8(OpID),
1888 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1889
1890 // Truncate the result back to the desired size.
1891 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1892 Builder.CreateBr(continueBB);
1893
Mike Stump2add4732009-04-01 20:28:16 +00001894 Builder.SetInsertPoint(continueBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001895 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnall7f18e672010-09-17 18:29:54 +00001896 phi->addIncoming(result, initialBB);
1897 phi->addIncoming(handlerResult, overflowBB);
1898
1899 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00001900}
Chris Lattner7f02f722007-08-24 05:35:26 +00001901
John McCall913dab22011-06-25 01:32:37 +00001902/// Emit pointer + index arithmetic.
1903static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1904 const BinOpInfo &op,
1905 bool isSubtraction) {
1906 // Must have binary (not unary) expr here. Unary pointer
1907 // increment/decrement doesn't use this path.
1908 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1909
1910 Value *pointer = op.LHS;
1911 Expr *pointerOperand = expr->getLHS();
1912 Value *index = op.RHS;
1913 Expr *indexOperand = expr->getRHS();
1914
1915 // In a subtraction, the LHS is always the pointer.
1916 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1917 std::swap(pointer, index);
1918 std::swap(pointerOperand, indexOperand);
1919 }
1920
1921 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1922 if (width != CGF.PointerWidthInBits) {
1923 // Zero-extend or sign-extend the pointer value according to
1924 // whether the index is signed or not.
1925 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1926 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1927 "idx.ext");
1928 }
1929
1930 // If this is subtraction, negate the index.
1931 if (isSubtraction)
1932 index = CGF.Builder.CreateNeg(index, "idx.neg");
1933
1934 const PointerType *pointerType
1935 = pointerOperand->getType()->getAs<PointerType>();
1936 if (!pointerType) {
1937 QualType objectType = pointerOperand->getType()
1938 ->castAs<ObjCObjectPointerType>()
1939 ->getPointeeType();
1940 llvm::Value *objectSize
1941 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1942
1943 index = CGF.Builder.CreateMul(index, objectSize);
1944
1945 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1946 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1947 return CGF.Builder.CreateBitCast(result, pointer->getType());
1948 }
1949
1950 QualType elementType = pointerType->getPointeeType();
1951 if (const VariableArrayType *vla
1952 = CGF.getContext().getAsVariableArrayType(elementType)) {
1953 // The element count here is the total number of non-VLA elements.
1954 llvm::Value *numElements = CGF.getVLASize(vla).first;
1955
1956 // Effectively, the multiply by the VLA size is part of the GEP.
1957 // GEP indexes are signed, and scaling an index isn't permitted to
1958 // signed-overflow, so we use the same semantics for our explicit
1959 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +00001960 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall913dab22011-06-25 01:32:37 +00001961 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
1962 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1963 } else {
1964 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
1965 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattnera4d71452010-06-26 21:25:03 +00001966 }
John McCall913dab22011-06-25 01:32:37 +00001967 return pointer;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001968 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001969
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001970 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1971 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1972 // future proof.
John McCall913dab22011-06-25 01:32:37 +00001973 if (elementType->isVoidType() || elementType->isFunctionType()) {
1974 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1975 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1976 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001977 }
1978
David Blaikie4e4d0842012-03-11 07:00:24 +00001979 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall913dab22011-06-25 01:32:37 +00001980 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1981
1982 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001983}
1984
John McCall913dab22011-06-25 01:32:37 +00001985Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
1986 if (op.LHS->getType()->isPointerTy() ||
1987 op.RHS->getType()->isPointerTy())
1988 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
1989
1990 if (op.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001991 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
John McCall913dab22011-06-25 01:32:37 +00001992 case LangOptions::SOB_Defined:
1993 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith9d3e2262012-08-25 00:32:28 +00001994 case LangOptions::SOB_Undefined:
1995 if (!CGF.CatchUndefined)
1996 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
1997 // Fall through.
John McCall913dab22011-06-25 01:32:37 +00001998 case LangOptions::SOB_Trapping:
1999 return EmitOverflowCheckedBinOp(op);
2000 }
2001 }
2002
2003 if (op.LHS->getType()->isFPOrFPVectorTy())
2004 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
2005
2006 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2007}
2008
2009Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2010 // The LHS is always a pointer if either side is.
2011 if (!op.LHS->getType()->isPointerTy()) {
2012 if (op.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002013 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00002014 case LangOptions::SOB_Defined:
John McCall913dab22011-06-25 01:32:37 +00002015 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith9d3e2262012-08-25 00:32:28 +00002016 case LangOptions::SOB_Undefined:
2017 if (!CGF.CatchUndefined)
2018 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2019 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +00002020 case LangOptions::SOB_Trapping:
John McCall913dab22011-06-25 01:32:37 +00002021 return EmitOverflowCheckedBinOp(op);
Chris Lattnera4d71452010-06-26 21:25:03 +00002022 }
2023 }
2024
John McCall913dab22011-06-25 01:32:37 +00002025 if (op.LHS->getType()->isFPOrFPVectorTy())
2026 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Chris Lattner2eb91e42010-03-29 17:28:16 +00002027
John McCall913dab22011-06-25 01:32:37 +00002028 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00002029 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00002030
John McCall913dab22011-06-25 01:32:37 +00002031 // If the RHS is not a pointer, then we have normal pointer
2032 // arithmetic.
2033 if (!op.RHS->getType()->isPointerTy())
2034 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmandaa24a22009-03-28 02:45:41 +00002035
John McCall913dab22011-06-25 01:32:37 +00002036 // Otherwise, this is a pointer subtraction.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00002037
John McCall913dab22011-06-25 01:32:37 +00002038 // Do the raw subtraction part.
2039 llvm::Value *LHS
2040 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2041 llvm::Value *RHS
2042 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2043 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar2a866252009-04-25 05:08:32 +00002044
John McCall913dab22011-06-25 01:32:37 +00002045 // Okay, figure out the element size.
2046 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2047 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002048
John McCall913dab22011-06-25 01:32:37 +00002049 llvm::Value *divisor = 0;
2050
2051 // For a variable-length array, this is going to be non-constant.
2052 if (const VariableArrayType *vla
2053 = CGF.getContext().getAsVariableArrayType(elementType)) {
2054 llvm::Value *numElements;
2055 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2056
2057 divisor = numElements;
2058
2059 // Scale the number of non-VLA elements by the non-VLA element size.
2060 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2061 if (!eltSize.isOne())
2062 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2063
2064 // For everything elese, we can just compute it, safe in the
2065 // assumption that Sema won't let anything through that we can't
2066 // safely compute the size of.
2067 } else {
2068 CharUnits elementSize;
2069 // Handle GCC extension for pointer arithmetic on void* and
2070 // function pointer types.
2071 if (elementType->isVoidType() || elementType->isFunctionType())
2072 elementSize = CharUnits::One();
2073 else
2074 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2075
2076 // Don't even emit the divide for element size of 1.
2077 if (elementSize.isOne())
2078 return diffInChars;
2079
2080 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner7f02f722007-08-24 05:35:26 +00002081 }
Chris Lattner2cb42222011-03-01 00:03:48 +00002082
Chris Lattner2cb42222011-03-01 00:03:48 +00002083 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2084 // pointer difference in C is only defined in the case where both operands
2085 // are pointing to elements of an array.
John McCall913dab22011-06-25 01:32:37 +00002086 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002087}
2088
2089Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2090 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2091 // RHS to the same size as the LHS.
2092 Value *RHS = Ops.RHS;
2093 if (Ops.LHS->getType() != RHS->getType())
2094 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002095
Richard Smith9d3e2262012-08-25 00:32:28 +00002096 if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
Mike Stumpbe07f602009-12-14 21:58:14 +00002097 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
Richard Smith9d3e2262012-08-25 00:32:28 +00002098 llvm::Value *WidthMinusOne =
Richard Smith5b092ef2012-08-25 05:43:00 +00002099 llvm::ConstantInt::get(RHS->getType(), Width - 1);
Richard Smith7ac9ef12012-09-08 02:08:36 +00002100 CGF.EmitCheck(Builder.CreateICmpULE(RHS, WidthMinusOne));
Richard Smith9d3e2262012-08-25 00:32:28 +00002101
2102 if (Ops.Ty->hasSignedIntegerRepresentation()) {
2103 // Check whether we are shifting any non-zero bits off the top of the
2104 // integer.
Richard Smith9d3e2262012-08-25 00:32:28 +00002105 llvm::Value *BitsShiftedOff =
2106 Builder.CreateLShr(Ops.LHS,
2107 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2108 /*NUW*/true, /*NSW*/true),
2109 "shl.check");
2110 if (CGF.getLangOpts().CPlusPlus) {
2111 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2112 // Under C++11's rules, shifting a 1 bit into the sign bit is
2113 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2114 // define signed left shifts, so we use the C99 and C++11 rules there).
2115 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2116 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2117 }
2118 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Richard Smith7ac9ef12012-09-08 02:08:36 +00002119 CGF.EmitCheck(Builder.CreateICmpEQ(BitsShiftedOff, Zero));
Richard Smith9d3e2262012-08-25 00:32:28 +00002120 }
Mike Stumpbe07f602009-12-14 21:58:14 +00002121 }
2122
Chris Lattner7f02f722007-08-24 05:35:26 +00002123 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2124}
2125
2126Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2127 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2128 // RHS to the same size as the LHS.
2129 Value *RHS = Ops.RHS;
2130 if (Ops.LHS->getType() != RHS->getType())
2131 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002132
Richard Smith9d3e2262012-08-25 00:32:28 +00002133 if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
Mike Stumpbe07f602009-12-14 21:58:14 +00002134 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
Richard Smith7ac9ef12012-09-08 02:08:36 +00002135 llvm::Value *WidthVal = llvm::ConstantInt::get(RHS->getType(), Width);
2136 CGF.EmitCheck(Builder.CreateICmpULT(RHS, WidthVal));
Mike Stumpbe07f602009-12-14 21:58:14 +00002137 }
2138
Douglas Gregorf6094622010-07-23 15:58:24 +00002139 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002140 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2141 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2142}
2143
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002144enum IntrinsicType { VCMPEQ, VCMPGT };
2145// return corresponding comparison intrinsic for given vector type
2146static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2147 BuiltinType::Kind ElemKind) {
2148 switch (ElemKind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002149 default: llvm_unreachable("unexpected element type");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002150 case BuiltinType::Char_U:
2151 case BuiltinType::UChar:
2152 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2153 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002154 case BuiltinType::Char_S:
2155 case BuiltinType::SChar:
2156 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2157 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002158 case BuiltinType::UShort:
2159 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2160 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002161 case BuiltinType::Short:
2162 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2163 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002164 case BuiltinType::UInt:
2165 case BuiltinType::ULong:
2166 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2167 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002168 case BuiltinType::Int:
2169 case BuiltinType::Long:
2170 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2171 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002172 case BuiltinType::Float:
2173 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2174 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002175 }
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002176}
2177
Chris Lattner7f02f722007-08-24 05:35:26 +00002178Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2179 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002180 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002181 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002182 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002183 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002184 assert(E->getOpcode() == BO_EQ ||
2185 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002186 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2187 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002188 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002189 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002190 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002191 Value *LHS = Visit(E->getLHS());
2192 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002193
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002194 // If AltiVec, the comparison results in a numeric type, so we use
2195 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002196 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002197 // constants for mapping CR6 register bits to predicate result
2198 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2199
2200 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2201
2202 // in several cases vector arguments order will be reversed
2203 Value *FirstVecArg = LHS,
2204 *SecondVecArg = RHS;
2205
2206 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002207 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002208 BuiltinType::Kind ElementKind = BTy->getKind();
2209
2210 switch(E->getOpcode()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002211 default: llvm_unreachable("is not a comparison operation");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002212 case BO_EQ:
2213 CR6 = CR6_LT;
2214 ID = GetIntrinsic(VCMPEQ, ElementKind);
2215 break;
2216 case BO_NE:
2217 CR6 = CR6_EQ;
2218 ID = GetIntrinsic(VCMPEQ, ElementKind);
2219 break;
2220 case BO_LT:
2221 CR6 = CR6_LT;
2222 ID = GetIntrinsic(VCMPGT, ElementKind);
2223 std::swap(FirstVecArg, SecondVecArg);
2224 break;
2225 case BO_GT:
2226 CR6 = CR6_LT;
2227 ID = GetIntrinsic(VCMPGT, ElementKind);
2228 break;
2229 case BO_LE:
2230 if (ElementKind == BuiltinType::Float) {
2231 CR6 = CR6_LT;
2232 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2233 std::swap(FirstVecArg, SecondVecArg);
2234 }
2235 else {
2236 CR6 = CR6_EQ;
2237 ID = GetIntrinsic(VCMPGT, ElementKind);
2238 }
2239 break;
2240 case BO_GE:
2241 if (ElementKind == BuiltinType::Float) {
2242 CR6 = CR6_LT;
2243 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2244 }
2245 else {
2246 CR6 = CR6_EQ;
2247 ID = GetIntrinsic(VCMPGT, ElementKind);
2248 std::swap(FirstVecArg, SecondVecArg);
2249 }
2250 break;
2251 }
2252
Chris Lattner48431f92011-04-19 22:55:03 +00002253 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002254 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2255 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2256 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2257 }
2258
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002259 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002260 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002261 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002262 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002263 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002264 LHS, RHS, "cmp");
2265 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002266 // Unsigned integers and pointers.
2267 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002268 LHS, RHS, "cmp");
2269 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002270
2271 // If this is a vector comparison, sign extend the result to the appropriate
2272 // vector integer type and return it (don't convert to bool).
2273 if (LHSTy->isVectorType())
2274 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002275
Chris Lattner7f02f722007-08-24 05:35:26 +00002276 } else {
2277 // Complex Comparison: can only be an equality comparison.
2278 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2279 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002280
John McCall183700f2009-09-21 23:43:11 +00002281 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002282
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002283 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002284 if (CETy->isRealFloatingType()) {
2285 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2286 LHS.first, RHS.first, "cmp.r");
2287 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2288 LHS.second, RHS.second, "cmp.i");
2289 } else {
2290 // Complex comparisons can only be equality comparisons. As such, signed
2291 // and unsigned opcodes are the same.
2292 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2293 LHS.first, RHS.first, "cmp.r");
2294 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2295 LHS.second, RHS.second, "cmp.i");
2296 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002297
John McCall2de56d12010-08-25 11:45:40 +00002298 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002299 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2300 } else {
John McCall2de56d12010-08-25 11:45:40 +00002301 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002302 "Complex comparison other than == or != ?");
2303 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2304 }
2305 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002306
2307 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002308}
2309
2310Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002311 bool Ignore = TestAndClearIgnoreResultAssign();
2312
John McCallf85e1932011-06-15 23:02:42 +00002313 Value *RHS;
2314 LValue LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002315
John McCallf85e1932011-06-15 23:02:42 +00002316 switch (E->getLHS()->getType().getObjCLifetime()) {
2317 case Qualifiers::OCL_Strong:
2318 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2319 break;
2320
2321 case Qualifiers::OCL_Autoreleasing:
2322 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2323 break;
2324
2325 case Qualifiers::OCL_Weak:
2326 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002327 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002328 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2329 break;
2330
2331 // No reason to do any of these differently.
2332 case Qualifiers::OCL_None:
2333 case Qualifiers::OCL_ExplicitNone:
2334 // __block variables need to have the rhs evaluated first, plus
2335 // this should improve codegen just a little.
2336 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002337 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002338
2339 // Store the value into the LHS. Bit-fields are handled specially
2340 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2341 // 'An assignment expression has the value of the left operand after
2342 // the assignment...'.
2343 if (LHS.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002344 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCallf85e1932011-06-15 23:02:42 +00002345 else
John McCall545d9962011-06-25 02:11:03 +00002346 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCallf85e1932011-06-15 23:02:42 +00002347 }
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002348
2349 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002350 if (Ignore)
2351 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002352
John McCallb418d742010-11-16 10:08:07 +00002353 // The result of an assignment in C is the assigned r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002354 if (!CGF.getContext().getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00002355 return RHS;
2356
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002357 // If the lvalue is non-volatile, return the computed value of the assignment.
2358 if (!LHS.isVolatileQualified())
2359 return RHS;
2360
2361 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00002362 return EmitLoadOfLValue(LHS);
Chris Lattner7f02f722007-08-24 05:35:26 +00002363}
2364
2365Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002366
2367 // Perform vector logical and on comparisons with zero vectors.
2368 if (E->getType()->isVectorType()) {
2369 Value *LHS = Visit(E->getLHS());
2370 Value *RHS = Visit(E->getRHS());
2371 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2372 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2373 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2374 Value *And = Builder.CreateAnd(LHS, RHS);
2375 return Builder.CreateSExt(And, Zero->getType(), "sext");
2376 }
2377
Chris Lattner2acc6e32011-07-18 04:24:23 +00002378 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002379
Chris Lattner20eb09d2008-11-12 08:26:50 +00002380 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2381 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002382 bool LHSCondVal;
2383 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2384 if (LHSCondVal) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002385 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002386 // ZExt result to int or bool.
2387 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002388 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002389
Chris Lattner7804bcb2009-10-17 04:24:20 +00002390 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002391 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002392 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002393 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002394
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002395 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2396 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002397
John McCall150b4622011-01-26 04:00:11 +00002398 CodeGenFunction::ConditionalEvaluation eval(CGF);
2399
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002400 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2401 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2402
2403 // Any edges into the ContBlock are now from an (indeterminate number of)
2404 // edges from this first condition. All of these values will be false. Start
2405 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002406 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002407 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002408 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2409 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002410 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002411
John McCall150b4622011-01-26 04:00:11 +00002412 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002413 CGF.EmitBlock(RHSBlock);
2414 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002415 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002416
Chris Lattner7f02f722007-08-24 05:35:26 +00002417 // Reaquire the RHS block, as there may be subblocks inserted.
2418 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002419
2420 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2421 // into the phi node for the edge with the value of RHSCond.
Devang Patelacd72362011-03-30 00:08:31 +00002422 if (CGF.getDebugInfo())
2423 // There is no need to emit line number for unconditional branch.
2424 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Chris Lattner7f02f722007-08-24 05:35:26 +00002425 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002426 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002427
Chris Lattner7f02f722007-08-24 05:35:26 +00002428 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002429 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002430}
2431
2432Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002433
2434 // Perform vector logical or on comparisons with zero vectors.
2435 if (E->getType()->isVectorType()) {
2436 Value *LHS = Visit(E->getLHS());
2437 Value *RHS = Visit(E->getRHS());
2438 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2439 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2440 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2441 Value *Or = Builder.CreateOr(LHS, RHS);
2442 return Builder.CreateSExt(Or, Zero->getType(), "sext");
2443 }
2444
Chris Lattner2acc6e32011-07-18 04:24:23 +00002445 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002446
Chris Lattner20eb09d2008-11-12 08:26:50 +00002447 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2448 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002449 bool LHSCondVal;
2450 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2451 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002452 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002453 // ZExt result to int or bool.
2454 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002455 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002456
Chris Lattner7804bcb2009-10-17 04:24:20 +00002457 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002458 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002459 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002460 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002461
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002462 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2463 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002464
John McCall150b4622011-01-26 04:00:11 +00002465 CodeGenFunction::ConditionalEvaluation eval(CGF);
2466
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002467 // Branch on the LHS first. If it is true, go to the success (cont) block.
2468 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2469
2470 // Any edges into the ContBlock are now from an (indeterminate number of)
2471 // edges from this first condition. All of these values will be true. Start
2472 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002473 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002474 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002475 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2476 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002477 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002478
John McCall150b4622011-01-26 04:00:11 +00002479 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002480
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002481 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002482 CGF.EmitBlock(RHSBlock);
2483 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002484
John McCall150b4622011-01-26 04:00:11 +00002485 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002486
Chris Lattner7f02f722007-08-24 05:35:26 +00002487 // Reaquire the RHS block, as there may be subblocks inserted.
2488 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002489
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002490 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2491 // into the phi node for the edge with the value of RHSCond.
2492 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002493 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002494
Chris Lattner7f02f722007-08-24 05:35:26 +00002495 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002496 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002497}
2498
2499Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002500 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002501 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002502 return Visit(E->getRHS());
2503}
2504
2505//===----------------------------------------------------------------------===//
2506// Other Operators
2507//===----------------------------------------------------------------------===//
2508
Chris Lattner9802a512008-11-12 08:55:54 +00002509/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2510/// expression is cheap enough and side-effect-free enough to evaluate
2511/// unconditionally instead of conditionally. This is used to convert control
2512/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002513static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2514 CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002515 E = E->IgnoreParens();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002516
Chris Lattnerc6bea672011-04-16 23:15:35 +00002517 // Anything that is an integer or floating point constant is fine.
2518 if (E->isConstantInitializer(CGF.getContext(), false))
Chris Lattner9802a512008-11-12 08:55:54 +00002519 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002520
Chris Lattner9802a512008-11-12 08:55:54 +00002521 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2522 // X and Y are local variables.
2523 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2524 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002525 if (VD->hasLocalStorage() && !(CGF.getContext()
2526 .getCanonicalType(VD->getType())
2527 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002528 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002529
Chris Lattner9802a512008-11-12 08:55:54 +00002530 return false;
2531}
2532
2533
Chris Lattner7f02f722007-08-24 05:35:26 +00002534Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00002535VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002536 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00002537
2538 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +00002539 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCall56ca35d2011-02-17 10:25:35 +00002540
2541 Expr *condExpr = E->getCond();
2542 Expr *lhsExpr = E->getTrueExpr();
2543 Expr *rhsExpr = E->getFalseExpr();
2544
Chris Lattner31a09842008-11-12 08:04:58 +00002545 // If the condition constant folds and can be elided, try to avoid emitting
2546 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002547 bool CondExprBool;
2548 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00002549 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00002550 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002551
Eli Friedmanc8645e32011-10-15 02:10:40 +00002552 // If the dead side doesn't have labels we need, just emit the Live part.
2553 if (!CGF.ContainsLabel(dead)) {
2554 Value *Result = Visit(live);
2555
2556 // If the live part is a throw expression, it acts like it has a void
2557 // type, so evaluating it returns a null Value*. However, a conditional
2558 // with non-void type must return a non-null Value*.
2559 if (!Result && !E->getType()->isVoidType())
2560 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
2561
2562 return Result;
2563 }
Chris Lattnerc657e922008-11-11 18:56:45 +00002564 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002565
Nate Begeman6155d732010-09-20 22:41:17 +00002566 // OpenCL: If the condition is a vector, we can treat this condition like
2567 // the select function.
David Blaikie4e4d0842012-03-11 07:00:24 +00002568 if (CGF.getContext().getLangOpts().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00002569 && condExpr->getType()->isVectorType()) {
2570 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2571 llvm::Value *LHS = Visit(lhsExpr);
2572 llvm::Value *RHS = Visit(rhsExpr);
Nate Begeman6155d732010-09-20 22:41:17 +00002573
Chris Lattner2acc6e32011-07-18 04:24:23 +00002574 llvm::Type *condType = ConvertType(condExpr->getType());
2575 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Nate Begeman6155d732010-09-20 22:41:17 +00002576
2577 unsigned numElem = vecTy->getNumElements();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002578 llvm::Type *elemType = vecTy->getElementType();
Nate Begeman6155d732010-09-20 22:41:17 +00002579
Chris Lattner2ce88422012-01-25 05:34:41 +00002580 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begeman6155d732010-09-20 22:41:17 +00002581 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2582 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2583 llvm::VectorType::get(elemType,
2584 numElem),
2585 "sext");
2586 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2587
2588 // Cast float to int to perform ANDs if necessary.
2589 llvm::Value *RHSTmp = RHS;
2590 llvm::Value *LHSTmp = LHS;
2591 bool wasCast = false;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002592 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourne565204d2012-05-29 00:35:18 +00002593 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begeman6155d732010-09-20 22:41:17 +00002594 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2595 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2596 wasCast = true;
2597 }
2598
2599 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2600 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2601 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2602 if (wasCast)
2603 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2604
2605 return tmp5;
2606 }
2607
Chris Lattner9802a512008-11-12 08:55:54 +00002608 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2609 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002610 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00002611 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2612 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2613 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2614 llvm::Value *LHS = Visit(lhsExpr);
2615 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman1e4f68c2011-12-08 22:01:56 +00002616 if (!LHS) {
2617 // If the conditional has void type, make sure we return a null Value*.
2618 assert(!RHS && "LHS and RHS types must match");
2619 return 0;
2620 }
Chris Lattner9802a512008-11-12 08:55:54 +00002621 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2622 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002623
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002624 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2625 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002626 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002627
2628 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002629 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002630
Chris Lattner7f02f722007-08-24 05:35:26 +00002631 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002632 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002633 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002634 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002635
Chris Lattner7f02f722007-08-24 05:35:26 +00002636 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002637 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002638
Chris Lattner7f02f722007-08-24 05:35:26 +00002639 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002640 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002641 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002642 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002643
John McCall150b4622011-01-26 04:00:11 +00002644 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002645 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002646
Eli Friedman48daf592009-12-07 20:25:53 +00002647 // If the LHS or RHS is a throw expression, it will be legitimately null.
2648 if (!LHS)
2649 return RHS;
2650 if (!RHS)
2651 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002652
Chris Lattner7f02f722007-08-24 05:35:26 +00002653 // Create a PHI node for the real part.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002654 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner7f02f722007-08-24 05:35:26 +00002655 PN->addIncoming(LHS, LHSBlock);
2656 PN->addIncoming(RHS, RHSBlock);
2657 return PN;
2658}
2659
2660Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002661 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002662}
2663
Chris Lattner2202bce2007-11-30 17:56:23 +00002664Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002665 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002666 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2667
2668 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002669 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002670 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2671
Mike Stump7f79f9b2009-05-29 15:46:01 +00002672 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002673 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002674}
2675
John McCall6b5a61b2011-02-07 10:33:21 +00002676Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2677 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002678}
2679
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002680Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2681 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2acc6e32011-07-18 04:24:23 +00002682 llvm::Type *DstTy = ConvertType(E->getType());
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002683
2684 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2685 // a shuffle vector instead of a bitcast.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002686 llvm::Type *SrcTy = Src->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002687 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2688 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2689 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2690 if ((numElementsDst == 3 && numElementsSrc == 4)
2691 || (numElementsDst == 4 && numElementsSrc == 3)) {
2692
2693
2694 // In the case of going from int4->float3, a bitcast is needed before
2695 // doing a shuffle.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002696 llvm::Type *srcElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002697 cast<llvm::VectorType>(SrcTy)->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002698 llvm::Type *dstElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002699 cast<llvm::VectorType>(DstTy)->getElementType();
2700
2701 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2702 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2703 // Create a float type of the same size as the source or destination.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002704 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002705 numElementsSrc);
2706
2707 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2708 }
2709
2710 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2711
Chris Lattner5f9e2722011-07-23 10:55:15 +00002712 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002713 Args.push_back(Builder.getInt32(0));
2714 Args.push_back(Builder.getInt32(1));
2715 Args.push_back(Builder.getInt32(2));
2716
2717 if (numElementsDst == 4)
Chris Lattner8b418682012-02-07 00:39:47 +00002718 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002719
2720 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2721
2722 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2723 }
2724 }
2725
2726 return Builder.CreateBitCast(Src, DstTy, "astype");
2727}
2728
Eli Friedman276b0612011-10-11 02:20:01 +00002729Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
2730 return CGF.EmitAtomicExpr(E).getScalarVal();
2731}
2732
Chris Lattner7f02f722007-08-24 05:35:26 +00002733//===----------------------------------------------------------------------===//
2734// Entry Point into this File
2735//===----------------------------------------------------------------------===//
2736
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002737/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2738/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002739Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002740 assert(E && !hasAggregateLLVMType(E->getType()) &&
2741 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002742
Devang Patel5de7a0e2011-03-07 18:29:53 +00002743 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002744 disableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002745 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stump7f79f9b2009-05-29 15:46:01 +00002746 .Visit(const_cast<Expr*>(E));
Devang Patel5de7a0e2011-03-07 18:29:53 +00002747 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002748 enableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002749 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +00002750}
Chris Lattner3707b252007-08-26 06:48:56 +00002751
2752/// EmitScalarConversion - Emit a conversion from the specified type to the
2753/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002754Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2755 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002756 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2757 "Invalid scalar expression to emit");
2758 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2759}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002760
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002761/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2762/// type to the specified destination type, where the destination type is an
2763/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002764Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2765 QualType SrcTy,
2766 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002767 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002768 "Invalid complex -> scalar conversion");
2769 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2770 DstTy);
2771}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002772
Chris Lattner8c11a652010-06-26 22:09:34 +00002773
2774llvm::Value *CodeGenFunction::
2775EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2776 bool isInc, bool isPre) {
2777 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2778}
2779
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002780LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2781 llvm::Value *V;
2782 // object->isa or (*object).isa
2783 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002784 // build Class* type
Chris Lattner2acc6e32011-07-18 04:24:23 +00002785 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002786
2787 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00002788 if (BaseExpr->isRValue()) {
Eli Friedmand71f4422011-12-19 23:03:09 +00002789 V = CreateMemTemp(E->getType(), "resval");
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002790 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2791 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002792 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
Eli Friedmand71f4422011-12-19 23:03:09 +00002793 MakeNaturalAlignAddrLValue(V, E->getType()));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002794 } else {
2795 if (E->isArrow())
2796 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2797 else
2798 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002799 }
2800
2801 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002802 ClassPtrTy = ClassPtrTy->getPointerTo();
2803 V = Builder.CreateBitCast(V, ClassPtrTy);
Eli Friedmand71f4422011-12-19 23:03:09 +00002804 return MakeNaturalAlignAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002805}
2806
Douglas Gregor6a03e342010-04-23 04:16:32 +00002807
John McCall2a416372010-12-05 02:00:02 +00002808LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00002809 const CompoundAssignOperator *E) {
2810 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002811 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002812 switch (E->getOpcode()) {
2813#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002814 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002815 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002816 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002817 COMPOUND_OP(Mul);
2818 COMPOUND_OP(Div);
2819 COMPOUND_OP(Rem);
2820 COMPOUND_OP(Add);
2821 COMPOUND_OP(Sub);
2822 COMPOUND_OP(Shl);
2823 COMPOUND_OP(Shr);
2824 COMPOUND_OP(And);
2825 COMPOUND_OP(Xor);
2826 COMPOUND_OP(Or);
2827#undef COMPOUND_OP
2828
John McCall2de56d12010-08-25 11:45:40 +00002829 case BO_PtrMemD:
2830 case BO_PtrMemI:
2831 case BO_Mul:
2832 case BO_Div:
2833 case BO_Rem:
2834 case BO_Add:
2835 case BO_Sub:
2836 case BO_Shl:
2837 case BO_Shr:
2838 case BO_LT:
2839 case BO_GT:
2840 case BO_LE:
2841 case BO_GE:
2842 case BO_EQ:
2843 case BO_NE:
2844 case BO_And:
2845 case BO_Xor:
2846 case BO_Or:
2847 case BO_LAnd:
2848 case BO_LOr:
2849 case BO_Assign:
2850 case BO_Comma:
David Blaikieb219cfc2011-09-23 05:06:16 +00002851 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor6a03e342010-04-23 04:16:32 +00002852 }
2853
2854 llvm_unreachable("Unhandled compound assignment operator");
2855}